Loading the Autoloader

Installing composer and autoloading classes

Open the demo website’s shell using WP Local and navigate to the plugin’s directory.

You can use the following shortcut command in the CLI.

$cd wp-content/plugins/domain-core

To install composer, enter this command.

$composer install

After running this command, the lib directory and composer.json will be generated. We now have changes to our file structure. Let us discuss the changes to the structure.

composerlock.json

This file locks the dependencies of your project to a known state. That is, it gets the version numbers of the dependencies in use. Suppose someone wishes to install these dependencies again in future. The composer will download dependencies based on the versions specified in this file. The later version of the dependencies will not be downloaded/used.

lib Directory

We have the composer directory in this folder with our autoloaded class map. We also have the autoloader (autoload.php).

We can now be confident that every file in the core folder is autoloaded for us and is ready for initialisation.

Benefits So far

This kind of setup/structure has some benefits.

  • We do not need to run the “require” statement to have these classes/services initialised. The autoloader caters for this.
  • Besides, we can import third-party libraries into our project using composer. This can extend the functionality of our plugin. The use of third-party libraries is like the use of node modules in node.js.

New file structure after installing composer and autoloading classes

PSR-4 Plugin File Structure after installing composer
PSR-4 Plugin File Structure after installing composer