Symfony 控制器 return 数组

Symfony Controller return array

我正在尝试创建一个侦听器,它使用注释配置 Response 并将响应内容设置为控制器 return。

控制器代码:

use PmtVct\PhotoBookBundle\Annotations\ResponseType;
use Symfony\Component\HttpFoundation\Request;

/**
* @ResponseType("JSON")
*/
public function home(Request $request) {
    return ['asdf' => 123];
}

但我收到“The controller must return a response”错误。

有一种方法可以 return Controller 上的数组而不是 Response?

根据 the documentation,您可以 return 一个像这样的 JsonResponse:

return new JsonResponse(['asdf' => 123]);

您正在尝试做与 FOSRestBundle 类似的事情。也许考虑使用这个包?它将允许:

  • Return 控制器中的数组,完全按照您想要的方式
  • 将响应序列化为Json,或您希望的其他格式,它还可以从请求中自动检测格式。

如果您仍然想自己构建这样的侦听器 - 看看它在 FOSRestBundle 中是如何完成的 - https://github.com/FriendsOfSymfony/FOSRestBundle/blob/master/EventListener/ViewResponseListener.php - 他们正在使用 "kernel.view" 事件。