如何在 Laravel 5.1 中自动加载自定义类? [英] How can I autoload a custom class in Laravel 5.1?
问题描述
我在 app
文件夹中创建了一个 library
文件夹来添加我自己的类.
I've created a library
folder within the app
folder to add my own classes.
这是app/library/helper.php
文件的内容:
<?php
namespace Library;
class MyHelper
{
public function v($arr)
{
var_dump($arr);
}
}
我将命名空间添加到 composer.json
:
I added the namespace to composer.json
:
然后我跑了
$ composer dump-autoload
但它似乎没有任何影响.
but it does not seem to have any effects.
文件
vendor/composer/autoload_psr4.php
vendor/composer/autoload_classmap.php
没有改变.
如果我尝试创建一个MyHelper
的实例,Laravel会报如下错误:
If I try to create an instance of MyHelper
, Laravel reports the following error:
我不确定我做错了什么.
I'm not sure what I am doing wrong.
推荐答案
你的自动加载配置几乎不错,但你有
Your autoloading configuration is almost good, but you have
- 命名空间错误
- 路径错误
要解决此问题,请调整您的自动加载配置:
To fix the problem, adjust your autoloading configuration:
{
"autoload": {
"classmap": [
"database"
],
"psr-4": {
"App\": "app/"
}
}
}
然后将目录/library
重命名为/Library
(注意大小写).
Then rename the directory /library
to /Library
(note the case).
然后将文件/app/Library/helper.php
重命名为/app/Library/MyHelper.php
(注意类名应该如何与文件名匹配).
Then rename the file /app/Library/helper.php
to /app/Library/MyHelper.php
(note how class name should match the file name).
然后调整 /app/Library/MyHelper
提供的类的命名空间以匹配 PSR-4 前缀(以及项目的结构),以及类的用法:
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 AppLibrary;
class MyHelper
{
public function v($arr)
{
var_dump($arr);
}
}
参考:
这篇关于如何在 Laravel 5.1 中自动加载自定义类?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!