Dependency Management (Composer)

In short, Composer is a dependency manager for PHP. If you’ve worked with npm for NodeJS, Maven for Java or NuGet for C#, the principle should be familiar. Basically, Composer lets us define a composer.json file in our project root which contains a list of dependencies for the project. Using commands such as composer install we can then automagically add those dependencies to our project.

By default, Composer pulls the dependencies from Packagist which is also where you can find the open-source modules of our framework. You can also define your own package sources, such as GitHub or a private packages repository. You can read more about how that works and how a composer.json file looks like by reading this article of the official documentation.

Composer also has another ground-breaking advantage — it generates an autoloader for your project. You probably know this already, but in PHP you need to call include or require before using the contents of a file. It can become tedious (and it’s definitely error-prone) to do that for all the files in your project, especially as your plugin grows. Moreover, if you want to only load classes conditionally, that becomes a nightmare!

An autoloader lets you define a function that loads PHP files containing classes only when the class is used. That basically guarantees the conditional loading. Moreover, the Composer autoloader also supports loading simple files containing plain PHP functions (albeit non-conditionally).

By using the PSR-4 autoloading standard for our project structure and Composer for loading dependencies and generating an autoloader, it’s virtually impossible to cause a “function/class does not exist” runtime error in production!

Here is an example of a composer.json file that is actually used by the first module of the framework, the Bootstrapper. The relevant entries are “autoload” and “autoload-dev”. The autoloader is then the only file that we need to require as one of the first things the module does in bootstrap.php.

Last updated