Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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