在服务中注入Doctrine Entity Manager - 不好的做法?

Mac*_*iel 6 dependency-injection symfony

使用https://insight.sensiolabs.com扫描/检查我的代码,我收到以下警告:

The Doctrine Entity Manager should not be passed as an argument.

为什么在服务中注入实体管理器是一种不好的做法?什么是解决方案?

Cer*_*rad 6

关于存储库不能持久化实体的评论.

class MyRepository extends EntityRepository
{
    public function persist($entity) { return $this->_em->persist($entity); }
    public function flush  ()        { return $this->_em->flush  (); }
Run Code Online (Sandbox Code Playgroud)

我喜欢让我的存储库或多或少地遵循"标准"存储库接口.所以我这样做:

interface NyRepositoryInterface
[
    function save($entity);
    function commit();
}
class MyRepository extends EntityRepository implements MyRepositoryInterface
{
    public function save  ($entity) { return $this->_em->persist($entity); }
    public function commit()        { return $this->_em->flush  (); }
Run Code Online (Sandbox Code Playgroud)

这允许我定义和注入非教义存储库.

您可能反对必须将这些辅助函数添加到每个存储库.但我发现有点复制/粘贴是值得的.特征也可能对此有所帮助.

这个想法是脱离实体经理的整个概念.

  • 这非常有用,谢谢.只有一个小的修正:方法持续存在,并且刷新是无效的,不会返回任何内容 (2认同)