-2

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?

user3440145
  • 793
  • 10
  • 34
  • If you need a parameter in an entity, maybe it should be a class constant instead. @Dezigo is right when he says "you should never inject anything into entities". But I don't like the idea with the setter. For everythings related to parameters, I suggest you to read this chapter of symfony best pratices https://symfony.com/doc/current/best_practices.html#configuration – Florian Hermann Apr 03 '20 at 09:49
  • Entities are not services. Using dependency injection configuration for entities is wrong, and won't work. – yivi Apr 03 '20 at 09:51

1 Answers1

4

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.

public function setParam1($param1) {
    $this->param1 = $param1;
}
Dezigo
  • 3,220
  • 3
  • 31
  • 39
  • I need a config parameter in the entity to provide a custom directory namer for vich uploader. Vich uploader needs a property (or getter function) providing a path. And I want my path to be dependend on a config parameter. So - what exactly should I do instead of injecting the parameters as you seem to say this is wrong in any imaginable case...? – user3440145 Apr 03 '20 at 13:43
  • in this case, don't inject anything into an entity. You need to create a new service and inject that param into it. $service = new YourService(); (in yml) $service->doSoomelogic($entity); – Dezigo Apr 07 '20 at 09:01