How can I autoload a custom class in Laravel 5.1?

前端 未结 4 1447
栀梦
栀梦 2021-02-08 21:34

I\'ve created a library folder within the app folder to add my own classes.

This is the content of the file app/library/helper.p

4条回答
  •  清酒与你
    2021-02-08 21:40

    Your autoloading configuration is almost good, but you have

    • got the namespaces wrong
    • got the paths wrong

    To fix the problem, adjust your autoloading configuration:

    {
        "autoload": {
            "classmap": [
                "database"
            ],
            "psr-4": {
                "App\\": "app/"
            }
        }
    }
    

    Then rename the directory /library to /Library (note the case).

    Then rename the file /app/Library/helper.php to /app/Library/MyHelper.php (note how class name should match the file name).

    Then adjust the namespace of the class provided by /app/Library/MyHelper to match the PSR-4 prefix (and thus the structure of your project), as well as usages of the class:

    namespace App\Library;
    
    class MyHelper 
    {
        public function v($arr)
        {
            var_dump($arr);
        }
    }
    

    For reference, see:

    • http://www.php-fig.org/psr/psr-4/

提交回复
热议问题