chronon/mobile_detect

一个用于识别移动设备的 CakePHP 插件组件,基于 Mobile_Detect 项目。

1.1.2 2014-08-05 18:34 UTC

This package is not auto-updated.

Last update: 2024-09-14 14:06:05 UTC


README

CakePHP 内置的 CakeRequest 对象可以轻松判断请求是否来自移动设备

$this->request->is('mobile');

然而,有时应用程序需要更精细地控制向特定设备提供的内容,例如为智能手机提供移动布局,为平板电脑提供桌面布局。《MobileDetect》项目是一个“轻量级 PHP 类,用于检测移动设备”。此组件作为插件打包,使 MobileDetect 可在 CakePHP 控制器中使用。

兼容性

已在 CakePHP 2.10.x 上测试,但应与任何 CakePHP 2.x 版本兼容。

注意:此插件与 CakePHP 3.x 不兼容,但 Mobile_Detect 库已包含在 CakePHP 3 的 app 框架 中,可以根据需要使用和扩展,因此无需此插件。

安装

使用 Composer/Packagist

在您的项目 composer.json 文件中

{
	"require": {
		"chronon/mobile_detect": "*"
	},
	"config": {
        "vendor-dir": "Vendor"
    }
}

这将安装插件到 Plugin/MobileDetect,并将 Mobile_Detect 库(从 Packagist)安装到您的 Vendor 目录中。

在您的应用的 Config/bootstrap.php 中,导入 composer 的自动加载文件

<?php
App::import('Vendor', array('file' => 'autoload'));

使用 git

您需要组件(打包为插件),以及 MobileDetect PHP 库(不包括)。MobileDetect 库需要在此插件的正确目录中,并且必须命名为 'MobileDetect'。使用 git,例如

git clone git@github.com:chronon/CakePHP-MobileDetectComponent-Plugin.git app/Plugin/MobileDetect  
git clone git@github.com:serbanghita/Mobile-Detect.git app/Plugin/MobileDetect/Vendor/MobileDetect

用法

该组件只有一个名为 detect 的方法。它接受两个参数:传递给 MobileDetect 库的方法,以及传递方法的任何参数。

示例:检查请求是否来自平板电脑

$result = $this->MobileDetect->detect('isTablet');

示例:检查请求是否来自 iOS 设备

$result = $this->MobileDetect->detect('isiOS');

示例:获取 Android 设备的版本号

$result = $this->MobileDetect->detect('version', 'Android');

请参阅 mobiledetect.net 上的演示,以获取所有可用方法的列表。

示例

假设我们想要为智能手机提供移动布局,为平板电脑提供桌面布局。而不是在每次请求时(通过将其添加到控制器的 $components 数组中)加载组件,我们将在需要时动态加载组件。此示例在请求来自平板电脑时设置会话变量 tablet,只调用组件一次。

Controller/AppController.php

<?php
public function beforeFilter() {
	// check if the request is 'mobile', includes phones, tablets, etc.
	if ($this->request->is('mobile')) {
		if (!$this->_isTablet()) {
			// if the request is mobile, but not a tablet, activate the mobile layout
			$this->_setMobile();
		}
	}
}

protected function _setMobile() {
	$this->theme = 'Mobile';
	// etc...
}

protected function _isTablet() {
	if ($this->Session->check('tablet')) {
		return $this->Session->read('tablet');
	}
	// load the component
	$this->MobileDetect = $this->Components->load('MobileDetect.MobileDetect');
	// pass the component the 'isTablet' method
	$result = $this->MobileDetect->detect('isTablet');
	$this->Session->write('tablet', $result);

	return $result;
}