【问题标题】:Dependency Inject non-default Entity Manager into Service in Symfony将非默认实体管理器注入到 Symfony 中的服务中
【发布时间】:2018-07-27 10:53:05
【问题描述】:

我想从默认的 em 更改为名为 'ps' 的 em。配置是正确的,在控制器中我可以简单地输入$this->getManager('ps')->getConnection('ps');

但是我想创建一个依赖注入的服务,它也需要访问这个连接。

<?php
namespace AppBundle\Service;

use Doctrine\ORM\EntityManagerInterface;

class HilaService
{

    private $entityManager;
    private $connection;

    public function __construct(EntityManagerInterface $entityManager)
    {
        $this->entityManager = $entityManager;
        $this->connection = $entityManager->getConnection('ps');

    }

    public function getCategories(){
        $query = $this->connection->query(
            'SQL ....'
        );

        $r = $query->execute();
    }
}

由于我无法选择实体管理器“ps”,它也无法加载连接“ps”,这会导致错误:

SQLSTATE[42S02]: Base table or view not found: 1146 Table 'ps_xxx' doesn't exist

我能以某种方式将参数传递给注入吗?或者注入一些“父对象”然后调用-&gt;getManager()

【问题讨论】:

  • 您只需要连接吗?

标签: symfony dependency-injection


【解决方案1】:

如果您的服务类只需要连接,那么最简单的方法就是创建您自己的连接类并注入它。

namepace AppBundle\Connection;

class PsConnection extends Doctrine\DBAL\Connection
{
}

# doctrine.yaml
doctrine:
    dbal:
        connections:
            ps:
                wrapper_class: AppBundle\Connection\PsConnection

class HilaService
{
    public function __construct(AppBundle\Connection\PsConnection $conn)

一切都会像以前一样工作,但您可以直接获得连接。

如果您确实需要实体管理器,那么您可以进行服务定义:

# services.yaml
AppBundle\Service\HilaService:
    $entityManager: '@doctrine.orm.ps_entity_manager'

最后,如果你不想在这些东西上胡闹,你可以注入 ManagerRegistry 并从中提取你需要的东西。

class HilaService
{
    public function __construct(Doctrine\Common\Persistence\ManagerRegistry $managerRegistry)
    {
        $em = $managerRegistry->getManager('ps'); // or getConnection()

【讨论】:

  • 您好,感谢您的回答。很好地解释了三种方法,但第一种方法 - 确实似乎是最好的 - 对我不起作用:Cannot autowire service "AppBundle\Connection\PsConnection": argument "$params" of method "Doctrine\DBAL\Connection::__construct()" is type-hinted "array", you should configure its value explicitly.
  • 对不起。您需要将 Connection 目录添加到 services.yaml 的 exclude 部分,以防止它被 autowire 拾取。
  • @PierredeLESPINAY 有几种方法:stackoverflow.com/questions/59266372/… 我个人喜欢装饰器方法,但选择最适合您的方法。
  • 正是我正在寻找的,谢谢!我不知道这个装饰器功能,在那种情况下非常有用。
猜你喜欢
  • 2012-10-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-08-18
  • 1970-01-01
  • 2016-01-02
  • 1970-01-01
相关资源
最近更新 更多