Configure CakePHP 2.x to Detect and Serve Mobile Browser Pages

Written by James McDonald

September 26, 2012

Put here for later:

http://madething.org/post/661607317/mobile-browser-detection-and-optimization-in-cakephp

http://doctorfox.wordpress.com/2012/05/28/mobile-browser-detection-and-optimization-in-cakephp-made-simple/

Only thing needing to be added would be a cookie based ‘request desktop site’ option…

Update: 

  • The above posts are for older versions of Cakephp which had a VIEW constant
  • assumed that the view directory would be lowercase

The following is a copy and paste of my app/Controllers/AppController.php class.

class AppController extends Controller {

	public $components = array('RequestHandler');

	public function beforeFilter(){
 	  if ($this->RequestHandler->isMobile()) {

            // required for CakePHP 2.2.2
            $viewDir = App::path('View'); 
            // returns an array
            /*
             * array(
             * 		(int) 0 => '/var/www/maps-cakephp2/app/View/'
             * ) 
             */

            $mobileViewFile = $viewDir[0] . $this->viewPath 
                              . '/mobile/' . 
                              $this->params['action'] . '.ctp';

            Debugger::log($this->viewPath); 
            // use this to log the output to
            // app/tmp/logs/debug.log

            if (file_exists($mobileViewFile)) {
               // if device is mobile, change layout to mobile
               // but only if a view exists for it.
                $this->layout = 'mobile';
               // and if a mobile view file has been 
               // created for the action, serve it instead 
                // of the default view file

                $mobileView = $this->viewPath . '/mobile/';
                $this->viewPath = $mobileView;
            }
           } 
	}
}

 

 

2 Comments

  1. Benny L.E.P

    great solution, working in cakephp 2.3.1
    thank you 🙂

    Reply
  2. kicaj

    There is static method for detect?

    Reply

Submit a Comment

Your email address will not be published. Required fields are marked *

You May Also Like…

How to Research a CPU Upgrade

How to Research a CPU Upgrade

Upgrade Time! Doing a lot of VMWare Workstation virtualization to create labs for self-study and training. Finding...