在服务中使用实体管理器

时间:2018-08-10 10:05:47

标签: php symfony

是否可以访问服务中的实体管理器? 尽管我认为我必须使用依赖项注入,但在symfony文档中找不到任何内容。 我正在使用symfony 4。

4 个答案:

答案 0 :(得分:1)

只需将其注入构造函数中即可:

use Doctrine\ORM\EntityManagerInterface

class YourService
{
    private $em;

    public function __construct(EntityManagerInterface $em)
    {
        $this->em = $em;
    }

    // ...
}

由于自动装配,不需要额外的配置。

答案 1 :(得分:1)

这里是注入了实体管理器的简单类的示例,您可以将其注册为服务:

namespace My\AppBundle;

use Doctrine\ORM\EntityManagerInterface;

class YourServiceName
{
    /**
     * @var EntityManagetInterface
     */
    private $em;

    public function __construct(EntityManagerInterface $em) : void
    {
        $this->em = $em;
    }

}

services.yml中:

services:
    your.service.name:
        class: My\AppBundle\YourServiceName
        arguments: [ @doctrine.orm.default_entity_manager]

答案 2 :(得分:0)

是的,

use Doctrine\Common\Persistence\ObjectManager;

public function __construct(ObjectManager $manager)
{
    $this->manager = manager;
}

答案 3 :(得分:0)

在服务中使用EntityManagerInterface并检查自动装配,否则您将需要注入