我有一个依赖于多个实体存储库的服务类,例如 4。
我可以注入每个存储库并最终得到许多依赖项,或者我可以将实体管理器作为单个依赖项注入;依靠EntityManager->getRepo('xyz')
.
单独的依赖项具有代码提示的好处。
单个依赖项意味着构造时不那么冗长。
可能更容易模拟和更少的设置?
什么被认为是更好的做法?
在本例中,EntityManager 类似于 Service Locator。当服务依赖于 EntityManager 时,它也正式依赖于其所有 API 和所有相关对象(存储库、metatada 等(。最好只注入你真正需要的东西:显式注入特定存储库使您的服务更易于阅读和测试。
此外,如果可能的话,更喜欢接口而不是类(ObjectRepository而不是EntityRepository,ObjectManager而不是EntityManager(。
我假设,您必须在服务依赖项中仅使用一个原则实体管理器。但是如果你想在你的IDE中有代码提示,你可以使用像这样的phpdoc注释来实现。
class SomeServiceWithDoctrineDependency
{
/** @var YourFirstObjectRepository */
protected $firstRepo;
/** @var YourSecondObjectRepository */
protected $secondRepo;
/** @var YourThirdObjectRepository */
protected $thirdRepo;
public function __construct(EntityManagerInterface $entityManager)
{
$this->firstRepo = $entityManager->getRepository('First:Repo');
$this->secondRepo = $entityManager->getRepository('Second:Repo');
$this->thirdRepo = $entityManager->getRepository('Third:Repo');
}
public function getCodeHint()
{
// You get hint here for find method
// $this->thirdRepo()->find()...
}
}