1. What is Autoloading

One of the biggest annoyances is having to write a long list of needed includes at the beginning of each script.

Problem: Supposing that you are developing an application and you have a long list of libraries that needed to be loaded.

Solution: Load all of classes at the beginning of your script and you will be able to use any one of these classes anywhere in your application.

Better Solution: Whenever I use a class, I go and load it, so my application doesn’t have to load all classes each request, this is called “Autoloading”. But how to achieve that?… let us figure out:

2. Let us Create our Autoloader

The simplest solution, we include all the files:

<?php

// Classes/A.php

class A {} <?php

// Classes/B.php

class B {} <?php

// index.php

include_once 'Classes/A.php';

include_once 'Classes/B.php'; // load A class

$a = new A(); // check the list of all loaded files

var_dump(get_included_files());

The script index.php will output:

array(3) {

[0]=> string(20) "/path/to/root/index.php"

[1]=> string(24) "/path/to/root/Classes/A.php"

[2]=> string(24) "/path/to/root/Classes/B.php"

}

Which means that we loaded all the files whether we used class B or not, and as long as your project is going bigger and bigger, this way is not going to work.

Here comes the Autoloading to solve the problem:

<?php

// index.php // my custom autoloader

function my_autoloader($class) {

include 'Classes/' . $class . '.php';

}



// register the autoloader

spl_autoload_register('my_autoloader');



// load A class

$a = new A();



// check the list of all loaded files

var_dump(get_included_files());

You write the way you do “mapping” between class name and its file path in my_autoloader() function and register it in your script so you tell your script that any time you instantiate a class, just go and look for it through this function and load it. Now, check the number of files loaded in your script:

array(2) {

[0]=> string(50) "/path/to/demos/autoload-2/index.php"

[1]=> string(54) "/path/to/demos/autoload-2/Classes/A.php"

}

Now, your script loads the files that it just needs.

PHP is telling you “I will give you the chance to go and load your class even if you didn’t load it before your statement $a = new A(); after that, I will throw an error if it didn’t work”.

The preceding example works alright, but you have to consider the following:

File name should have the same class name. Every single file should have only one class. Sensitivity in classes names and files names.

You can handle all these situations with your own implementation, and any application can do its own mapping based on its file structure, but in order to use this autoloader, you have to follow the preceding considerations.

Composer comes up with a way that suits most of structures (or you can say that it forces the applications to choose between), let us dig a bit deeper in it.