Symfony2: get doctrine in a generic PHP class

In a Symfony2 project, when you use a controller, you can access Doctrine by calling getDoctrine() on this , getDoctrine() .:

 $this->getDoctrine(); 

That way, I can access the repository of such a Doctrine object.

Suppose you have a generic PHP class in a Symfony2 project. How can I get the doctrine? I believe there is such a service to receive it, but I do not know which one.

+4
source share
2 answers

You can register this class as service and enter any other services in it. Suppose you have GenericClass.php as follows:

 class GenericClass { public function __construct() { // some cool stuff } } 

You can register it as a service (usually in your kit Resources/config/service.yml|xml ) and enter the Doctrine entity administrator in it:

 services: my_mailer: class: Path/To/GenericClass arguments: [doctrine.orm.entity_manager] 

And he will try to add the entity administrator (default) of the GenericClass constructor. So you just need to add an argument:

 public function __construct($entityManager) { // do something awesome with entity manager } 

If you do not know what services are available in the DI container of your application, you can find out using the command line tool: php app/console container:debug and it will list all available services along with its aliases and classes.

+11
source

After checking the symfony2 docs, I figured out how to pass your service in a user-defined method to abort the default behavior.

Rewrite your configurations as follows:

 services: my_mailer: class: Path/To/GenericClass calls: - [anotherMethodName, [doctrine.orm.entity_manager]] 

So, the service is now available in another method.

 public function anotherMethodName($entityManager) { // your magic } 

The answer from Ondrej is absolutely correct, I just wanted to add this puzzle piece to this topic.

+1
source

All Articles