我有一個服務類,依賴於多個實體存儲庫,例如4.
我可以注入每個存儲庫,並結束了許多依賴,或者我可以注入實體經理作爲單一的依賴;依靠EntityManager->getRepo('xyz')
。注入依賴 - 原則:多個存儲庫vs單個實體管理器
單獨的依賴關係有代碼提示的好處。
單一依賴性意味着在構造上較少冗長。
可能更容易嘲笑和更少的設置?
什麼被認爲是一種更好的做法?
我有一個服務類,依賴於多個實體存儲庫,例如4.
我可以注入每個存儲庫,並結束了許多依賴,或者我可以注入實體經理作爲單一的依賴;依靠EntityManager->getRepo('xyz')
。注入依賴 - 原則:多個存儲庫vs單個實體管理器
單獨的依賴關係有代碼提示的好處。
單一依賴性意味着在構造上較少冗長。
可能更容易嘲笑和更少的設置?
什麼被認爲是一種更好的做法?
在這種情況下,EntityManager類似於Service Locator。當服務取決於EntityManager時,它也正式依賴於它的所有API和所有相關對象(存儲庫,元數據等)。更好地注入您真正需要的東西: 顯式注入特定存儲庫使您的服務更易於閱讀和測試。
此外,如果可能的話,更喜歡使用接口類(ObjectRepository而不是EntityRepository,ObjectManager而不是EntityManager)。
我假設你必須在服務依賴關係中只使用一個Doctrine Entity Manager。 但是,如果你想有代碼提示在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()...
}
}
庫注入做到勝手了。真正的問題是任何依賴4個倉庫的類都可能做得太多。 – Cerad
我同意它看起來過度。然而,它可能應該合併一些回購,因爲它是formElement,formElementOption,formElementFilter等的組合。所以,它的大部分可能超過規範化。但我讚賞評論。 – mr12086