The DI Container - 3ev/wordpress-core GitHub Wiki

Wordpress Core makes use of a dependency injection container to manage all of its classes and their dependencies. Doing this means that code is extremely maintainable and testable.

It's worth reading up on the container used (the excellent Pimple) to get a handle on how dependency injection works, if you don't already.

###Accessing the container

The container is a singleton instance of Tev\Application\Application that's available using Tev\Application\Application::getInstance(). Handily, there is a helper function called tev_app() that means that you don't have to write out the long static method every time.

###Resolving entities from the container

To resolve a class from the container, you will usually use the tev_fetch($identifier) method. This method will instantiate a class from the container using its registered identifier. This is a convenient wrapper around Tev\Application\Application::getInstance()->fecth($identifer).

In some instances, you will be using a class that has DI container as one of its member variables (such as shortcode and action providers). In those cases, you can resolve a class using $this->app->fetch($identifier).

###Binding new entities into the container

You can easily bind new entities into the container using tev_app()->bind($identifier, $callback). The $callback function has a single parameter, which is the container itself. Your callback should return an instance of the class that you want to bind into the container.

For example:

<?php

tev_app()->bind('my_custom_class', function ($app) {
    return new MyPluginVendor\MyCustomClass($app->fetch('post_factory));
});

In the example above, we register our own custom class and resolve its dependency on the Tev\Post\Factory class by fetching it from the container.

###List of built-in bindings

The following is a list of the built in bindings that come as part of Wordpress Core. Note that bindings are all snake_case, so please try to stick to that where possible.

Binding key Class instance
author_factory Tev\Author\Factory
field_factory Tev\Field\Factory
plugin_loader Tev\Plugin\Loader
post_factory Tev\Post\Factory
post_repo Tev\Post\Repository\PostRepository
taxonomy_factory Tev\Taxonomy\Factory
taxonomy_repo Tev\Taxonomy\Repository\TaxonomyRepository
term_factory Tev\Term\Factory
term_repo Tev\Term\Repository\TermRepository
template_extras Tev\Util\TemplateExtras