How to get Container object from LifecycleEventArgs of postLoad in Entity?

北战南征 提交于 2019-12-04 15:11:21

You can use setter-injection which result in a call to a predefined method (setContainer() in this case) with the container as an argument upon creation of the listener service:

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 }

Now the container is injected into the constructor of your listener class:

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'));

This is just an example. Please consider injecting only the services you really need - instead of injecting the container itself. You will be rewarded with better testability and performance.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!