包子

木森技术分享

路漫漫其修远兮,吾将上下而求索。

您现在的位置是:网站首页 > THINKPHP

Thinkphp5.0完全相同的域名下访问电脑和手机网站

2021-03-13 21:25:00236

  完全相同的域名下访问电脑和手机网站

  例如,有个域名:www.###.com,在电脑上访问是电脑的网站,在手机上访问是手机网站。如何实现?

  其实只要控制View层使用不同的模版即可实现。主要拿fetch()这个渲染模版的函数来开刀。

  下面就是实际代码:

  公共函数

  在common.php下添加:

/**
 * 判断是否为手机访问
 * @return  boolean
 */
function is_mobile()
{
    static $is_mobile;

    if (isset($is_mobile)) {
        return $is_mobile;
    }

    if (empty($_SERVER['HTTP_USER_AGENT'])) {
        $is_mobile = false;
    } elseif (strpos($_SERVER['HTTP_USER_AGENT'], 'Mobile') !== false
        || strpos($_SERVER['HTTP_USER_AGENT'], 'Android') !== false
        || strpos($_SERVER['HTTP_USER_AGENT'], 'Silk/') !== false
        || strpos($_SERVER['HTTP_USER_AGENT'], 'Kindle') !== false
        || strpos($_SERVER['HTTP_USER_AGENT'], 'BlackBerry') !== false
        || strpos($_SERVER['HTTP_USER_AGENT'], 'Opera Mini') !== false
        || strpos($_SERVER['HTTP_USER_AGENT'], 'Opera Mobi') !== false
    ) {
        $is_mobile = true;
    } else {
        $is_mobile = false;
    }

    return $is_mobile;
}

  控制器

  在基类控制器下覆盖fetch()方法:

/**
     * 加载模板输出(电脑和手机)
     * @access protected
     * @param string $template 模板文件名
     * @param string $mobiletemplate 手机模板文件名
     * @param array  $vars     模板输出变量
     * @param array  $replace  模板替换
     * @param array  $config   模板参数
     * @return mixed
     */
protected function fetch($template = '',$mobiletemplate = '', $vars = [], $replace = [], $config = [])
    {
        if(Config::get('mobile_theme') == true && is_mobile() == true){
            return $this->view->fetch($mobiletemplate, $vars, $replace, $config);
        }else{
            return $this->view->fetch($template, $vars, $replace, $config);
        }
    }

  在控制器下使用fetch()方法:

return $this->fetch('default/index/index','mobile/index/index');