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...
}
}

Hi! Great post, but, when I try load a web I have a “Missing Layout” error. What is exactly the files I have to create with the mobile_ prefix? Can you give me a example?
Thank You!
@Replicant
Just make sure you have a view file with “mobile_” preceding it in the same folder as the regular view; so for example, if you’re calling the “view” action of the “posts” controller, be sure that you have a mobile_view.ctp file in your views/posts folder. Also forgot to mention; the second parameter of $this->render is the layout to be used; so be sure you have mobile.ctp in your views/layouts folder with a mobile-friendly layout.
Ok! It´s working now! Thank you!! It´s very simple and powerful