Mobile phones are taking over the world and, by extension, the web. Aside from the growth of responsive web design, websites are increasingly designing specific versions of their sites for mobile devices.

In this article we'll introduce MobileDetectBundle, which detects mobile devices and helps you redirect users to the appropriate version of your website. Once installed, this is the only configuration you need to setup the usual scenario of redirecting mobile users to the m. host of your website:

1
2
3
4
5
6
7
8
# app/config/config.yml
mobile_detect:
    redirect:
        mobile:
            is_enabled: true
            host: http://m.example.com
            action: redirect
        detect_tablet_as_mobile: true

Read the official documentation of this bundle to learn how to configure more complex redirection scenarios.

Apart from redirecting users, this bundle also provides a mobile_detector service which allows you to detect device types, operating systems and even vendors:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
$device = $this->get('mobile_detect.mobile_detector');

// basic device detection
$device->isMobile();
$device->isTablet();

// fine-grained device detection
$device->isIphone();
$device->isIpad();
$device->isSamsung();

// device operating system
$device->isIOS();
$device->isAndroidOS();

All these methods are also available in your Twig templates via the equivalent functions provided by the bundle:

1
2
3
4
5
6
7
8
9
{% extends is_mobile() ? 'mobile/layout.html.twig': 'layout.html.twig' %}

{% if is_android_os() %}
    Download our application from the store.
{% endif %}

{% if is_device('samsung') %}
    Thinking about buying an iPhone? Check out our deals!
{% endif %}

About the author

MobileDetectBundle is developed by Nikolay Ivlev, a Symfony developer from Moscow (Russia).

We're looking for the next bundle

Do you know any other useful Symfony bundle which is not well-known by the community yet? Tell us about it in the comments below or send us an email to javier.eguiluz@sensiolabs.com and we'll feature it in the next article of this series!