组织 Laravel 和自动加载子目录
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/17393853/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Organizing Laravel and autoloading sub directories
提问by ipengineer
I am wanting to structure my laravel app in a way that all of my code is under the src
directory. My project structure would look something like the below. How would I do this where I can still call Route::get('accounting/item/{id}','AccountingItemController@getId')
我想以我的所有代码都在src
目录下的方式构建我的 Laravel 应用程序。我的项目结构如下所示。我将如何做到这一点,我仍然可以打电话Route::get('accounting/item/{id}','AccountingItemController@getId')
I am wanting to avoid adding every module under src to the ClassLoader. Is there a way to tell the class loader to load all sub-directories under the parent directory src?
我想避免将 src 下的每个模块添加到 ClassLoader。有没有办法告诉类加载器加载父目录src下的所有子目录?
app
app/src
app/src/accounting
app/src/accounting/controllers
app/src/accounting/models
app/src/accounting/repos
app/src/accounting/interfaces
app/src/job
app/src/job/controllers
app/src/job/models
app/src/job/repos
app/src/job/interfaces
回答by Jason Lewis
Yes, it's called PSR-0.
是的,它被称为 PSR-0。
You should namespace all of your code. Typically you'll have a vendor name that you'll use a the top level namespace. Your application structure should then look something like this.
您应该命名所有代码。通常,您将有一个供应商名称,您将使用顶级命名空间。您的应用程序结构应该如下所示。
app/src/Vendor/Accounting/Controllers
app/src/Vendor/Job/Controllers
Your controllers will then be namespaced accordingly.
然后您的控制器将被相应地命名。
namespace Vendor\Accounting\Controllers;
And when using them in routes.
在路由中使用它们时。
Route::get('accounting/item/{id}','Vendor\Accounting\Controllers\ItemController@getId');
Lastly, you can register your namespace with Composer in your composer.json
.
最后,您可以在composer.json
.
"autoload": {
"psr-0": {
"Vendor": "app/src"
}
}
Of course, if you don't want that top level Vendor
namespace you can remove it, but you'll need to register each component as PSR-0.
当然,如果您不想要顶级Vendor
命名空间,您可以将其删除,但您需要将每个组件注册为 PSR-0。
"autoload": {
"psr-0": {
"Accounting": "app/src",
"Job": "app/src",
}
}
Once done, run composer dump-autoload
once and you should be able to add new controllers, models, libraries, etc. Just make sure the directory structure aligns with the namespacing of each file.
完成后,运行composer dump-autoload
一次,您应该能够添加新的控制器、模型、库等。只要确保目录结构与每个文件的命名空间对齐即可。
回答by Aljana Polanc
Do you have composer installed? You should use this:
你有没有安装作曲家?你应该使用这个:
composer dump-autoload
composer dump-autoload
But you can could add directories to the Laravel's classloader. Check the reference here: http://laravel.com/api/class-Illuminate.Support.ClassLoader.html
但是您可以将目录添加到 Laravel 的类加载器。检查这里的参考:http: //laravel.com/api/class-Illuminate.Support.ClassLoader.html