Created
September 27, 2019 03:02
-
-
Save taiju/cbe277015e06b4f4f63abd674919c642 to your computer and use it in GitHub Desktop.
CakePHP で任意のステータスコードで JSON レスポンスを返すサンプル
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
$ curl -X POST http://localhost:8765/api/posts | jq . | |
{ | |
"status": "invalid" | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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(); | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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