在 PHP 7.4 中检测是否是移动设备,进而渲染不同的模板文件
1、由于前端,同一个页面,针对移动设备与桌面设备,是分别编写的页面。因此,需要在 PHP 7.4 中检测是否是移动设备,进而渲染不同的模板文件
2、参考:Mobile-Detect 。只能够使用 3.* 的最新版本,因为现在是使用的 PHP 7.4,其 4.* 的版本要求 PHP 8 以上的版本。。如图1
3、Mobile Detect 是一个轻量级的 PHP 类,用于检测移动设备(包括平板电脑)。它使用 User-Agent 字符串结合特定的 HTTP 标头来检测移动环境。在页面的 Modules, plugins, ports -> Yii Framework,发现实现的 Yii2 扩展,都有 5 年左右没有更新,且依赖 “mobiledetect/mobiledetectlib”: “~2.8″。最终决定使用 “mobiledetect/mobiledetectlib”: “^3.74” 。配置 composer.json 。安装更新。如图2
{ "require": { "mobiledetect/mobiledetectlib": "^3.74" } }
PS C:\wwwroot\object\src> composer install Installing dependencies from lock file (including require-dev) Verifying lock file contents can be installed on current platform. Warning: The lock file is not up to date with the latest changes in composer.json. You may be getting outdated dependencies. It is recommended that you run `composer update` or `composer update <package name>`. - Required package "mobiledetect/mobiledetectlib" is not present in the lock file. This usually happens when composer files are incorrectly merged or the composer.json file is manually edited. Read more about correctly resolving merge conflicts https://getcomposer.org/doc/articles/resolving-merge-conflicts.md and prefer using the "require" command over editing the composer.json file directly https://getcomposer.org/doc/03-cli.md#require-r PS C:\wwwroot\object\src> composer update mobiledetect/mobiledetectlib Loading composer repositories with package information Updating dependencies Lock file operations: 1 install, 0 updates, 0 removals - Locking mobiledetect/mobiledetectlib (3.74.3) Writing lock file Installing dependencies from lock file (including require-dev) Package operations: 1 install, 0 updates, 0 removals - Downloading mobiledetect/mobiledetectlib (3.74.3) - Installing mobiledetect/mobiledetectlib (3.74.3): Extracting archive Package codeception/phpunit-wrapper is abandoned, you should avoid using it. No replacement was suggested. Package sebastian/resource-operations is abandoned, you should avoid using it. No replacement was suggested. Generating autoload files 59 packages you are using are looking for funding. Use the `composer fund` command to find out more! No security vulnerability advisories found. PS C:\wwwroot\object\src>
4、然后在控制器中实现如下
use Detection\MobileDetect; /** * Displays homepage. * * @return mixed */ public function actionIndex() { $detect = new MobileDetect(); // $deviceType = ($detect->isMobile() ? ($detect->isTablet() ? 'tablet' : 'phone') : 'computer'); if ($detect->isMobile()) { return $this->render('index_mobile'); } return $this->render('index'); }
近期评论