根据在 Symfony 中调用的位置阻止监听器被激活

我有一个包含很多捆绑包的 Symfony 项目。


在其中一个中,我有一个像这样的标准 Doctrine 监听器:


class MyListener

{


    public function postLoad(LifecycleEventArgs $args)

    {

        $entity = $args->getObject();


        if ($entity instanceof MyEntity) {

            //do something

        }

...

现在我创建了一个新的 Bundle,它也将这些实体加载到控制器中。


正如预期的那样,它还触发了监听器中的 postLoad。


我需要它不要触发它,或者如果它是由这个 Bundle/Controller 触发的,则不要执行任何操作,例如:


class MyListener

{


    public function postLoad(LifecycleEventArgs $args)

    {

        $entity = $args->getObject();


        if ($caller = "DontTriggerBundle")

            return true;

        }


        if ($entity instanceof MyEntity) {

            //do something

        }

...

有没有办法做到这一点?提前致谢


素胚勾勒不出你
浏览 119回答 1
1回答

DIEA

所以这就是我解决它的方法:将请求堆栈添加到服务:<service id="myservice>&nbsp; &nbsp; <argument type="service" id="request_stack"/></service>然后得到这样的控制器:// src/AppBundle/EventListener/AcmeListener.phpnamespace AppBundle\EventListener;use Doctrine\ORM\Event\LifecycleEventArgs;use Symfony\Component\HttpFoundation\Request;use Symfony\Component\HttpFoundation\RequestStack;class AcmeListener{&nbsp; &nbsp; /** @var Request */&nbsp; &nbsp; protected $request;&nbsp; &nbsp; /**&nbsp; &nbsp; &nbsp;* AcmeListener constructor.&nbsp; &nbsp; &nbsp;*&nbsp; &nbsp; &nbsp;* @param RequestStack $requestStack&nbsp; &nbsp; &nbsp;*/&nbsp; &nbsp; public function __construct(RequestStack $requestStack)&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; $this->request = $requestStack->getCurrentRequest();&nbsp; &nbsp; }&nbsp; &nbsp; /**&nbsp; &nbsp; &nbsp;* @param LifecycleEventArgs $args&nbsp; &nbsp; &nbsp;*/&nbsp; &nbsp; public function postLoad(LifecycleEventArgs $args)&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; $controller = $this->request->attributes->get('_controller');&nbsp; &nbsp; &nbsp; &nbsp; if (strpos($controller, 'DontTriggerController::indexAction') !== false) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; // Do nothing&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; return;&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; // Do somethings&nbsp; &nbsp; }}希望这可以帮助某人
打开App,查看更多内容
随时随地看视频慕课网APP