Code Happy: Autoloading Classes

← Back to Index

Please note that this chapter was written for VERSION 3 of the Laravel PHP Framework.

With many frameworks knowing where to put your files, and how to load class definitions can be a tricky topic. However with Laravel there are no strict rules applied to the layout of your application. Laravel's auto loader is a clever library which simplifies the loading of classes with various naming or sub-folder conventions. It is flexible enough to handle the addition of complex libraries or packages with ease. Let's have a look at the functions we have available.

Mappings

Mappings are the simplest method of loading classes, you can pass the auto loader an array of Class name to file location key-value pairs and Laravel will handle the rest. It's efficient autoloader will only load the required class definition when the class is used. By default the Autoloader mappings are set within the start.php file, you can however use the class from anywhere, but the start.php file is a good choice due to it being loaded early. Let's take a look at a mapping..

<?php

// application/start.php

Autoloader::map(array(
    'Cloud'     => path('app').'libraries/ff/cloud.php',
    'Tifa'      => path('app').'libraries/ff/tifa.php',
));

The path('app') is a handy helper method to retrieve the absolute path to your projects application folder. You can also retrieve absolute paths to other folders using the path() method, here is a short list.

| Method          | Directory        |
|-----------------|------------------|
| path('app')     | application      |
| path('sys')     | laravel          |
| path('bundle')  | bundles          |
| path('storage') | storage          |

In the mapping example, you will see that we specify our Class name as the array index, and the file and location as the value. So if we wish to use the Cloud class..

<?php

$c = new Cloud();

Laravel's autoloader will 'detect' (php magic methods) that a class definition needs to be loaded, it will look at the mapping definitions to see if our Class exists there, and proceed to include() the source.

Directory Mapping

If you have a number of Classes which follow the Class name to lower-case file name pattern, you may want to specify the directory, rather than each file individually. You can do this by using the directories() method of the Autoloader, however this time you need only supply an array of values as locations and file names. For example..

<?php

Autoloader::directories(array(
    path('app').'smurfs'
));

Now all of our classes inside the application/smurfs directory will be auto loaded, so long as their file name matches the lower-case of their Class name.

Namespace Mapping

PHP 5.3 saw the arrival of name-spacing. Although far from perfect, name-spacing allows the PSR-0 convention of loading files. Under the PSR-0, namespaces are used to indicate directory structure, and class names are used to identify the file name, therefore we can assume that..

<?php namespace Paladin\Mage;

class Princess
{
    // so pretty
}

will live in the file..

paladin/mage/princess.php

Before we can use this convention, Laravel needs to know where our root namespace directory is. We can help it find our files by using the namespaces() method of the Autoloader class, for example..

<?php

Autoloader::namespaces(array(
    'Paladin'   => path('libraries').'paladin'
));

As you can see we pass an array to the method. The array key represents the name of the root namespace, in this case Paladin and the and array value is used to indicate the root folder that is matched by this namespace, in my example application/libraries/paladin.

Mapping Underscores

Well we don't actually need to map the underscore, it's sitting right there on the keyboard, always watching, judging... Look I'm sorry underscore, I may abuse you a little but it's purely out of love. Camel-casing simply looks wrong to me!

Sorry about that outburst, we will discuss it later in private. The reason that the title is named mapping underscores is because in 'ye olde' days of PHP, before namespaces (and Laravel) had arrived many developers chose to use underscores within file names to separate sub directories. Laravel offers the underscored method on the Autoloader to accommodate this type of class loading. Once more pass an array with the key representing the class prefix and the value representing the root directory, for example..

<?php

Autoloader::underscored(array(
    'Paladin'   => path('app').'jobs/pld'
));

and now the Class Paladin_Light_Knight will have its definition loaded from the file application/jobs/pld/light/knight.php.

So now that you know how to auto load your classes with Laravel, you will no longer have to plaster your source code with include() statements!

My books are available online for free to encourage learning. However, if you'd like for me to keep writing, then please consider buying a digital copy over at Leanpub.com.

It's available in PDF, ePub, and Kindle format, and contains a bunch of extras that you won't find on the site. I have a full-time job, and I write my books in my spare time. Please consider buying a copy so that I can continue to write new books from the comfort of my sofa!