如何从实体中的postLoad的LifecycleEventArgs获取Container对象?

时间:2015-05-27 10:00:32

标签: php symfony entity containers symfony-2.6

我正在尝试使用postLoad lifecycleCallbacks将Container对象(在控制器中可用)注入实体。 postLoad方法的参数是LifecycleEventArgs。根据转储输出,我可以在EventManager LifecycleEventArgs中看到容器属性(我要检索),但它似乎是一个私有属性,并且没有getContainer()方法EventManager。以下是我的代码。

service.yml

services:
    ibw.jobeet.entity.job.container_aware:
        class: Ibw\JobeetBundle\Entity\Job
        tags:
            - { name: doctrine.event_listener, event: postLoad }

IBW \ JobeetBundle \实体\ Job.php

<?php
namespace Ibw\JobeetBundle\Entity;

use Doctrine\ORM\Mapping as ORM;
use Doctrine\ORM\Event\LifecycleEventArgs;
use Symfony\Component\Validator\Constraints as Assert;
use Symfony\Component\HttpFoundation\File\UploadedFile;
use Symfony\Component\DependencyInjection\ContainerAware;
use Symfony\Component\DependencyInjection\ContainerInterface;

use Ibw\JobeetBundle\Utils\Jobeet;

/**
 * Job
 */
class Job
{
    //....
    /**
     * @var Container
     */
    protected $container;

    public function postLoad(LifecycleEventArgs $eventArgs)
    {
        $entity = $eventArgs->getEntity();
        $entityManager = $eventArgs->getEntityManager();
        $eventManager = $entityManager->getEventManager();
        echo '<pre>';
        \Doctrine\Common\Util\Debug::dump($eventManager, 3);

        // want to get $eventManager->container here

        exit;
    }
    //....
}

有没有其他方法可以检索它?

1 个答案:

答案 0 :(得分:2)

您可以使用setter-injection导致调用预定义的方法(在本例中为setContainer()),并在创建侦听器服务时将容器作为参数:

services:
    ibw.jobeet.entity.job.container_aware:
        class: Your\Bundle\Doctrine\Event\Listener\JobListener
        calls:
            - [setContainer, ["@service_container"]]
        tags:
            - { name: doctrine.event_listener, event: postLoad }

现在容器被注入到监听器类的构造函数中:

namespace Your\Bundle\Doctrine\Event\Listener;

use Symfony\Component\DependencyInjection\ContainerInterface;
use Doctrine\ORM\Event\LifecycleEventArgs;

class JobListener
{
     /** @var ContainerInterface */
     protected $container;

     /** 
      * @param ContainerInterface @container
      */
     public function setContainer(ContainerInterface $container)
     {
          $this->container = $container;
     }

     public function postLoad(LifecycleEventArgs $eventArgs)
     {
         $entity = $eventArgs->getEntity();
         // do something with your entity here i.e.
         $entity->setFoo($this->container->getParameter('foo'));

这只是一个例子。请考虑只注入您真正需要的服务 - 而不是注入容器本身。您将获得更好的可测试性和性能。