CakePHP3でjsonを返すAPIをCakePHPの流儀に従って記述量少なく書きたい人生だったの続き。
REST APIを書いていると、jsonとともにHTTP status codeを設定したいことがある。
だめな方法
$this->response->statusCode(403);
@deprecated 3.4.0 Use `getStatusCode()` and `withStatus()` instead.
動くけどだめです。
ずっと今のバージョンを使うならこれで良いだろう。
なるほど withStatus
ね
$this->response->withStatus(400);
200が返る…。
withStatusの戻りをreturnすると今度はbodyが返らない。
結局こうした
$response = new Response();
$response = $response->withType('application/json')
->withStatus($status)
->withStringBody(json_encode($something));
return $response;
動いたけど、本当にこれしかないの?
json_encodeとか書きたくないし、前回と比べて統一感がなさすぎる。