Best practice for dependency injection in Symfony2

Before saving the entity, I need to copy and format some data to another table in my database. I want this task to run as a service. Therefore, I describe the service in config.yml

services: my_service: class: Acme\Bundle\AcmeBundle\DependencyInjections\MyService arguments: entityManager: "@doctrine.orm.entity_manager" 

I was wondering what you can call this service. The only way I can figure out is with the controller:

 $entity = new Entity($this->get('my_service')); 

Is this the best way to continue?

+4
source share
1 answer

If my understanding is good, your my_service is what you want to do before continuing with your essence. This is the service that should be called by the prePersist event.

So, I just transform this service into a doctrine listener.

 services: my_service: class: Acme\Bundle\AcmeBundle\DependencyInjections\MyService arguments: entityManager: "@doctrine.orm.entity_manager" tags: - { name: doctrine.event_listener, event: prePersist } 

In the MyService class, now you must define the prePersist method with everything you want to do.

 use Doctrine\ORM\Event\LifecycleEventArgs; class MyService { public function prePersist(LifecycleEventArgs $args) { $entity = $args->getEntity(); $entityManager = $args->getEntityManager(); (...) } } 

You can even remove the arguments to your service, as LifecycleEventArgs provides a method to get the entity manager.

Finally, you have this listener

 services: my_service: class: Acme\Bundle\AcmeBundle\DependencyInjections\MyService tags: - { name: doctrine.event_listener, event: prePersist } 

I hope the answer to your question

+7
source

Source: https://habr.com/ru/post/1381438/


All Articles