$id
不应为null。我可以通过控制器而不是从EventSubscriber检索$ id值。
如何使用FilterControllerEvent
通过EventSubscriber从URL正确检索参数?
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尚未完全处理请求?
答案 0 :(得分:1)
似乎已处理了数据,但仅在此之下:
$id = $event->getRequest()->attributes->get("id");