Skip to content

Instantly share code, notes, and snippets.

@taiju
Created September 27, 2019 03:02
Show Gist options
  • Save taiju/cbe277015e06b4f4f63abd674919c642 to your computer and use it in GitHub Desktop.
Save taiju/cbe277015e06b4f4f63abd674919c642 to your computer and use it in GitHub Desktop.
CakePHP で任意のステータスコードで JSON レスポンスを返すサンプル
$ curl -X POST http://localhost:8765/api/posts | jq .
{
"status": "invalid"
}
<?php
namespace App\Controller;
class PostsController extends AppController
{
public function initialize()
{
parent::initialize();
// Accept ヘッダの指定によらず JSON を返す
$this->viewBuilder()->setClassName('Json');
}
public function add()
{
$this->set([
'response' => ['status' => 'invalid'],
'_serialize' => 'response'
]);
$response = $this->response->withStatus(400);
$this->setResponse($response);
return $this->render();
}
}
Router::scope('/api', function(RouteBuilder $routes) {
// Resources は fallback が効かないので inflect を指定する
$routes->resources('Posts', ['inflect' => 'dasherize']);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment