Laravel - How to use a vendor class?

扶醉桌前 提交于 2019-12-22 08:12:10

问题


I want to use Mobile Detect on m routes.php file. I have added the package as a require in composer.json and it's installed in the vendor file. How can I use it now?

I tried this answer and no luck because the class wasn't found: 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"
}

EDIT: I tried using this one: https://github.com/jenssegers/Laravel-Agent, but the alias never worked saying the class was not found.


回答1:


This package is PSR-0 namespaced. Looking at the git repo, it appears to be Detection\MobileDetect though you will want to make sure this is indeed the correct namespace. Have you tried adding the proper namespace to your routes.php file?

use Detection\MobileDetect as MobileDetect;

or you can reference the proper namespace inline. Here is an example:

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

If this doesn't work for you, you may be able to get away by adding it to your composer.json classmap:

"autoload": {
    "classmap": ["/vendor/serbanghita/namespaced/"],
}

Of course, fill in the proper path then run a composer dump-auto.




回答2:


I was also struggling with the mobile detection in Laravel, but I found the solution! This is from the beginning (incl. installation):

  • 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');
    

And you are ready to go ;)



来源:https://stackoverflow.com/questions/26432447/laravel-how-to-use-a-vendor-class

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!