hocvt/browser-detect

Laravel 的浏览器和移动设备检测包。

v5.0.4 2024-01-30 16:49 UTC

This package is auto-updated.

Last update: 2024-08-30 01:50:03 UTC


README

Browser Detection Logo

浏览器检测 v5.0 by hisorange

Latest Stable Version Build Coverage Status Total Downloads License

易于使用的包,用于识别访客的浏览器详细信息和设备类型。这里没有魔法,结果是由多个经过充分测试和开发的包生成的。

支持 4.010.x 之间的所有 Laravel 版本;也在 5.68.2 之间的所有 PHP 版本上进行了测试。

如何安装

composer require hisorange/browser-detect

是的,它已经准备好供您使用了! ^.^

如何使用

在您的代码中,只需调用 Browser 门面

use Browser;

// Determine the user's device type is simple as this:
$isMobile = Browser::isMobile();
Browser::isTablet();
Browser::isDesktop();

if (Browser::isMobile()) {
  // Redirect to the mobile version of the site.
}

// Every wondered if it is a bot who loading Your page?
if (Browser::isBot()) {
    echo 'No need to wonder anymore!';
}

// Check for common vendors.
if (Browser::isFirefox() || Browser::isOpera()) {
    $response .= '<script src="firefox-fix.js"></script>';
}

// Sometimes You may want to serve different content based on the OS.
if (Browser::isAndroid()) {
    $response .= '<a>Install our Android App!</a>';
} elseif (Browser::isMac() && Browser::isMobile()) {
    $response .= '<a>Install our iOS App!</a>';
}

即使在您的 blade 模板中

@mobile
    <p>This is the MOBILE template!</p>
    @include('your-mobile-template')
@endmobile

@tablet
    <p>This is the TABLET template!</p>
    <link rel="stylesheet" href="tablet.css" title="Reduce the page size, load what the user need">
@endtablet

@desktop
    <p>This is the DESKTOP template!</p>
@enddesktop

{-- Every result key is supported --}
@browser('isBot')
    <p>Bots are identified too :)</p>
@endbrowser

简单易行,不是吗?

版本支持

以下矩阵已经由伟大的 GitHub Actions 持续测试!

自 2013 年以来,该包已针对所有可能的 PHP/Laravel 版本矩阵运行测试。

独立模式,无需 Laravel!

基于社区请求;现在您可以使用库而无需 Laravel。只需简单地使用 Parser 类作为静态对象。

use hisorange\BrowserDetect\Parser as Browser;

if (Browser::isLinux()) {
    // Works as well!
}

可用的 API 调用

每个对 Browser 门面的调用都代理到结果对象,因此以下信息也在您的结果上可用,您可以使用 [数组] 语法来访问它们。

配置,个性化

如果您正在使用 Laravel,则安装后运行以下命令

# Will copy a config file to ~/app/config/browser-detect.php
php artisan vendor:publish

为独立模式应用自定义配置

use hisorange\BrowserDetect\Parser;

$browser = new Parser(null, null, [
    'cache' => [
        'interval' => 86400 // This will override the default configuration.
    ]
]);

$result = $browser->detect();

由于该包旨在易于使用,因此没有太多可配置的。但您可以自定义缓存和安全值。

高级使用信息

代码设计为易于使用,因此您在 Browser 门面上发出的每个调用都将访问结果对象并为您获取数据,但您也可以解析除当前用户代理之外的代理。

// When You call the detect function You will get a result object, from the current user's agent.
$result = Browser::detect();

// If You wanna get browser details from a user agent other than the current user call the parse function.
$result = Browser::parse('Opera/9.80 (Windows NT 6.0) Presto/2.12.388 Version/12.14');

值得注意!解析器只解析每个用户代理字符串一次,然后将其缓存,它使用内存中的运行时缓存来处理单个页面加载中的多个调用;它还将使用应用程序的缓存来持久化结果约一周,这应该为您提供了足够的缓存机制,以便检测的成本低于 0.02 毫秒,这是通过 80,000 次假访问测试的。

变更日志

CHANGELOG 文件中查看详细更改。