Alias-Container
This package contains a really minimalist dependency injection container that can be used to create aliases of instances in existing containers. Alias-container is compatible with PSR-11 and is meant to be used in conjunction with other containers. By itself, Alias-container does not store any entry. It can only be used to create aliases of instances stored in other containers.
You can use AliasContainer to add support for alias for any container that does not support this feature.
Installation
Before using AliasContainer in your project, add it to your composer.json
file:
$ ./composer.phar require mouf/alias-container
Defining aliases in the container
Creating an alias container is a matter of creating an AliasContainer
instance.
The AliasContainer
class takes 2 parameters:
- a delegate-lookup container (e.g. the container we will look aliases into)
- the list of aliases, as an associative array of strings
use Mouf\AliasContainer;
use Psr\Container\ContainerInterface;
$aliasContainer = new AliasContainer($rootContainer, [
"myAlias"=>"myInstance",
"myAlias2"=>"myInstance2"
]);
The list of entries is an associative array.
- The key is the identifier of the alias to create
- The value is the identifier of the entry that will be aliased
Fetching entries from the container
Fetching entries from the container is as simple as calling the get
method:
$myInstance = $aliasContainer->get('myAlias');
Requesting an entry, whose alias wasn't specified will throw an exception.
// Throws exception
$myInstance = $aliasContainer->get('myInstance');
Adding aliases to the container
You can add new aliases using the set
method.
$aliasContainer->set('newAlias', 'myInstance');
set
method.Removing aliases from the container
You can add new aliases using the remove
method.
$aliasContainer->remove('myAlias');
Found a typo? Something is wrong in this documentation? Just fork and edit it!