Mobile device detection and development with CakePHP

I was recently working on a project that required a mobile version of the site (built with cakePHP). The site was simple enough that the majority of the actions that rendered views were contained within one controller. Using cake’s built in Request Handling makes it easy to detect mobile devices and select an appropriate view and layout file to render the action.
In your app_controller.php, turn off autoRender if the isMobile method returns true:

// file: /app/app_controller.php
class AppController extends Controller {
var $components = array('RequestHandler');

function beforeFilter(){
if ($this->RequestHandler->isMobile()) {
$this->autoRender = false;
}
}

function afterFilter(){
if ($this->RequestHandler->isMobile()) {
$this->render($this->action, 'mobile', 'mobile_'.$this->action);
}
}
}

The afterFilter function runs the same conditional statement as beforeFilter, but tells cake to render the currently running action using the mobile’ layout, using the mobile_action’ view. So when you create your normal view files, also create a mobile version with the same file name, preceeded with mobile_’. This approach assumes you want to run the same controller logic for both versions of the site (mobile and standard). You could always use routes to create a more elegant system for handling requests from mobile devices, but for this particular project, the logic didn’t change much beyond defining the default limit with pagination.
And don’t forget, if you’re defining afterFilter and beforeFilter in your app_controller, be sure your controllers inherit app_controller’s filter functions.

// file: /app/controllers/posts_controller.php
class PostsController extends AppController {
var $name = 'Posts';

function beforeFilter(){
parent::beforeFilter();
//rest of your beforeFilter function here...
}
}