phpcakephpsubdomainmobile-website

CakePHP website mobile version


I have developed a full website with CakePHP framework and we'd like to make a very light version of the website for mobile devices (mainly iPhone/iPad).

Is there a way to use the existing website with a new sub domain (for instance mobile.mywebsite.com) which will render specific views? I would like to avoid copying and simplifying the current one to match the new one requirements. I do not want to have to "re-develop" a new CakePHP website and do the changes twice every time I need to change a controller action.


Solution

  • I've done this using a quick addition to the beforeFilter() in my app_controller.php file.

    function beforeFilter() {
         if ($this->RequestHandler->isMobile()) {
            $this->is_mobile = true;
            $this->set('is_mobile', true );
            $this->autoRender = false;
         }
    }
    

    This uses the CakePHP RequestHandler to sense if it's a mobile device visiting my site. It sets a property and view variable to allow actions an views to adjust themselves based on the new layout. Also turns off the autoRender because we'll take care of that in an afterFilter.

    In the afterFilter() it looks for and uses a mobile view file if one exists. Mobile versions are stored in a 'mobile' folder inside the controller's view folder and are named exactly the same as the normal non-mobile versions. (ie. add.ctp becomes mobile/add.ctp)

        function afterFilter() {
            // if in mobile mode, check for a valid view and use it
            if (isset($this->is_mobile) && $this->is_mobile) {
                $view_file = new File( VIEWS . $this->name . DS . 'mobile/' . $this->action . '.ctp' );
                $this->render($this->action, 'mobile', ($view_file->exists()?'mobile/':'').$this->action);
            }
         }