How can I autoload a custom class in Laravel 5.1?

99封情书 提交于 2019-12-03 06:31:14

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:

Use files directive in composer.json: https://getcomposer.org/doc/04-schema.md#files

{
    "autoload": {
        "files": ["app/library/helper.php"]
    }
}

I know this question was answered a while ago, but the reason it isn't working is that you need to give the namespace that corresponds with the file structure. Therefore, since the Library class is inside the App folder you need:

namespace App\Library;

class MyHelper{
    public function v($arr){
        var_dump($arr);
    }
}

Additionally, if you are going to call the class MyHelper, you need to call the file MyHelper.php

Use composer.json :

   "autoload": {
    "classmap": [
        "database",
        "app/Transformers"
    ]
 },

Add your auto load directories like I added app/Transformers.

Don't Forget to add run composer dump-autoload.

The only problem with this method is you need to run composer dump-autoload whenever you add new class do that directory.

Or You can use "Files" in composer.json.

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