Download the PHP package sasa-b/container without Composer
On this page you can find all versions of the php package sasa-b/container. It is possible to download/install these versions without Composer. Possible dependencies are resolved automatically.
Download sasa-b/container
More information about sasa-b/container
Files in sasa-b/container
Package container
Short Description Lightweight dependency injection container with laravel like autowiring, interface/abstract class binding and contextual binding. PSR-11 compliant.
License MIT
Informations about the package container
IOC container
Lightweight dependency injection container with laravel like autowiring, interface/abstract class binding and contextual binding. PSR-11 compliant.
To use the library clone the repo or just use composer to install it.
composer require sasa-b/container
Usage examples
Binding/Registering services
A service (bound value) can be a string representation of a class, an anonymous function which returns an object instance, or an object instance itself. If you bind an object instance itself, that service will essentially act as a singleton because the same instance will always be returned.
Singletons
Mapping services to keys
For convenience you can map your services to keys and there are multiple ways of doing it.
-
With mapTo method via method chaining
-
With the key method
- Directly with the bind statement
When you directly bind services to a key, they will only be accessible by that key and those services can't be used for autowiring (injecting by type hinting), unless the service you are binding/registering is a string representaton of a class, in that case the service will automatically be mapped to the given key.
In case of mapTo
and key
bound/registered services are accessible by both the key and their class name, and because of that they can be used for autowiring.
Binding/Registering multiple services
For registering multiple services at once you can use the register
method or it's alias bindMany
.
Registering multiple singletons
Abstract binding
You can bind/register services to interfaces and abstract classes as well. These abstract bindings are convenient when used with autowiring, because you can type hint with abstractions (abstract classes and interfaces) and not concretions (implementations).
Contextual binding
When you want to bind/register multiple different services to a same interface or abstract class you need to provide context otherwise one will override the other. Context is the third parameter to the bind
method, and it can be a string representation of a class or a key mapped to a class, and that class needs to be the one in whose constructor or method the interface/abstract class is used as a typehint.