Skip to content

Instantly share code, notes, and snippets.

@josegonzalez
Created February 27, 2012 05:25
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save josegonzalez/1921657 to your computer and use it in GitHub Desktop.
Save josegonzalez/1921657 to your computer and use it in GitHub Desktop.
Custom response types in CakePHP. Must have debug mode to less than 2 in order for it to work properly
<?php
class AppController extends Controller {
/**
* Setup the RequestHandler component
*
* @var array
*/
var $components = array('RequestHandler');
/**
* AppController::beforeFilter() gets triggered before
* RequestHandler::startup(), which triggers RequestHandler::renderAs()
*
* @return void
*/
function beforeFilter() {
$this->_setupResponseTypes();
}
/**
* RequestHandler::respondAs() does not set a custom response type if debug
* mode is set to 2 or higher, thus we need to set debug to 1 in order to
* trigger the custom response types
*
* @return void
*/
function _setupResponseTypes() {
// Setup all the custom content-types,
// extensions mapping to content-types
$this->RequestHandler->setContent('plist', 'application/x-plist');
if (!isset($this->params['url']['ext'])) {
return;
}
if (!isset($this->RequestHandler->__requestContent[$this->params['url']['ext']])) {
return;
}
if (Configure::read('debug') > 1) {
Configure::write('debug', 1);
}
}
}
<?php // this is my app/views/layouts/plist/default.ctp ?>
<?php echo "<?xml version=\"1.0\" encoding=\"UTF-8\"?>"; ?>
<?php echo "<!DOCTYPE plist SYSTEM \"file://localhost/System/Library/DTDs/PropertyList.dtd\">"; ?>
<plist version="1.0">
<?php echo $content_for_layout; ?>
</plist>
<?php
class PostsController extends AppController {
function test() {
}
}
<?php
// This would work to support all extensions
Router::parseExtensions();
// You can also make it explicitly only support certain extensions:
Router::parseExtensions('plist');
<?php // this is my app/views/posts/plist/test.ctp ?>
<dict>
<key>Response</key>
<string>Success</string>
</dict>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment