In a Symfony2 project, when you use a Controller, you can access Doctrine by calling getDoctrine() on this, i.e.:
$this->getDoctrine();
In this way, I can access the repository of such a Doctrine Entity.
Suppose to have a generic PHP class in a Symfony2 project. How can I retrieve Doctrine ?
I suppose that there is such a service to get it, but I don’t know which one.
You can register this class as a service and inject whatever other services into it. Suppose you have GenericClass.php as follows:
You can register it as service (in your bundle’s
Resources/config/service.yml|xmlusually) and inject Doctrine’s entity manager into it:And it’ll try to inject entity manager to (by default) constructor of
GenericClass. So you just have to add argument for it:If you are not sure what services are available in your application’s DI container, you can find out by using command line tool:
php app/console container:debugand it’ll list all available services along with their aliases and classes.