Laravel - 如何使用供应商类?

6
我希望在我的routes.php文件中使用Mobile Detect。我已经将该软件包添加为composer.json中的要求,并安装在vendor文件夹中。现在我该如何使用它?
我尝试了这个答案,但没有成功,因为找不到该类:Laravel 4 using vendor classes
{
    "name": "laravel/laravel",
    "description": "The Laravel Framework.",
    "keywords": ["framework", "laravel"],
    "license": "MIT",
    "require": {
        "laravel/framework": "4.2.*",
        "mobiledetect/mobiledetectlib": "*"
    },
    "autoload": {
        "classmap": [
            "app/commands",
            "app/controllers",
            "app/models",
            "app/database/migrations",
            "app/database/seeds",
            "app/tests/TestCase.php"
        ]
    },
    "scripts": {
        "post-install-cmd": [
            "php artisan clear-compiled",
            "php artisan optimize"
        ],
        "post-update-cmd": [
            "php artisan clear-compiled",
            "php artisan optimize"
        ],
        "post-create-project-cmd": [
            "php artisan key:generate"
        ]
    },
    "config": {
        "preferred-install": "dist"
    },
    "minimum-stability": "stable"
}

编辑:我尝试使用这个:https://github.com/jenssegers/Laravel-Agent,但是别名从未起作用,显示找不到该类。


1
你可以尝试运行 php artisan dump-autoloadcomposer dump-autoload 或者 php composer.phar dump-autoload 吗? - Sam
我做了这个。现在怎么办? - jstudios
有一定机会能够修复它,我假设你仍然遇到了“class not found”的问题?确保你没有命名空间的问题(请参考@MatthewBrown)。 - Sam
Sam,我认为他的问题更多地涉及名称空间以及如何/什么使用基本观点来调用它。这也是我的问题。我正在寻找@Matthews的答案。 - blamb
2个回答

9

这个包使用PSR-0命名空间。从git repo中看,它似乎是Detection\MobileDetect,但你需要确保这确实是正确的命名空间。你尝试过在routes.php文件中添加正确的命名空间吗?

use Detection\MobileDetect as MobileDetect;

或者您可以直接引用适当的名称空间。以下是一个示例:

$detect = new Detection\MobileDetect\Mobile_Detect;
$deviceType = ($detect->isMobile() ? ($detect->isTablet() ? 'tablet' : 'phone') : 'computer');

如果这对您无效,您可能可以通过将它添加到您的composer.json类映射中来获得帮助:
"autoload": {
    "classmap": ["/vendor/serbanghita/namespaced/"],
}

当然,填写正确的路径后运行composer dump-auto

之后我该怎么使用它?我尝试在下面加上$detect = new MobileDetect();,但是提示Class 'Detection\MobileDetect' not found - jstudios
尝试使用答案中的classmap部分,确保填写正确的Mobile_Detect.php文件夹路径。 - Matthew Brown
如果您将其添加到类映射中并运行composer dump-auto,则应该能够直接引用该类,而无需使用命名空间。现在当您尝试$detect = new Mobile_Detect;时会发生什么? - Matthew Brown
没错,但是当你自动加载类时,你不需要担心命名空间。尝试:$detect = new Mobile_Detect; 另外,请问您能否更新您的答案并提供您的类映射表? - Matthew Brown
我按照你之前建议的尝试了Mobile_Detect,但是没有成功。请看我在原始帖子末尾的编辑,那样是否更容易解决问题?但是我也无法让它起作用。 - jstudios
显示剩余2条评论

2

我也曾在Laravel中遇到移动设备检测的问题,但我找到了解决方案!以下是从安装开始的步骤:

  • in the terminal in your Laravel project folder:

    $ composer require mobiledetect/mobiledetectlib
    
  • in a Middleware file for mobile detection:

    use Mobile_Detect;
    
    ...
    
    $detect = new Mobile_Detect;
    
    if ($detect->isMobile()) var_dump('is mobile');
    else var_dump('is not mobile');
    

你已经准备就绪啦 ;)


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接