The Fulcrum DI Container Module provides a lean Dependency Injection Container.
The primary purpose of a a DI Container is to manage objects. By passing in a closure that wraps up the creation of objects, using the container, you can:
- Create a new object without having to use
new
in your code or having to specify it's dependencies. - Get an object out of the container without having to use Singletons, statics, or globals. WooHoo!
The container also stores datasets. Think of it like a big array where you add values into it by a unique key. Powerful.
Seriously, a DI Container makes you job so much easier. Let it handle:
- Object creation along with all of the object's dependencies.
- Managing objects.
- Storing datasets in memory.
- Retrieving the object or dataset you need.
It extends Pimple by providing the following functionality:
has()
method to check if a unique key exists in the container.get()
method to fetch something out of the container by it's unique key.registerConcrete()
method - providing the ability to register a closure.
The best way to use this component is through Composer:
composer require wpfulcrum/container
Using the registerConcrete()
method, you can register a closure that then handles creating the object and its dependencies.
For example, let's say you have an object that has several dependencies. For example, you are adding a Portfolio custom post type to your project using Fulcrum.
This might be the configuration for that CPT:
$concreteConfig = [
'autoload' => true,
'concrete' => function ($container) {
$configObj = new Config(YOURPLUGIN_PATH . '/config/post-type/portfolio.php');
return new PostType(
$configObj,
$configObj->postTypeName,
new PostTypeSupports($configObj)
);
},
];
Let's stop and notice a few points:
- There are multiple dependencies including:
- a
Config
object - a post type name
- PostTypeSupports` object.
- a
- Everything you need to create the CPT object is wrapped up in that closure.
- The
autoload
parameter is set totrue
. Therefore, the object is created immediately upon registering it into the container.
Using the above configuration, it can be registered into the container like this:
$container = new DIContainer();
$portfolioCpt = $container->registerConcrete($concreteConfig, 'portfolio_cpt');
All feedback, bug reports, and pull requests are welcome.