我知道我可以从实体经理那里获得参考资料.但是,我不希望我的服务依赖于实体管理器.相反,我想注入一个Repository类,然后以某种方式从该Repository类中获取一个Reference.这可能吗?
我不想要这个:
<?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);
}
}
Run Code Online (Sandbox Code Playgroud)
我想要这样的东西:
<?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 = ???
}
}
Run Code Online (Sandbox Code Playgroud)
// 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);
Run Code Online (Sandbox Code Playgroud)
注意使用getEntityName.无需拼出类名,因为存储库已经知道这一点.您实际上可以创建自己的基本存储库类并将其添加到其中.然后从中扩展所有自定义存储库.
考虑添加持久化,刷新等方法.
小智 -3
通过此调用,您将获得引用/实体对象
$reference = $this->repo->find($someId);
Run Code Online (Sandbox Code Playgroud)