Autoload

Let’s start with the Autoloader.

We will create two classes:

  • Autoload.php
  • vendor/Psr/PsrAutoloader.php


The first class registered the namespaces, so that the second class can find and load them.

In the PHP world, namespaces are designed to solve two problems that authors of libraries and applications encounter when creating re-usable code elements such as classes or functions:

  1. Name collisions between code you create, and internal PHP classes/functions/constants or third-party classes/functions/constants.
  2. Ability to alias (or shorten) Extra_Long_Names designed to alleviate the first problem, improving readability of source code.

PHP Namespaces provide a way in which to group related classes, interfaces, functions and constants.

Reference: php.net

1. PROJECT_ROOT/Autoload.php
As described we want to create two classes for our autoloading, so we need to import the second class in the first one:

Let’s declare the class itself and some variables:

Without a function, it is pretty empty here. Our autoloader should be a singleton, because we only want to have one instance.

Now we need the constructor to create the instance we want to have in the code above.

But all code needs some documentation. The final code looks like this:

2. PROJECT_ROOT/vendor/Psr/PsrAutoloader.php

Finally implement the autoloader into your project, but don’t forget to register your namespaces.
Folder structure:
PROJECT_ROOT/vendor/Psr/PsrAutoload.php
PROJECT_ROOT/Autoload.php
PROJECT_ROOT/test.php
PROJECT_ROOT/test.php

Leave a Reply