How to get request type (master/sub) in Symfony2 controller?

匿名 (未验证) 提交于 2019-12-03 03:05:02

问题:

Is there possible get request type in controller? How?

回答1:

To detect if the request is a master or not requires the use of the RequestStack, which should be injected into your controller. The request stack has 3 useful methods

getCurrentRequest(); getMasterRequest(); getParentRequest();

The getParentRequest() will always return null if the current request is the master.



回答2:

I was looking for this myself, and it seems it is just passed around, so there doesn't seem to be one single place that knows what it is.

My thought for solving this would be to create a simple kernel.request listener that just adds an attribute to the request. Rough (un-tested) code below:

public function onKernelRequest(GetResponseEvent $event) {     $event->getRequest()->attributes->set('_request_type', $event->getRequestType()); }

Then in the controller you should be able to do:

$requestType = $this->getRequest()->attributes->get('_request_type');

Again this is untested. You would need to write out the full listener class and add it to the services config file, but other than that I think this will work.



回答3:

Easy, just call the getMethod() method on your Request object:

$method = $this->get('request')->getMethod();

This will return the HTTP method of the current request, e.g. GET, POST, PUT or DELETE.



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