strident / container
Dependency injection container component designed for ease of use and speed. Built for Trident. Heavily inspired by Pimple.
Requires
- php: >=5.4
Requires (Dev)
- codeclimate/php-test-reporter: ~0.1
- phpunit/phpunit: ~4.5
This package is not auto-updated.
Last update: 2024-10-26 17:13:46 UTC
README
Dependency injection container component designed for ease of use and speed. Built for Trident. Heavily inspired by Pimple.
##Installation
Installation is available via Composer. Add the package to your composer.json:
$ composer require strident/container ~2.0
##Usage
The container is incredibly simple to instantiate. Simply do the following:
use Strident\Container\Container; $container = new Container();
###Defining Services
From there, you can define services like so:
// 'Service' class defined somewhere, and 'dependency_name' service defined $container->set("service_name", function($container) { return new Service($container->get("dependency_name")); });
The services are lazy loaded (i.e. nothing is instantiated until it is called).
###Extending a Service After Definition
You may also extend services once they have been defined (for example, if you wish to augment a service, alter settings, swap out dependencies etc). But note that once a service is used, it becomes locked and cannot be modified further.
$container->extend("service_name", function($service, $container) { $service->doSomething(); $service->addSomething($container->get("dependency_name")); return $service; });
###Defining Factory Services
If you wish to return a new instance of your service every time instead of the same instance, you may define a factory service like so:
$container->set("service_name", $container->factory(function($container) { return new Service($container->get("dependency_name")); }));
###Parameters
Parameters are get / set by accessing the container like an array:
// Set $container["foo"] = "A parameter can be anything"; // Get $foo = $container["foo"];