Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Organizing Laravel and autoloading sub directories

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')

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?

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
like image 748
ipengineer Avatar asked Dec 15 '22 09:12

ipengineer


2 Answers

Yes, it's called 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.

"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.

"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.

like image 117
Jason Lewis Avatar answered Jan 05 '23 00:01

Jason Lewis


Do you have composer installed? You should use this:

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

like image 21
Aljana Polanc Avatar answered Jan 04 '23 23:01

Aljana Polanc