有没有一种简单的方法可以将依赖项注入(inject)到 Doctrine2 中的每个存储库实例中?
我试过听loadClassMetadata
事件并在存储库上使用 setter 注入(inject),但这自然会导致无限循环,因为调用 getRepository
在事件中触发了相同的事件。
看完Doctrine\ORM\EntityManager::getRepository
方法似乎存储库根本没有使用依赖注入(inject),而是在函数级别实例化它们:
public function getRepository($entityName)
{
$entityName = ltrim($entityName, '\\');
if (isset($this->repositories[$entityName])) {
return $this->repositories[$entityName];
}
$metadata = $this->getClassMetadata($entityName);
$customRepositoryClassName = $metadata->customRepositoryClassName;
if ($customRepositoryClassName !== null) {
$repository = new $customRepositoryClassName($this, $metadata);
} else {
$repository = new EntityRepository($this, $metadata);
}
$this->repositories[$entityName] = $repository;
return $repository;
}
有任何想法吗 ?
最佳答案
自 Symfony 3.3+ 和 2017 您可以使用服务。
而不是这里提出的其他解决方案导致:
你能行的...
Clean Way - 通过构造函数注入(inject)的依赖关系,就像在任何其他服务中一样
<?php declare(strict_types=1);
namespace App\Repository;
use App\Entity\Post;
use Doctrine\ORM\EntityManager;
use Doctrine\ORM\EntityRepository;
final class PostRepository
{
/**
* @var EntityRepository
*/
private $repository;
/**
* @var YourOwnDependency
*/
private $yourOwnDependency;
public function __construct(YourOwnDependency $YourOwnDependency, EntityManager $entityManager)
{
$this->repository = $entityManager->getRepository(Post::class);
$this->yourOwnDependency = $yourOwnDependency
}
}
在帖子中阅读更多内容
您可以在 How to use Repository with Doctrine as Service in Symfony 中阅读更详细的教程和清晰的代码示例。邮政。
关于symfony - 将依赖项注入(inject)实体存储库,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8153103/