获取内部控制环境 [英] Get environment inside controller
问题描述
我有一种情况,我的控制器之一,应该只通过AJAX来访问,我有以下code。
I have a situation in one of my controllers that should only be accessed via AJAX, I have the following code.
if (!$request->isXmlHttpRequest()) {
$response = new Response();
$response->setContent('AJAX requests only!');
return $response;
}
当我测试这给了我一个问题,因为该请求实际上并没有通过AJAX进行。这就打破了我的测试中每次。我应该如何去解决这个工作?
When I am testing this gives me an issue because the request hasn't actually been made via AJAX. This then breaks my tests every time. How should I go about working around this?
我的思路:
- 在我试图设置服务器的头,但也绝对没有成功。
- 检查,如果我在测试环境中的控制器和不做的检查,如果它是。我知道这是肮脏的,但它的工作。 : - /问题是,我无法弄清楚如何发现我在什么样的环境 。
任何人有任何其他想法或提示,我很想念获得上述之一的工作?
Anyone else have any other ideas or tips that I am missing to get one of the above to work?
推荐答案
纵观$ C $下 isXmlHtt prequest
类请求
和方法 getHeaders
类 ServerBag
,这块低于code应该做的伎俩:
Looking at the code for isXmlHttpRequest
in class Request
and method getHeaders
in class ServerBag
, the piece of code below should do the trick:
$client->request(
'GET',
'/path/to/test',
array(),
array(),
array(
'HTTP_X-Requested-With' => 'XMLHttpRequest',
)
);
我并没有亲自测试,但我认为它应该工作。低于code。在要求
用于检查HTTP请求是 XmlHtt prequest
。
I did not test it personally but I think it should works. The line of code below in Request
is used to check if the http request is a XmlHttpRequest
.
return 'XMLHttpRequest' == $this->headers->get('X-Requested-With');
在code, $这个 - >标题
使用设置:
In the code, $this->headers
is set using:
$this->headers = new HeaderBag($this->server->getHeaders());
方法 getHeaders
创建头的数组。首先是 HTTP每个服务器变量_
,再加上像 CONTENT_TYPE
一些特殊的服务器变量,都放在这个数组中。
The method getHeaders
creates an array of headers. Each server variable starting with HTTP_
, plus some special server variables like CONTENT_TYPE
, are put in this array.
希望这有助于。
问候,
马特
Regards,
Matt
这篇关于获取内部控制环境的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!