Developed with love by KnpLabs Hire us for your project!
191

MobileDetectBundle

by suncat2000

Symfony2 bundle for detect mobile devices, manage mobile view and redirect to the mobile and tablet version.

MobileDetectBundle

Symfony2 bundle for detect mobile devices, manage mobile view and redirect to the mobile and tablet version.

Build Status Latest Stable Version Total Downloads

knpbundles.com

Introduction

This Bundle use Mobile_Detect class and provides the following features:

  • Detect the various mobile devices by Name, OS, browser User-Agent
  • Manages site views for the variuos mobile devices (mobile, tablet, full)
  • Redirects to mobile and tablet sites

Switch device view

For switch device view, use device_view GET parameter:

http://site.com?device_view={full/mobile/tablet}

Installation

Composer

Add to composer.json in your project to require section:

{
    "suncat/mobile-detect-bundle": "0.10.*"
}

Run command:
php composer.phar install

Add this bundle to your application's kernel

//app/AppKernel.php
public function registerBundles()
{
    return array(
         // ...
        new SunCat\MobileDetectBundle\MobileDetectBundle(),
        // ...
    );
}

Configure service in your YAML configuration

#app/config/config.yml
mobile_detect:
    redirect:
        mobile: ~
        tablet: ~
    switch_device_view: ~

Full configuration

You can change default behaviour of your redirects with action parameter:

  • redirect: redirects to appropriate host with your current path
  • no_redirect: no redirection (default behaviour)
  • redirect_without_path: redirects to appropriate host index page
#app/config/config.yml
mobile_detect:
    redirect:
        full:
            is_enabled: true            # default false
            host: http://site.com       # with scheme (http|https), default null, url validate
            status_code: 301            # default 302
            action: redirect            # redirect, no_redirect, redirect_without_path
        mobile:
            is_enabled: true            # default false
            host: http://m.site.com     # with scheme (http|https), default null, url validate
            status_code: 301            # default 302
            action: redirect            # redirect, no_redirect, redirect_without_path
        tablet:
            is_enabled: true            # default false
            host: http://t.site.com     # with scheme (http|https), default null, url validate
            status_code: 301            # default 302
            action: redirect            # redirect, no_redirect, redirect_without_path
        detect_tablet_as_mobile: true   # default false
    switch_device_view:
        save_referer_path: false        # default true
                                        # true  redirectUrl = http://site.com/current/path?currentQuery=string
                                        # false redirectUrl = http://site.com
    service:
        mobile_detector: mobile_detect.mobile_detector.default
    device_view_class: SunCat\MobileDetectBundle\Helper\DeviceView
    request_listener_class: SunCat\MobileDetectBundle\EventListener\RequestListener
    extension_class: SunCat\MobileDetectBundle\Twig\Extension\MobileDetectExtension

You can also create route specific rules for redirecting in your routing.yml.
Just put appropriate platform to options field and add it redirecting rule.

#routing.yml
someaction:
    pattern:  /someaction
    defaults: { _controller: YourBundle:Index:someaction }
    options:  { mobile: redirect, tablet: no_redirect, full: redirect_without_path }         # redirect, no_redirect, redirect_without_path

PHP examples

Check type device

$mobileDetector = $this->get('mobile_detect.mobile_detector');
$mobileDetector->isMobile();
$mobileDetector->isTablet()

Check phone

is[iPhone|HTC|Nexus|Dell|Motorola|Samsung|Sony|Asus|Palm|Vertu|GenericPhone]

$mobileDetector->isIphone();
$mobileDetector->isHTC();
etc.

Check tablet

is[BlackBerryTablet|iPad|Kindle|SamsungTablet|HTCtablet|MotorolaTablet|AsusTablet|NookTablet|AcerTablet|
YarvikTablet|GenericTablet]

$mobileDetector->isIpad();
$mobileDetector->isMotorolaTablet();
etc.

Check mobile OS

is[AndroidOS|BlackBerryOS|PalmOS|SymbianOS|WindowsMobileOS|iOS|badaOS]

$mobileDetector->isAndroidOS();
$mobileDetector->isIOS();

Check mobile browser User-Agent

is[Chrome|Dolfin|Opera|Skyfire|IE|Firefox|Bolt|TeaShark|Blazer|Safari|Midori|GenericBrowser]

$mobileDetector->isChrome();
$mobileDetector->isSafari();

Twig Helper

{% if is_mobile() %}
{% if is_tablet() %}
{% if is_device('iphone') %} # magic methods is[...]
{% if is_ios() %}
{% if is_android_os() %}
{% if is_full_view() %}
{% if is_mobile_view() %}
{% if is_tablet_view() %}
{% if is_not_mobile_view() %}
{{ full_view_url() }}

Twig examples

{% extends is_mobile() ? "MyBundle:Layout:mobile.html.twig" : "MyBundle:Layout:full.html.twig" %}
{% if is_mobile_view() %}
    {% extends "MyBundle:Layout:mobile.html.twig" %}
{% else if is_tablet_view() %}
    {% extends "MyBundle:Layout:tablet.html.twig" %}
{% else if is_full_view() or is_not_mobile_view() %}
    {% extends "MyBundle:Layout:full.html.twig" %}
{% endif %}
{% if is_device('iphone') %}
    <link rel="stylesheet" href="{{ asset('css/iphone.css') }}" type="text/css" />
{% endif %}
{% if is_mobile_view() %}
    <link rel="canonical" href="{{ full_view_url() }}" />
{% endif %}

Usage Example:

Setting up redirection to and from a mobile site that is the same Symfony 2 instance as your main site.

In this example, let's assume that you have a website http://site.com and you wish to activate
redirection to a mobile site http://m.site.com when the user is using a mobile device.

Additionally, when a user with a desktop browser reaches the mobile site http://m.site.com, he
should be redirected to the full version at http://site.com.

  1. Set up mobile redirection to your config.yml

    mobile_detect:
        redirect:
            mobile:
                is_enabled: true
                host: http://m.site.com
                status_code: 301
                action: redirect
            tablet: ~
        switch_device_view: ~
    

    Now when you hit http://site.com with a mobile device, you are redirected to http://m.site.com.
    At this point if the http://m.site.com is configured to point to your project, you will get circular reference error.
    To get rid of the circular reference error, we want to disable mobile redirecting when we land on our mobile site.

  2. Crete a new app.php file with a name like, for example, app_mobile.php and change the following:
    php
    $kernel = new AppKernel('prod', false);

    to:
    php
    $kernel = new AppKernel('mobile', false);

    Now your mobile site has its own environment and we can nicely create some custom configuration for it, disable
    mobile redirecting and activate desktop redirection instead.

  3. Create config_mobile.yml next to your config.yml and disable mobile redirecting. This should take care of the circular
    reference errors. Adding the full configuration activates desktop redirection.

    Also you might want to define your routing file as mobile specific. If you do, just create new routing_mobile.yml
    file and use it just like the default routing.yml. This gives you nice opportunity to route requests to
    custom mobile specific controllers that can render views that are designed for mobile. This way you don't need to write
    platform specific conditions to your view files.

    framework:
        router:
            resource: "%kernel.root_dir%/config/routing_mobile.yml"
    
    mobile_detect:
        redirect:
            mobile:
                is_enabled: false
            tablet: ~
            full:
                is_enabled: true
                host: http://site.com
        switch_device_view: ~
    
  4. Configure your http server: Make sure that in your http server virtual host, you make http://m.site.com use app_mobile.php as its script file
    instead of app.php.

    After you have restarted your http server everything should work.
    Also remember to clear the cache if you do changes to configs or you might end to get frustrated for nothing.

TODO

  • Write more tests
  • Add twig function url_for_switch_view('mobile') for generating switch view url's
Copyright (c) 2012 Ivlev Nikolay

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is furnished
to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
mobile_detect:
redirect:
mobile: # Required
is_enabled: false
host: ~
status_code: 302
tablet: # Required
is_enabled: false
host: ~
status_code: 302
switch_device_view: # Required
save_referer_path: true
  • Fixes #63: Doubled up query string after redirect.
    By , 2 years ago
  • Fixed typo in test name.
    By netmikey, 2 years ago
  • Fixes #62: Symfony 2.3 is now the minimum required version.
    By netmikey, 2 years ago
  • Added full_view_url() twig function.
    By netmikey, 2 years ago
  • Merge pull request #60 from sfdumi/dev-overrideable
    By netmikey, 2 years ago
  • Reverted change made to scope check
    By sfdumi, 2 years ago
  • Fixed console issue with synthetic service
    By sfdumi, 2 years ago
  • Updated mobiledetect dependency to 2.8.*
    By netmikey, 2 years ago
  • sm doc fix
    By suncat2000, 2 years ago
  • Merge pull request #58 from netmikey/desktop_redirect
    By suncat2000, 2 years ago
  • Merge branch 'master' into desktop_redirect
    By netmikey, 2 years ago
  • Added desktop (full view) redirection. This involved rewriting a solid
    By netmikey, 2 years ago
  • markdown doc fixes
    By suncat2000, 2 years ago
  • Merge pull request #57 from customer-alliance/listener-update-request
    By suncat2000, 2 years ago
  • Update MobileDetector user agent after master request
    By mhlavac, 2 years ago
  • add new info to readme
    By suncat2000, 2 years ago
  • Merge pull request #53 from netmikey/fix_deviceview_query
    By suncat2000, 2 years ago
  • Merge pull request #52 from escapestudios/master
    By suncat2000, 2 years ago
  • Merge pull request #54 from netmikey/fix_travis_build
    By suncat2000, 2 years ago
  • Updates the phpunit version to ~4.1, which should fix Travis builds
    By netmikey, 2 years ago
  • Fixes #50: Query string gets lost on "device_view=XXX"
    By netmikey, 2 years ago
  • Allow mobile OS-check via Twig filter
    By djoos, 2 years ago
  • Merge pull request #46 from ricoli/add-tag-to-listener-service
    By suncat2000, 3 years ago
  • added tag for response event
    By ricoli, 3 years ago
  • priority of 1 to request listener
    By ricoli, 3 years ago
  • Merge pull request #45 from ricoli/detect-tablet-as-mobile-tests-cleanup
    By suncat2000, 3 years ago
  • added event listener tag to request listener config
    By ricoli, 3 years ago
  • clean up of tests because of new default
    By ricoli, 3 years ago
  • revert last commit
    By ricoli, 3 years ago
  • cleaned up tests because of new default
    By ricoli, 3 years ago