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…

List local disks

GET-CimInstance -query "SELECT * from Win32_DiskDrive" DeviceID Caption Partitions Size Model -------- -------...

Create ISO using Powershell

Usage New-IsoFile -NewIsoFilePath C:\tmp\Hyper-V.iso-sources -ImageName Hyper-V -SourceFilePath 'C:\tmp\Hyper-V'...