In Symfony 5.0 I need to access parameters defined in services.yaml inside an entity. When injecting the parameter_bag in services.yaml into my entity like
App\Entity\MyEntity:
class: App\Entity\MyEntity
calls:
- [setParameterBag, ['@parameter_bag']]
It works if I create a new entity with
$myEntity = new MyEntity();
Then the parameter bag is injected by using my function setParameterBag(..) in MyEntity.php defined as follows
private $params;
public function setParameterBag(ParameterBagInterface $params) {
$this->params = $params;
}
But if the entity is loaded from the DB $this->params is null.
What is the right way (or any way) to inject the parameter bag into an entity?
This approach is wrong, you should never inject anything into entities neither parameters nor classes. Entities should store only data and should be independent of everything.
Every time when an entity is created via 'new', dependencies won't be added.
You have to call $this-get('serviceName') from you controller.
if you want to add parameter to an entity just use a setter.