Create autoloader with Composer

I started a small WordPress plugin and tried to orientate myself a little bit towards the Speaking Plugin of Alain Schlesser for the structure and basic principles. So I came about the topic autoloading. Alain wrote a custom autoloader for the plugin but mentioned the possibility via composer in his talk at the WordCamp Nijmegen. This post describes how to create an autoloader with Composer.

Of course, you need Composer installed. Now we run composer init in our project folder and enter a few information – as a result, we get a composer.json.

After that, we need to add a small additional piece into the composer.json, so we can create the autoloader in the next step. This section looks like that in my plugin (helpful for the whole autoloading thing with Composer was an article from phpenthusiast.com):

"autoload": { "psr-4": { "FlorianBrinkmann\\CustomizeThemesInstaller\\": "src/" } }
Code language: JavaScript (javascript)

We map the namespace FlorianBrinkmann\CustomizeThemesInstaller to the src directory, so that, for example, the class FlorianBrinkmann\CustomizeThemesInstaller\Plugin is searched in the file src/Plugin.php (PSR-4 requires the usage of namespaces).

Now we run composer dump-autoload to create the autoloader and include it into our bootstrap file via require_once __DIR__ . '/vendor/autoload.php';.

For the production, it is recommended to optimize the autoloader, so it does not need to scan the file system before resolving a class name. There are different ways to optimize it, as described in the Composer docs.

Leave a Reply

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