Autoloading in PHP

by

Autoloading is a feature of PHP, that you can't live without in today's world. A file is automatically loaded, when a class name with namespace is supplied.

In the background a configuration is used, often via composer, that finds a file for a class name.

That makes sure, that manual requires and includes are unnecessary and the code is easier readable. When you use autoloading please use a standard, psr-4 would be the default, so that your packages can easily be integrated.

Configuration

Assuming that you are using composer, the complete configuration is done in the composer.json. You have the keys autoload and autoload-dev here to define your configuration.

Define a new object for the property psr-4 in both autoload and autoload-dev. This object will contain the mapping between namespace and folder.

Usually a property My\Namespace\ is defined within autoload.psr-4 with the value src. Autoload-dev.psr-4 works in a similar fashin. Here the value for My\Namespace\ is usually test.

{
  "autoload": {
    "psr-4": {
      "My\\Namespace\\": "src"
    }
  },
  "autoload-dev": {
    "psr-4": {
      "My\\Namespace\\": "test"
    }
  }
}

With that all subnamespaces are available as well, if you name the files matching the classname and the foldernames matching the subnamespace. In our example the interface My\Namespace\Example\Contract would be expected in src/Example/Contract.php.

Updating

To make the new namespace definitions available, you have to use composer install, composer update or composer dump-autoload. This updates the classes that handle the class to file matching.

Optimizations

For production use it is adviseable to set the flag optimize_autoloader to true. This reduces the time for searching and the necessary file system access a lot, but can't handle changes in the file structures automatically. When deploying code, the autoloader has to be updated to solve that issue.