Using JSON in CakePHP 1.2

March 8, 2008

original post

I’m going to explain you how to setup CakePHP 1.2 to output JSON with help of Router::parseExtensions() and the JavascriptHelper::object() method.

In this example we’re going to use a simple posts controller like the one in the Cake blog tutorial.

First we need to let Cake know to parse .json extentions. Add the following to /config/routes.php


Because JSON is not a default content type in CakePHP currently, we need to add it. We also need enable the RequestHandler component. Add the following to your app_controller.php

var $components = array(‘RequestHandler’);
var $helpers = array( ‘Html’, ‘Javascript’ );//Added by me to activate the Javscript helper
var $beforeFilter = array(‘setContent’);
function setContent() {
$this->RequestHandler->setContent(‘json’, ‘text/x-json’);

Now we need to create our JSON layout.
Create: /layouts/json/default.ctp
Paste the following code in the new layout

<_?php class="string">“Pragma: no-cache”);
header(“Cache-Control: no-store, no-cache, max-age=0, must-revalidate”);
header(‘Content-Type: text/x-json’);
header(“X-JSON: “.$content_for_layout);
echo $content_for_layout;

Note: the X-JSON header is used by prototype.js and is automatically evaluated into a JSON object.

Next is our view, we’ll use the index action of the posts controller.
Create: /views/posts/json/index.ctp
And insert the following code in the view

echo $javascript->object($aPosts);

Note: the object method will convert the posts array into a json string, just like the jsonComponent.

Just to be clear here is the index action from the posts controller

function index() {
$this->set(‘aPosts’, $this->Post->findAll());

Now access your posts controller in your browser, /posts/index/ will output the regular html view and /posts/index.json will output your json object!

Note that you can also use xml, rss (supported by default in CakePHP 1.2) to create your own feed in a snap!

NOTE: one important thing is to turn off debug, in order to avoid cake adding debug code under json text.
change line in file core.php, from 2 to 0:
Configure::write(‘debug’, 2);

Gonzalo Escribano

Ver entradas

Most Recent

June 9, 2022

¿Qué son las DAO y cuáles son sus beneficios?

Es común en la historia contemporánea que haya cambios a partir de los avances en el campo de la...

Read More

June 2, 2022

¿Qué son las DeFi y por qué son el futuro de las finanzas?

Es común en la historia contemporánea que haya cambios a partir de los avances en el campo de la...

Read More

May 27, 2022

How to start a successful product build from scratch?

Creating a product from scratch could be a huge challenge. To achieve your business goals it’s important to develop...

Read More