The component, packaged as a plugin, is available at GitHub.
CakePHP’s built-in CakeRequest object can easily determine if a request is from a mobile device:
However, sometimes an application needs finer control over what to serve certain devices, such as a mobile layout to smartphones and a desktop layout to tablets. The MobileDetect project is a “lightweight PHP class for detecting mobile devices”. This component, packaged as a plugin, makes MobileDetect available in a CakePHP controller.
Tested with CakePHP 2.3.x, but should work fine with any CakePHP 2.x version.
In your project
1 2 3 4 5 6 7 8
This will install the plugin into
Plugin/MobileDetect, and install the Mobile_Detect lib
(from Packagist) into your
In your app’s
Config/bootstrap.php, import composer’s autoload file:
You will need the component (packaged as a plugin), and the MobileDetect PHP library (not included). The MobileDetect library needs to be in this plugin’s Vendor directory and must be named ‘MobileDetect’. Using git, something like this:
The MobileDetect library could also be added as a git submodule…
The component has only one method, named
detect. It accepts two arguments: the method to pass to
the MobileDetect library, and any arguments for the passed method.
Example: check if a request is from a tablet:
$result = $this->MobileDetect->detect('isTablet');
Example: check if a request is from an iOS device :
$result = $this->MobileDetect->detect('isiOS');
Example: get version number of an Android device:
$result = $this->MobileDetect->detect('version', 'Android');
See the demo at mobiledetect.net for a list of all available methods.
Let’s say we want to serve a mobile layout to smartphones and a desktop layout to
tablets. Instead of loading the component on every request (by adding it to your controller’s
$components array), we’ll load the component on the fly when needed. This example sets a session
tablet if the request is from a tablet, calling the component only once.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30