LoginSignup
3
2

More than 5 years have passed since last update.

CakePHP2: JSONを返すコントローラを実装する

Posted at

CakePHP2ではアクションが終わるとビューの描画に処理が移ってしまう。JSON APIを実装する場合はビューが不要なので、そうならないために、autoRenderautoLayoutの値をfalseにしておく。また、Content-Typeapplication/jsonにしたいので、response->type()でJSONを指定しておく。

各アクションにこれらの設定を書いてもいいが、コントローラにJSON APIのエンドポイントのアクションしかない場合は、beforeFilterで宣言しておくと重複して書かないで良いので楽。


class ApiController extends AppController
{
  public function beforeFilter()
  {
    parent::beforeFilter();
    $this->autoRender = false;
    $this->autoLayout = false;
    $this->response->type('json');
  }
}
3
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
2