Creating advanced Autoloaders with namespaces and directories

If we want to be sure that our custom classes don’t conflict with any other class in our app,
we will need to add them to a namespace. Using the PSR-0 standard and Composer, we can
easily autoload these classes into Laravel.

Getting ready

For this recipe, we need to set up a standard Laravel installation.

How to do it…

To complete this recipe, follow these steps:
1. Inside the /app directory, create a new directory named custom, and inside of custom,
create a directory named Custom, and in Custom, create a directory named Shapes.

2. Inside the /app/custom/Custom/Shapes directory, create a file named
MyShapes.php and add this code:
<?php namespace Custom\Shapes;
class MyShapes {
public function triangle()
{
return ‘I am a triangle’;
}
}

3. In the root of the application, open the composer.json file and locate the
autoload section. Update it so it looks like this:
“autoload”: {
“classmap”: [
“app/commands”,
“app/controllers”,
“app/models”,
“app/database/migrations”,
“app/database/seeds”,
“app/tests/TestCase.php”,
],
“psr-0”: {
“Custom”: “app/custom”
}
}

4. Open the command line and run dump-autoload on Composer:
php composer.phar dump-autoload.

5. Now we can call that class by using its namespace. For example, if we create a route:
Route::get(‘shape’, function()
{
$shape = new Custom\Shapes\MyShapes;
return $shape->triangle();
});

How it works…

Namespaces are a powerful addition to PHP, and they allow our classes to be used without
us having to worry about their class names interfering with other class names. By autoloading
namespaces in Laravel, we could create a complex group of classes and never have to worry
about class names conflicting with other namespaces.
For our purposes, we’re loading the custom class through composer, and the PSR-0 standard
of autoloading.

There’s more…

To further extend the use of our namespaced class, we could use the IoC to bind
it to our app. More information can be found in the Laravel documentation at
http://laravel.com/docs/ioc.

Leave a Reply

Your email address will not be published. Required fields are marked *