代码之家  ›  专栏  ›  技术社区  ›  kockburn

在EventSubscriber中如何从URL获取参数?

  •  0
  • kockburn  · 技术社区  · 7 年前

    $id 当它不应该是空的时候总是空的。我可以通过控制器检索$id值,但不能从EventSubscriber检索。

    FilterControllerEvent

    class TestVerificationSubscriber implements EventSubscriberInterface
    {
    
        private $testService;
        public function __construct(TestService $testService)
        {
            $this->testService = $testService;
        }
    
        /**
         * Returns an array of event names this subscriber wants to listen to.
         *
         * The array keys are event names and the value can be:
         *
         *  * The method name to call (priority defaults to 0)
         *  * An array composed of the method name to call and the priority
         *  * An array of arrays composed of the method names to call and respective
         *    priorities, or 0 if unset
         *
         * For instance:
         *
         *  * array('eventName' => 'methodName')
         *  * array('eventName' => array('methodName', $priority))
         *  * array('eventName' => array(array('methodName1', $priority), array('methodName2')))
         *
         * @return array The event names to listen to
         */
        public static function getSubscribedEvents()
        {
            return array(
                KernelEvents::CONTROLLER => 'onKernelController',
            );
        }
    
        public function onKernelController(FilterControllerEvent $event){
            $controller = $event->getController();
    
            /*
             * $controller passed can be either a class or a Closure.
             * This is not usual in Symfony but it may happen.
             * If it is a class, it comes in array format
             */
            if (!is_array($controller)) {
                return;
            }
    
            if ($controller[0] instanceof TestVerificationController) {
                //this always returns null
                $id = $event->getRequest()->query->get('id');
                if(!$id){
                    throw new CustomApiException(Response::HTTP_BAD_REQUEST, "Could not verify that the test exists.");
                }
                $this->testService->checkAndUpdateWithId($id);
            }
        }
    
    }
    

    我现在唯一的假设是,也许在这个特定的时刻,symfony还没有完全处理请求?

    1 回复  |  直到 7 年前
        1
  •  2
  •   kockburn    7 年前

    $id = $event->getRequest()->attributes->get("id");