Autowiring
What is autowiring?
Autowiring is an exotic word that represents something very simple: the container's ability to create and inject dependencies automatically.
The quote is taken from the PHP-DI library that we use.
In a nutshell, we use a dependency injection (DI) container to load all your service classes. Alongside the DI container, we also use the PSR-4 coding standard for autoloading. That allows us to predict what your file/folder structure will look like in correlation to the namespace. With that in mind, you don't have to worry about requiring your classes. Our autoloading takes care of everything. All you need to do is follow a few coding standards so that you can automatically inject other classes as dependencies.
Autowiring runs inside the Main
service class as an extended class of our AbstractMain
class. You can install the main class using this command:
wp boilerplate create_main
How it works
Here is a quick overview of how this works:
- You create a new class manually or using the WP-CLI command.
- PSR-4 should detect your new class if you followed the PSR-4 naming standard.
- The new class is added to the
classmap
array inside thevendor
folder. - Autowiring class reads the new class, checks if your class has any class dependencies, and injects them.
- And it just works.
To put it shortly: just add a new class (that is PSR-4 compliant) with or without some class dependencies and everything will be automatically resolved/injected.
What if I have to mock or manually call a class?
Before we start with the automatization and autowiring, let's see how service classes are called manually.
We can think of these scenarios where you want to load a class manually:
- You have to write tests and manually provide mocked classes.
- Your classes have a custom structure and autowiring can't resolve it.
- You want to provide a primitive parameter (
string
,int
, etc.) inside a constructor method.
In those cases, you can manually provide your DI container with the implementation using the getServiceClasses
method inside the src>Main>Main.php
class.
Provide the method and add your custom implementation like this:
src>Main>Main.php
/**
* Get the list of services to register.
*
* A list of classes which contain hooks.
*
* @return array<class-string, string|string[]> Array of fully qualified service class names.
*/
protected function getServiceClasses(): array
{
return [
// If you are using a class as a DI.
ProjectNamespace\Rest\Routes\DocumentsRoute::class => [
ProjectNamespace\Query\Documents\QueryDocuments::class
],
// If you just want to include a simple class with no DI.
ProjectNamespace\CoolFolder\CoolClass::class,
];
}