Symfony2:获取实体内部服务

时间:2012-12-10 07:38:18

标签: php symfony doctrine-orm

有没有办法在实体内部调用服务

我需要实体内部的实体管理器,因此我可以使用存储库功能获得自定义结果。

我正在考虑像我这样在我的实体中注入ContainerInterface。

use Symfony\Component\DependencyInjection\ContainerInterface;

class MyEntity
{
    protected $container;

    public function __construct(ContainerInterface $container)
    {
        $this->container = $container;
    }

    public function getEntityManager(){
        return $this->container->get('doctrine')->getEntityManager();
    }
} 

但我认为这不是正确的方法,它需要更多代码我的意思是我必须为我需要实体管理器的所有实体执行此操作

有什么好的解决方案吗?

2 个答案:

答案 0 :(得分:3)

我不知道你能不能,但你不应该这样做。实体意味着非常简单......

  

需要实体管理器内部实体,这样我就可以获得具有存储库功能的自定义结果

你想要做什么,必须有一个不同的解决方案......

答案 1 :(得分:1)

如前所述,依赖注入肯定是错误的方法。

使用自定义实体存储库(http://symfony.com/doc/2.0/book/doctrine.html#custom-repository-classes)进行更复杂的查询,或使用特定服务来实现自定义结果需要更多的复杂性(http://symfony.com/doc/2.0/book/service_container.html#referencing-injecting-services)