个性化阅读
专注于IT技术分析

如何在Symfony 3中检测移动设备

本文概述

如今, 人们使用移动设备的次数比以前要频繁得多, 这是一个简单的原因, 即Internet, 这意味着你的网站应该得到优化, 并能够像在台式机上使用网站一样, 为此类设备提供很棒的体验。尽管许多开发人员更喜欢在其网站上使用响应式设计来优化SEO和其他原因, 但是还有其他开发人员针对该网站的同一版本使用子域, 但针对不同的设备进行了优化(例如, 针对平板电脑的www.t.yourweb.com)或www.m.yourweb.com(电话)。响应式设计之间的区别在于, 你无需弄乱服务器上的内容, 例如创建新域并正确配置它们, 而只需更改源代码, 但是, 如果你决定使用子域, 则需要将两者都弄乱(源代码以检测访客是否使用移动设备或台式计算机, 然后配置域)。

在Symfony项目中, 如果使用正确的工具, 则此任务将非常容易。为了检测使用访问者查看你网站的平台, 我们建议你使用移动检测捆绑包。该捆绑包依赖于Mobile Detect项目。 Mobile_Detect是用于检测移动设备(包括平板电脑)的轻量级PHP类。它结合使用User-Agent字符串和特定的HTTP标头来检测移动环境。

在本文中, 你将学习如何在Symfony 3项目中安装和实现Mobile Detect Bundle。

1.安装MobileDetectBundle

MobileDetectBundle是Symfony兼容的2.4.x和3.0.x捆绑软件, 用于检测移动设备, 管理移动视图并重定向到移动和平板电脑版本。它提供以下功能:

  • 通过名称, 操作系统, 浏览器用户代理来检测各种移动设备。
  • 管理各种移动设备(移动设备, 平板电脑, 完整设备)的网站视图。
  • 重定向到手机和平板电脑网站。

要在你的项目中安装此捆绑包, 请打开一个新终端, 切换到项目目录并运行以下composer命令:

composer require suncat/mobile-detect-bundle

另外, 你可以修改composer.json文件并手动将库添加为依赖项:

{
    "require": {
        "suncat/mobile-detect-bundle": "^1.0"
    }, }

然后在该目录上运行composer install。通过composer完成库的安装后, 请继续在AppKernel.php中启用捆绑软件:

<?php
    
public function registerBundles()
{
    $bundles = [
        // ...
        // Enable MobileDetectBundle
        new SunCat\MobileDetectBundle\MobileDetectBundle(), // ...
    ];

    // ... //
}

清除项目的缓存, 即可使用项目中的库。如果你需要有关此捆绑包的更多信息, 请在此处访问Github中的官方存储库。

2.从控制器和视图手动使用Mobile Detect Bundle

此捆绑包中的第一个也是最有用的事情是, 你可以毫不费力地单独使用它提供的许多功能, 并且无需创建自定义的Twig函数即可验证用户从Android设备导航还是从你的其他浏览器导航意见。当你要根据用户访问的平台向用户展示某些广告时, 这非常方便。

通常检查设备类型

在大多数情况下, 你只需要检查用户是否正在从移动设备, 平板电脑或台式计算机上导航即可。根据isTablet或isMobile之类的方法的结果, 可以使用条件语句轻松实现:

<?php

namespace AppBundle\Controller;

use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;

class DefaultController extends Controller
{
    /**
     * @Route("/", name="homepage")
     */
    public function indexAction(Request $request)
    {
        // Retrieve the mobile detector service
        $mobileDetector = $this->get('mobile_detect.mobile_detector');
        
        // Create a flag string to returns as response
        $responseText = "Another kind of device";

        // Verify from the controller if is a tablet
        if($mobileDetector->isTablet()){
            $responseText = "You're using a tablet, our system works only in Desktop computers";

        // Verify if it's a mobile device (tablet is a mobile device too)
        }else if($mobileDetector->isMobile()){
            $responseText = "You're using a mobile device, our system works only in Desktop computers";
        }
        
        return new Response($responseText);
    }
}

在其他情况下, 你不需要从控制器检查此信息, 而只需使用Twig查看视图。幸运的是, 有了这个捆绑包, 你将不需要向Twig公开自定义功能, 因为它已经提供了可以在视图中使用的自定义功能:

{% extends 'base.html.twig' %}

{% block body %}
    {% if is_mobile() %}
        {# Tablets are mobile devices too #}
        <h1>Is a Mobile device</h1>
    {% endif %}

    {% if is_tablet() %}
        <h1>Is a Tablet</h1>
    {% endif %}
{% endblock %}

这样, 你可以验证更复杂的设备模式或根据平台发送某些信息, 而无需重定向到另一个网站。

检查操作系统

你可以使用is *(其中通配符是操作系统标识符)功能检查用户当前正在使用哪个操作系统:

<?php

namespace AppBundle\Controller;

use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;

class DefaultController extends Controller
{
    /**
     * @Route("/", name="homepage")
     */
    public function indexAction(Request $request)
    {
        // Retrieve the mobile detector service
        $mobileDetector = $this->get('mobile_detect.mobile_detector');
        
        // Check for different mobile operative systems
        // They return a boolean (true if match)
        $mobileDetector->isAndroidOS();
        $mobileDetector->isBlackBerryOS();
        $mobileDetector->isPalmOS();
        $mobileDetector->isSymbianOS();
        $mobileDetector->isWindowsMobileOS();
        $mobileDetector->isiOS();
        $mobileDetector->isbadaOS();

        return new Response("Some response text");
    }
}

同样, 你可以在Twig中使用这些功能(仅iOS和Android):

{% extends 'base.html.twig' %}

{% block body %}

    {% if is_android_os() %}
        <h1>Android</h1>
    {% endif %}

    {% if is_ios() %}
        <h1>iOS</h1>
    {% endif %}

{% endblock %}

检查移动浏览器的用户代理

你可以在控制器中检查访问者正在使用哪种浏览器:

<?php

namespace AppBundle\Controller;

use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response; 

class DefaultController extends Controller
{
    /**
     * @Route("/", name="homepage")
     */
    public function indexAction(Request $request)
    {
        $mobileDetector = $this->get('mobile_detect.mobile_detector');

        /*
         * Returns a boolean (true in case the browser matches)
         */
        $mobileDetector->isChrome();
        $mobileDetector->isSafari();
        $mobileDetector->isDolfin();
        $mobileDetector->isOpera();
        $mobileDetector->isSkyfire();
        $mobileDetector->isIE();
        $mobileDetector->isFirefox();
        $mobileDetector->isBolt();
        $mobileDetector->isTeaShark();
        $mobileDetector->isBlazer();
        $mobileDetector->isSafari();
        $mobileDetector->isMidori();
        $mobileDetector->isGenericBrowser();

        return new Response("");
    }
}

3.自动配置移动检测捆绑

这一步可能有点麻烦和棘手。如果在移动设备和台式机的网站上使用多个域, 则可以将主项目配置为重定向到另一个URL, 甚至可以对同一网站使用相同的Symfony项目, 但该项目位于不同的域。

为此, 请按照下列步骤操作:

1.在你的config.yml中配置重定向

第一步, 你想通过在config.yml中添加适当的配置, 将访问你网站(www.yourweb.com)的用户从移动设备重定向到移动域(www.m.yourweb.com)。以下代码段会将访问你网站的所有用户从移动设备(平板电脑和电话)重定向到移动域:

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

请注意, 这只是一个示例, 你甚至可以重定向到平板电脑域。阅读文档中的完整配置区域, 以获取更多信息。

2.创建一个新的应用程序文件

如你所知, 在生产中, 位于yourapp / web中的app.php文件是应用程序的入口。为了为你的应用程序创建移动项, 请复制app.php文件并将其粘贴到具有新名称app_mobile.php的同一目录中。现在搜索以下行(在第9行附近):

$kernel = new AppKernel('prod', false);

此行指定应用于你的应用程序的环境类型(最初有2个应用程序文件app.php和app_dev.php)。现在, 在复制的文件(app_mobile.php)中, 将环境从prod修改为mobile:

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

将更改保存在文件上, 然后继续下一步。

3.创建新的配置文件

现在, 在yourapp / app / config文件夹中创建一个新的config_mobile.yml文件, 并在其中添加以下内容:

imports:
    - { resource: parameters.yml }

framework:
    secret: "%secret%"
    router:
        resource: "%kernel.root_dir%/config/routing_mobile.yml"

mobile_detect:
    redirect:
        mobile:
            is_enabled: false
        tablet: ~
        full:
            is_enabled: true
            host: http://ourcodeworld.com
    switch_device_view: ~

我们正在做的是使用最基本的设置, 框架和mobile_detect创建一个自定义配置文件。在mobile_detect区域中, 我们将指示如果有人通过移动设备访问移动网站, 则应将其重定向到桌面版(完整版), 并且在重定向操作中将禁用移动版。

4.配置你的移动域以定位app_mobile.php文件

最后一步由你决定, 具体取决于你的服务器。你需要指定你的移动域(www.m.yourweb.com)定位到app_mobile.php文件而不是app.php文件。重新启动http服务器后, 所有内容均应正常工作。还请记住, 如果对配置进行了更改, 请清除缓存, 否则你可能一无所获。

编码愉快!

赞(0)
未经允许不得转载:srcmini » 如何在Symfony 3中检测移动设备

评论 抢沙发

评论前必须登录!