你可以在应用程序目录中的某个位置创建一个新目录,例如:
app/libraries
然后在你的composer.json文件中,你可以将
app/libraries
包含在你的自动加载类映射中:
{
"name": "laravel/laravel",
"description": "The Laravel Framework.",
"keywords": ["framework", "laravel"],
"license": "MIT",
"require": {
"laravel/framework": "4.2.*",
},
"autoload": {
"classmap": [
"app/commands",
"app/controllers",
"app/models",
"app/libraries", <------------------ YOUR CUSTOM DIRECTORY
"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",
}
请在修改composer.json文件后务必运行
composer dump-autoload
命令。
假设你的类名为
CustomClass.php
,并且它位于
app/libraries
目录下(因此完整路径为
app/libraries/CustomClass.php
)。如果你已经按照惯例正确地给你的类设置了命名空间,那么你的命名空间可能会被命名为
libraries
。为了清晰起见,我们将使用
custom
作为命名空间名称,以避免与目录混淆。
$class = new \custom\CustomClass();
或者,您可以在app/config/app.php
文件中为其设置别名:
'aliases' => array(
...
'CustomClass' => 'custom\CustomClass',
...
)
您可以像实例化其他类一样,在应用程序的任何地方实例化该类:
$class = new CustomClass()
希望这可以帮助你!
TextCleaner => 'libraries \ TextCleaner'
添加到app / config / app.php别名中。 我尝试使用$imageCleaner = new \ libraries \ TextCleaner()
和$imageCleaner = new TextCleaner();
实例化我的类,但都报错,说类不存在。 是的,我已经成功运行了composer dump-autload。 - Bill Garrisonnamespace helpers;
)。在你的config/app.php文件中,你需要将它包含进去,例如:'TextCleaner' => 'helpers\TextCleaner'
。我编辑了原始答案以帮助澄清。 - eluong