Model namespace hierarchy in Laravel 4

Jul 10, 2013   #php  #composer 

When you’ve been working on a couple of projects, you know that it doesn’t take long before clutter starts to form in the nice simplified structure of any project.

Of course this also holds true for Laravel 4, but when looking over the documentation it does however not explain how to structure you project in a way that it can grow without clutter. I’m not talking about packages though, just simple models.

So how does it work? Is there some kind of naming convention? PRS-0? Namespaces and filenames? Not really..

##Namespaces or PSR-0? Who cares?!! Laravel surely don’t care about this. It uses Composer for lazy-loading the missing classes. This is why you can’t find any documentation on how to do this with Laravel. You were looking in the wrong direction. But fear not. It is very simple to do with Composer.

##Using Composer

When using Composer and you have defined something like this in composer.json (Laravel does this):

{

	"autoload": {
		"classmap": [
			"app/models",
            …
		]
	},

}

and run composer.phar dump-autoload from the command line, Composer will traverse through all subdirectories in app/models and register all classes and namespaces (if any) that it finds in the PHP files. It will use this information to create a map, a classmap.

like so:


'SomeClass' => $baseDir . '/app/models/XXX/SimonsClass.php',
'TestCase' => $baseDir . '/app/tests/TestCase.php',
'Update' => $baseDir . '/app/models/Update.php',
'UpdateGalleryHelper' => $baseDir . '/app/helpers/UpdateGalleryHelper.php',
'BaseX\\API\\Base' => $baseDir . '/app/models/BaseX/API/Base.php',
'BaseX\\API\\Gallery' => $baseDir . '/app/models/BaseX/API/Gallery.php',
'BaseX\\ApiRequest' => $baseDir . '/app/libraries/BaseX/ApiRequest.php',

This means that as long as you don’t create duplicate names of your classes, you can name them whatever you want and Composer will pick up the bill.

This is why Laravel don’t care. It relies on Composer for the execution of the environment. This is the advantage of Laravel, it relies very much on well-tested third-party implementations.

composer.phar dump-autoload is your friend. Create the hierarchy you want and make Composer sort it out.