原则2:我可以从存储库而不是实体管理器中获得引用吗?


Doctrine 2: Can I get a Reference from a Repository instead of from the Entity Manager?

我知道我可以从实体管理器获得引用。但是,我不希望我的服务依赖于实体管理器。相反,我想注入一个Repository类,然后以某种方式从该Repository类获取一个引用。这可能吗?

I don't want this:

<?php
use Doctrine'ORM'EntityManager;
class MyService {
    protected $em;
    public function __construct(EntityManager $em){
        $this->em = $em;
    }
    public function doSomething($someId)
    {
        $reference = $this->em->getReference('My'Entity', $someId);
    }
}

我想要这样的东西:

<?php
use Doctrine'ORM'EntityRepository;
class MyService {
    protected $repo;
    public function __construct(EntityRepository $repo){
        $this->repo = $repo;
    }
    public function doSomething($someId)
    {
        // how to retrieve a reference???
        $reference = ???
    }
}
// Add getReference() to the repository
class MyRepository extends Doctrine'ORM'EntityRepository
{
    public function getReference($id)
    {
        return $this->getEntityManager()->getReference($this->getEntityName(),$id));
    }
// From a controller
$reference = $repo->getReference($id);

注意getEntityName的使用。不需要拼写类名,因为存储库已经知道了。实际上,您可以创建自己的基存储库类并将其添加到其中。然后从它扩展所有自定义存储库。

考虑添加persist,flush等方法

通过这个调用,您可以获得引用/entity-object

$reference = $this->repo->find($someId);