Skip to content

Instantly share code, notes, and snippets.

@nissuk
Created February 6, 2011 03:06
Show Gist options
  • Star 5 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nissuk/813066 to your computer and use it in GitHub Desktop.
Save nissuk/813066 to your computer and use it in GitHub Desktop.
CakePHP(1.3)でJSON出力する単純な例
<?php // {app}/config/routes.php
/**
* Routes Configuration
*
* In this file, you set up routes to your controllers and their actions.
* Routes are very important mechanism that allows you to freely connect
* different urls to chosen controllers and their actions (functions).
*
* PHP versions 4 and 5
*
* CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
* Copyright 2005-2010, Cake Software Foundation, Inc. (http://cakefoundation.org)
*
* Licensed under The MIT License
* Redistributions of files must retain the above copyright notice.
*
* @copyright Copyright 2005-2010, Cake Software Foundation, Inc. (http://cakefoundation.org)
* @link http://cakephp.org CakePHP(tm) Project
* @package cake
* @subpackage cake.app.config
* @since CakePHP(tm) v 0.2.9
* @license MIT License (http://www.opensource.org/licenses/mit-license.php)
*/
/**
* Here, we are connecting '/' (base path) to controller called 'Pages',
* its action called 'display', and we pass a param to select the view file
* to use (in this case, /app/views/pages/home.ctp)...
*/
Router::connect('/', array('controller' => 'pages', 'action' => 'display', 'home'));
/**
* ...and connect the rest of 'Pages' controller's urls.
*/
Router::connect('/pages/*', array('controller' => 'pages', 'action' => 'display'));
// 1. 拡張子でリソースの種類を判断できるよう、Router::parseExtensions()を追加します。
Router::parseExtensions();
<?php // {app}/views/layouts/json/default.ctp
// 2. JSON用のデフォルトレイアウトビューファイルを追加します。
?>
<?php echo $content_for_layout; ?>
<?php // {app}/views/users/json/index.ctp
// 3. データをJSON出力するためのビューファイルを作成します。
?>
<?php echo json_encode($users) ?>
<?php // {app}/controllers/users_controller.php
class UsersController extends AppController {
var $name = 'Users';
var $helpers = array('Html', 'Form');
// 4. RequestHandlerを追加します。
var $components = array('RequestHandler');
function beforeFilter() {
// 5. debug設定が0でないとContent-Typeがtext/htmlになるようなので、
// debug設定を0にしてJSONのときのContent-Typeがapplication/jsonになるようにします。
// (4.と5.はapp_controller.phpに設定してしまってもよいかもしれません)
if ($this->RequestHandler->ext == 'json') {
Configure::write('debug', 0);
}
}
function index() {
// 6. JSON出力するデータをセットします。
$this->User->recursive = 0;
$this->set('users', $this->paginate());
}
}
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment