How to do it is scattered and buried in various places for CakePHP for various versions of the framework. Some of the older methods were complex and really wouldn’t work anymore for the latest build, which is 1.3. So I figured out that 1.3 does make it easier and I finally learned how to use http://domain.com/controller/view.xml as a request or link in a few steps. First, I need to add to routes.php in the config directory:
Router::parseExtensions('xml');
and in the app_controller, add the component, so it’ll know what layout and view to use:
var $components = array('RequestHandler');
This XML layout and view is standard with CakePHP in 1.3 but if I wanted to add a .json extension with the content-type set as “application/json” — add the json extension to the router, and then add json folder to the views/layout path. In the json folder, add default.ctp and it’s contents are:
<?php
header("Pragma: no-cache");
header("Cache-Control: no-store, no-cache, max-age=0, must-revalidate");
header('Content-Type: application/json');
header("X-JSON: ".$content_for_layout);
echo $content_for_layout;
?>
And to pass parameters like http://domain/controller/view/param1/param2, I need to add the extension I want to use at the very end. So the parameter in the request, or in the link, becomes http://domain/controller/view/param1/param2.json or whatever other extension.
Also, in addition to adding the component to the app_controller, if I wanted to remove the debugging output that gets generated at the bottom of the json or xml for requests that pass ‘HTTP_X_REQUESTED_WITH’ == ‘XMLHttpRequest’ in the header, I added to my beforeRender method in the app_controller.
public function beforeRender() {
if ($this->RequestHandler->isAjax())
Configure::write('debug',0);
}
