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 *

This site is protected by reCAPTCHA and the Google Privacy Policy and Terms of Service apply.

The reCAPTCHA verification period has expired. Please reload the page.

You May Also Like…

Squarespace Image Export

To gain continued access to your Squarespace website images after cancelling your subscription you have several...

MySQL 8.x GRANT ALL STATEMENT

-- CREATE CREATE USER 'tgnrestoreuser'@'localhost' IDENTIFIED BY 'AppleSauceLoveBird2024'; GRANT ALL PRIVILEGES ON...

Exetel Opt-Out of CGNAT

If your port forwards and inbound and/or outbound site-to-site VPN's have failed when switching to Exetel due to their...