如何在Symfony2中的Entity类中获取Kernel实例

时间:2014-04-24 06:39:45

标签: php symfony doctrine-orm

标题很好地解释了这个问题。我在Doctrine Entity类的生命周期回调中,想要做一些额外的DB条目。为此,我需要获取内核的实例。我怎么能这样做?

2 个答案:

答案 0 :(得分:6)

大多数情况下,需要实体中的容器/内核,错误。实体不应该知道任何服务。那是为什么?

基本上,实体是代表事物的对象。实体主要用于关系数据库,但您可以随时将此实体用于其他事项(序列化它,从HTTP层实现它...)。
您希望您的实体可以进行单元测试,这意味着您需要能够轻松地实现您的实体,而不需要任何操作,而且没有任何业务逻辑。

您应该将您的逻辑移动到另一个层,即将实体化您的实体的层 对于您的用例,我认为,最简单的方法是使用doctrine event

services.yml

services:
    acme_foo.bar_listener:
        class: Acme\FooBundle\Bar\BarListener
        arguments:
            - @kernel
        tags:
            - { name: doctrine.event_listener, event: postLoad }

的Acme \ FooBundle \酒吧\ BarListener

use Symfony\Component\HttpKernel\KernelInterface;
use Doctrine\ORM\Event\LifecycleEventArgs;
use Acme\FooBundle\Entity\Bar;

class BarListener
{
    protected $kernel;

    /**
     * Constructor
     *
     * @param KernelInterface $kernel A kernel instance
     */
    public function __construct(KernelInterface $kernel)
    {
        $this->kernel = $kernel;
    }

    /**
     * On Post Load
     * This method will be trigerred once an entity gets loaded
     *
     * @param LifecycleEventArgs $args Doctrine event
     */
    public function postLoad(LifecycleEventArgs $args)
    {
        $entity = $args->getEntity();

        if (!($entity instanceof Bar)) {
            return;
        }

        $entity->setEnvironment($this->kernel->getEnvironment());
    }
}

你去了,你的实体保持平坦而没有依赖关系,你可以轻松地对事件监听器进行单元测试

答案 1 :(得分:1)

  1. 如果必须使用某些服务,则不应特别使用整个容器或内核实例。
  2. 使用服务本身 - 总是尝试注入单个服务,而不是整个容器
  3. 您的案例看起来应该使用doctrine events