依赖关系将非默认实体管理器注入到Symfony中的服务中 [英] Dependency Inject non-default Entity Manager into Service in Symfony
问题描述
我想从默认em更改为名为 ps的em。配置正确,在控制器中,我只需键入 $ this-> getManager(’ps’)-> getConnection(’ps');
。
I want to change from the default em to an em called 'ps'. The configuration is correct and in the controller I can simply type $this->getManager('ps')->getConnection('ps');
.
但是我想创建带有依赖项注入的服务,该服务也需要访问此连接。
However I want to create a service with dependency injection which also needs to access this connection.
<?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,从而导致错误:
As I can nowhere select the Entity Manager 'ps' it can't also load the connection 'ps', which results in an error:
SQLSTATE[42S02]: Base table or view not found: 1146 Table 'ps_xxx' doesn't exist
我可以通过某种方式将参数传递给注射?还是注入一些父对象然后调用-> getManager()
?
Can I somehow pass an argument to the injection? Or Inject somewhat of a 'parent object' to then call ->getManager()
?
推荐答案
如果您的服务类只需要连接,那么它是创建自己的连接类并注入它的最简单方法。
If your service class just needs the connection then it easiest way it make your own connection class and inject it.
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)
一切都会像以前一样工作,但是您可以获取连接
Everything will work as before but you can get the connection directly.
如果您确实需要实体管理器,则可以定义服务:
if you really do need the entity manager then you can make a service definition:
# services.yaml
AppBundle\Service\HilaService:
$entityManager: '@doctrine.orm.ps_entity_manager'
最后,如果您不想闲逛这些东西,可以注入ManagerRegistry并从中获取所需的东西。
Finally, if you don't want to fool around with any of this stuff you can inject the ManagerRegistry and pull what you need from it.
class HilaService
{
public function __construct(Doctrine\Common\Persistence\ManagerRegistry $managerRegistry)
{
$em = $managerRegistry->getManager('ps'); // or getConnection()
这篇关于依赖关系将非默认实体管理器注入到Symfony中的服务中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!