Laravel:从新的自定义目录加载自定义类 [英] Laravel: load custom class from new custom directory

查看:566
本文介绍了Laravel:从新的自定义目录加载自定义类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前已为我所有的库"添加了一个新文件夹到我的应用程序目录中.我不断收到一个找不到该类的错误,这是我要做的:

I have currently added a new folder to my app directory for all my 'libraries'. I keep recieving an error that the class is not found, this is what I do:

我已将其添加到自动加载值中的composer.json文件中:

I have added it to the composer.json file in the autoload value:

"autoload": {
    "classmap": [
        "app/commands",
        "app/controllers",
        "app/models",
        "app/database/migrations",
        "app/database/seeds",
        "app/tests/TestCase.php",
        "app/services",
        "app/facades",
        "app/libraries" --> here
    ]
},

将其添加到类加载器中的global.php文件中:

Added it to my global.php file in the classloader:

ClassLoader::addDirectories(array(

    app_path().'/commands',
    app_path().'/controllers',
    app_path().'/models',
    app_path().'/database/seeds',
    app_path().'/libraries', --> here

));

在app.php中为其创建别名:

Created an alias for it in app.php:

'aliases' => array(

    'App'               => 'Illuminate\Support\Facades\App',
    'Session'           => 'Illuminate\Support\Facades\Session',
    ...
    'SimpleImage'       => 'App\Libraries\abeautifulsite\SimpleImage', --> here

),

并在我的控制器中调用该类:

And called the class in my controller:

$img = new SimpleImage($file);

我一直收到的错误是找不到该类.我想念什么?

The error I keep receiving is that the class is not found. What am I missing?

ErrorException (E_UNKNOWN) 
Class 'App\Libraries\abeautifulsite\SimpleImage' not found

(PS.我在终端中做了作曲家的转储自动加载)

(PS. I did composer dump-autoload in terminal)

推荐答案

在Laravel项目中添加自定义文件夹的最佳方法是使用PSR-4.

The best way to add a custom folder in your Laravel project is using PSR-4.

首先在/app中创建您的自定义目录,例如:

First of all create your custom directory in /app, for example:

/app/YourName/libraries

现在打开composer.json,并在autoload -> classmap之后添加psr-4结构:

now open composer.json and just after the autoload -> classmap add the psr-4 structure:

"autoload": {
    "classmap": [
        "app/commands",
        "app/controllers",
        "app/models",
        "app/database/migrations",
        "app/database/seeds",
        "app/tests/TestCase.php",
        "app/services",
        "app/facades"
    ],
    "psr-4": {
        "YourName\\": "app/YourName"
    }
},

请注意,我删除了您的/app/libraries行,然后运行:

Note that I removed your /app/libraries row, then run:

composer dump-autoload

通过这种方式,您将添加到 YourName 文件夹中的所有文件夹将被加载.

In this way all the folders you will add in YourName folder will be loaded.

例如:

app/ChristianGiupponi/libraries

"psr-4": {
    "ChristianGiupponi\\": "app/ChristianGiupponi"
 }

这篇关于Laravel:从新的自定义目录加载自定义类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆