Organizing Laravel and autoloading sub directories

laravel, laravel-4, php

Solution

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.

Problem

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 ```

Original source