4

I have an entity called Container which depends on a service, DeviceService.

I currently inject it using an Entity Listener on postLoad. However this is not being injected when just creating the plain object new Container().

Should I create a ContainerFactory where I inject the service into the new object, along with the current listener, or do a smarter way exist in Symfony?

Patrick Reck
  • 329
  • 2
  • 4
  • 16
  • 5
    It's pretty bad practice to inject a service into an entity (especially when just creating a new instance and not using it for any events like postLoad). Can you explain a bit more what's the background and why you would need a Service with your Entity? – LBA Mar 07 '16 at 09:41
  • 1
    It's not a best practice to inject services into an entity. I'd review the design and try to figure out if that dependency is only for a single method on the entity. If it is, you might be able to pass that dependency when calling that method instead. – hasumedic Mar 07 '16 at 09:42
  • 1
    Sometimes it does make sense to give an entity access to a service. So yes, a ContainerFactory is what you need for creating a new object. Sometime I cheat and just add a create method to the Doctrine repository class. – Cerad Mar 07 '16 at 14:22
  • 2
    Possible duplicate of [Symfony 2.0 getting service inside entity](https://stackoverflow.com/questions/10330704/symfony-2-0-getting-service-inside-entity) – GKFX Aug 21 '18 at 18:03

1 Answers1

2

You can use Doctrine events. See : https://symfonycasts.com/screencast/api-platform-extending/post-load-listener

francoisV
  • 79
  • 3