CakePHP网站手机版

Nic*_*las 19 subdomain cakephp mobile-website

我已经开发了一个完整的CakePHP框架网站,我们想为移动设备(主要是iPhone/iPad)制作一个非常简单的网站版本.

有没有办法使用现有网站的新子域(例如mobile.mywebsite.com)来呈现特定的视图?我想避免复制和简化当前的一个以匹配新的要求.我不想在每次需要更改控制器操作时"重新开发"新的CakePHP网站并进行两次更改.

Dan*_*ung 31

我在app_controller.php文件中使用了对beforeFilter()的快速添加来完成此操作.

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

这使用CakePHP RequestHandler来感知它是否是访问我网站的移动设备.它设置属性和视图变量,以允许视图根据新布局调整自身的操作.同时关闭autoRender因为我们会在afterFilter中处理它.

在afterFilter()中,它查找并使用移动视图文件(如果存在).移动版本存储在控制器视图文件夹内的"移动"文件夹中,其名称与普通非移动版本完全相同.(即add.ctp变为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);
        }
     }
Run Code Online (Sandbox Code Playgroud)


小智 5

丹的回答对我有用.但是,我使用了file_exists而不是File构造函数,并添加了使用移动布局的功能.前过滤器是相同的,但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' );

        $this->render($this->action, ($layout_file?'mobile/':'').$this->layout, ($view_file?'mobile/':'').$this->action);
    }
 }
Run Code Online (Sandbox Code Playgroud)


小智 5

您可以在CakePHP 2.x中使用主题功能进行移动布局.

简单地说:

if($this->RequestHandler->isMobile())
    $this->theme = 'mobile';
Run Code Online (Sandbox Code Playgroud)

我发现这更好,因为您可以轻松地在移动和桌面主题上共享View文件.