我正在使用FOSRestBundle开发REST API。我无法从控制器发送JSON响应。我正在将fooAction of FooControllerFoo的请求转发给某个BarController,当我尝试从该动作返回JSON响应时,我得到了空白数组。
这是场景:
FooController.php
class FooController extends FOSRestController {
...
public function fooAction() {
...
$response = $this->forward('ApplicationPApiBundle:bar:getByZipCode', array(), array('zipcode' => $zipcode));
print_r($response); //getting blank array here
...
}
}
BarController.php
class BarController extends FOSRestController {
...
public function getByZipCodeAction() {
...
$response = new Response((array("one"=>"1", "two"=> "2")));
$response->headers->set('Content-Type', 'application/json');
// print_r($response); // after printing I can see data in json format
return $response;
}
}
当我在FooController的fooAction中打印响应时,我将其视为一个空数组,但是当我在返回它之前在Barcontroller的getByZipCodeAction中打印它时,我看到了带有json内容的正确响应对象。
有人可以帮我弄清楚这里发生了什么吗?
编辑: 响应对象在返回之前打印在Barcontroller中:
Symfony\Component\HttpFoundation\Response Object
(
[headers] => Symfony\Component\HttpFoundation\ResponseHeaderBag Object
(
[computedCacheControl:protected] => Array
(
[no-cache] => 1
)
[cookies:protected] => Array
(
)
[headerNames:protected] => Array
(
[cache-control] => Cache-Control
[date] => Date
[content-type] => Content-Type
)
[headers:protected] => Array
(
[cache-control] => Array
(
[0] => no-cache
)
[date] => Array
(
[0] => Wed, 24 Sep 2014 13:48:49 GMT
)
[content-type] => Array
(
[0] => application/json
)
)
[cacheControl:protected] => Array
(
)
)
[content:protected] => {"one":"1","two":"2"}
[version:protected] => 1.0
[statusCode:protected] => 200
[statusText:protected] => OK
[charset:protected] =>
)
=============================================== ==================
在收到转发操作的回复后,在Foocontroller中打印响应对象:
Symfony\Component\HttpFoundation\Response Object
(
[headers] => Symfony\Component\HttpFoundation\ResponseHeaderBag Object
(
[computedCacheControl:protected] => Array
(
[no-cache] => 1
)
[cookies:protected] => Array
(
)
[headerNames:protected] => Array
(
[cache-control] => Cache-Control
[date] => Date
[content-type] => Content-Type
[x-debug-token] => X-Debug-Token
[x-debug-token-link] => X-Debug-Token-Link
)
[headers:protected] => Array
(
[cache-control] => Array
(
[0] => no-cache
)
[date] => Array
(
[0] => Wed, 24 Sep 2014 13:48:49 GMT
)
[content-type] => Array
(
[0] => application/json
)
[x-debug-token] => Array
(
[0] => 168be3
)
[x-debug-token-link] => Array
(
[0] => /app_dev.php/_profiler/168be3
)
)
[cacheControl:protected] => Array
(
)
)
[content:protected] => []
[version:protected] => 1.0
[statusCode:protected] => 200
[statusText:protected] => OK
[charset:protected] =>
)
请注意内容是空的。
答案 0 :(得分:0)
我不是FOSRestBundle的专家,但我认为你应该这样做:
$view = $this->view(['one' => 1, 'two' => 2]);
$view->setFormat('json');
return $this->handleView($view);
我相信目前正在发生的事情是视图处理程序侦听器没有收到任何数据,所以用null覆盖响应的内容。
答案 1 :(得分:0)
我无法弄清楚导致问题的确切原因,它可能与FOSRestBundle视图侦听器有关。 根据@Cerad在评论中提到的链接,我决定创建我转发请求的操作服务。所以在我的情况下,我废弃了BarController并创建了一个服务,虽然我可以选择使用这个控制器作为服务,但我认为使用单独的类作为服务在我的情况下更可行。