美文网首页
tp5多模块下判断PC访问和手机访问的功能

tp5多模块下判断PC访问和手机访问的功能

作者: 懒得代码 | 来源:发表于2019-01-16 10:17 被阅读0次

    网站开发时自动识别pc还是mobile,相信这个问题已经很容易解决了,而且tp5框架有自带的识别方法
    Request->isMobile()
    但是再做多模块的时候遇到了点问题,下面是我的解决办法,比较简单

    说明:
    tp5开发多模块网站时用了多级控器
    index/home.index/index

    问题
    我的模板文件是放在项目下的view文件夹下的,
    因为我的模块有前后台,所以我的view下面现在是view/admin,view/home这两个文件夹,现在有一个手机端,如果是按照多级控制器的话,默认会需要我把view/home这文件夹拆分成view/home/default,view/home/mobile,但是我感觉这样有点麻烦,目录层级太深了,所有我的想法是view下分别是admin,home,mobile这三个目录。

    解决
    多级控制器默认的模板路径会自动解析成home/index/index,这个是根据路由来的,直接是没法改变的
    看了模板的fetch()方法后,想到了可以在controller里面继承一个fetch()方法然后重写一下,再模板文件fetch()的时候把home/index/index改成mobile/index/index问题可以解决了
    下面是代码,一个简单的小方法。

    public function fetch($template = '', $vars = [], $replace = [], $config = [])
        {
            $request=$this->request;
            if(empty($template)){
                $controller= $this->request->controller();
                if($request->isMobile()){
                    $controller=str_replace('Home.','Wap.',$controller);
                }
                $template = str_replace('.', DS, $controller) . DS . Loader::parseName($request->action(true));
            }
            $__HOME=$this->request->root(true).'/public/static/'.$request->module().'/home';
            if($request->isMobile()){
                $__HOME=$this->request->root(true).'/public/static/'.$request->module().'/wap';
            }
            $replace_ext=[
                '__HOME__'=>$__HOME
            ];
            $replace=array_merge($replace,$replace_ext);
            return parent::fetch($template, $vars, $replace, $config);
        }
    

    相关文章

      网友评论

          本文标题:tp5多模块下判断PC访问和手机访问的功能

          本文链接:https://www.haomeiwen.com/subject/fkvpdqtx.html