Symfony2: get Doctrine in a generic PHP class

前端 未结 2 807
抹茶落季
抹茶落季 2021-01-06 08:13

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

2条回答
  •  走了就别回头了
    2021-01-06 08:36

    You can register this class as a service and inject whatever other services into it. Suppose you have GenericClass.php as follows:

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

    You can register it as service (in your bundle's Resources/config/service.yml|xml usually) and inject Doctrine's entity manager into it:

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

    And it'll try to inject entity manager to (by default) constructor of GenericClass. So you just have to add argument for it:

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

    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:debug and it'll list all available services along with their aliases and classes.

提交回复
热议问题