CakePHP website mobile version

2019-01-16 05:40发布

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.

8条回答
Melony?
2楼-- · 2019-01-16 06:24

The simple solution is to create a new 'mobile' layout with respective stylesheet(s) and turn it on in AppController:

public $components = array('RequestHandler');
public function beforeRender() {
    parent::beforeRender();
    if ($this->RequestHandler->isMobile()) {
        $this->layout = 'mobile';
    }
}

It is important to do that in beforeRender() in case if you change $this->layout in your controllers' methods.

查看更多
三岁会撩人
3楼-- · 2019-01-16 06:27

I modified this technique for a CakePHP 2.1 app. Here is my beforeFilter():

public function beforeFilter() {

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

}

And here is my afterFilter():

function afterFilter() {
    // if in mobile mode, check for a valid view and use it
    if (isset($this->is_mobile) && $this->is_mobile) {
        $view_file = file_exists( 'Views' . $this->name . DS . 'mobile/' . $this->action . '.ctp' );
        $layout_file = file_exists( 'Layouts' . 'mobile/' . $this->layout . '.ctp' );
        if($view_file || $layout_file){
            $this->render($this->action, ($layout_file?'mobile/':'').$this->layout, ($view_file?'mobile/':'').$this->action);
        }
    }
 }

This helps account for deprecated verbiage and constants in CakePHP 2.

查看更多
登录 后发表回答