首先,我想指出,这样的要求似乎很不方便。 如果希望响应具有JSON格式的正文,则可以在此处轻松定义自定义原因短语。
Response::httpCodes()仅与“旧”前端控制器一起使用
话虽这么说,通常这是可能的,但是当使用CakePHP 3.3引入的PSR兼容请求/响应组件时,当前不直接支持,因为自定义原因短语不会传递到PSR兼容响应。 使用3.3之前的调度机制,它仍然可以工作,但是,请检查“旧的”应用程序模板前端控制器( webroot/index.php文件)。
从3.4起可以轻松地再次完成
从CakePHP 3.4开始,不推荐使用Response::httpCodes() ,它将在4.0中删除。 同样从3.4版本开始,CakePHP响应类将与PSR-7完全兼容,并且您将能够通过Response::withStatus()方法使用自定义原因短语来设置状态,例如
return $this->response->withStatus(400, 'Bad Origin');
请记住,与PSR-7兼容的响应对象是不可变的! 即,如果您希望在控制器中修改$this->response以进一步使用,则必须将其覆盖,例如:
$this->response = $this->response->withStatus(/* ... */);
在3.3 / 3.4转换中需要“解决方法”
在3.3和3.4之间的过渡中,当使用与PSR兼容的前端控制器时,可以通过覆盖Application::__invoke()来添加对自定义原因短语的支持(默认情况下, Application类文件位于apps src文件夹中。
您必须重新实现BaseApplication::__invoke()代码,并传递从Response::httpCodes()获得的原因短语,类似以下内容:
use Cake\Http\RequestTransformer;
use Cake\Http\ResponseTransformer;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface;
// ...
public function __invoke(ServerRequestInterface $request, ResponseInterface $response, $next)
{
$cakeRequest = RequestTransformer::toCake($request);
$cakeResponse = ResponseTransformer::toCake($response);
$cakeResponse = $this->getDispatcher()->dispatch($cakeRequest, $cakeResponse);
$psrResponse = ResponseTransformer::toPsr($cakeResponse);
$status = $psrResponse->getStatusCode();
$httpCodes = $cakeResponse->httpCodes($status);
if ($httpCodes !== null && isset($httpCodes[$status])) {
return $psrResponse->withStatus($status, $httpCodes[$status]);
}
return $psrResponse;
}
也可以看看