Dependency injection container
- Comparing
- v1 to v2
- Current
- Read the document
Abstract
A I will give the panel a dependency injection container that constructs objects and supplies their dependencies. Classes are resolved
It will
resolve classes automatically from their constructor signaturesconstructors, or through bindings bindings that supply a concrete a
concrete class, an instance or a
a factory. Resolved instances are shared will be
shared by default and can be held weakly, resolution can be deferred through lazy
proxies and a
lazy proxy or a ghost objectsobject, and any callable, method or or
constructor can be invoked with its parameters supplied by the
the container.
Motivation
The panel needs a dependency injection solution. It needs , and it has to be:
- Flexible, without being convoluted,
supportingwith the features expected of modern dependency injection. - Cacheable, built so that
bindingsbindings and resolution configuration can be compiledandand cached fora production environmentproduction. - Easy to use,
requiringneeding no in-depth understanding to get started.
Proposal
Concepts
| Term | Meaning |
|---|---|
| Resolution | Producing an instance of a class, from a binding or automatically from its constructor. |
| Invocation | Calling a callable, method or constructor with its parameters supplied by the container. |
| Abstract | The class or interface requested. |
| Concrete | The class instantiated in place of an abstract. |
| Binding | Registered resolution information for one abstract. |
| Alias | Another class name that resolves through the same binding. |
| Named binding | A child binding of an abstract, selected by a string name. |
| Qualified binding | A child binding of an abstract, selected by a qualifier attribute. |
| Shared | Resolved once, cached, and returned on every later resolution. |
| Liminal | Shared, but held through a weak reference, so it can be garbage collected once nothing else uses it. |
| Lazy proxy | An object that stands in for an instance not yet resolved, and forwards to that instance once it is. |
| Ghost object | An object of the final class left uninitialised, which becomes the instance itself once initialised. |
| Dependency | A parameter the container has to supply. |
| Resolver | An object that resolves a dependency. |
| Resolvable attribute | A parameter attribute that selects a custom resolver for that dependency. |
Components
| Component | Responsibility |
|---|---|
Container |
Resolves classes and invokes callables. Holds the binding and resolver catalogues it is constructed with, and caches shared instances. |
Resolution |
Describes a request to resolve a class. |
Invocation |
Describes a callable, method or constructor to invoke, with any arguments supplied up front. |
Dependency |
Describes one parameter to supply: its name, type, default, and the attributes that affect its resolution. |
BindingRegistry, BindingBuilder |
Mutable. Collect binding definitions. |
Binding |
Immutable. The binding for one abstract, with its named and qualified child bindings. |
BindingCatalogue |
Immutable. The bindings and aliases the container is constructed with, looked up by class, name or qualifier. |
Resolver |
Contract for resolving a dependency. |
Resolvable |
Marker contract for attributes that select a custom resolver. |
ResolverRegistry |
Mutable. Collects the default resolver and the resolver for each resolvable attribute. |
ResolverCatalogue |
Immutable mapping of resolvable attribute to resolver, plus the default resolver, from which the container obtains resolver instances. |
GenericResolver |
The default resolver. |
GhostResolver |
The resolver for the Ghost attribute. |
Named, Qualifier |
Select named and qualified bindings for a parameter. |
Lazy, Liminal, NoResolution |
Attributes the container handles itself. |
Ghost |
A resolvable attribute, handled by GhostResolver. |
ContainerException |
Marker contract implemented by every exception the container throws. |
Bindings
A class with no binding is registered per abstract will be constructed from its constructor. A binding holds the
resolution information for one abstract that needs more than that. Bindings will be collected
through a BindingRegistry. Each , where each call to bind() returns a new
new BindingBuilder; several for the abstract. The registry
and its builders will be mutable, and the Binding each builder describes, and the BindingCatalogue that holds them
for the same container, will be immutable, as
ADR-0003 decides. Several builders for one
abstract will accumulate, which is how named and bindings and
qualified child
bindings bindings sit alongside the main binding.
$registry->bind(Contract::class)->to(Implementation::class);
$registry->bind(Contract::class)->to(new Implementation());
$registry->bind(Contract::class)->using(fn (Dependency $dependency) => new Implementation($dependency));
$registry->bind(Contract::class)->to(Implementation::class)->as(OtherContract::class);
$registry->bind(Contract::class)->named('secondary')->to(SecondaryImplementation::class);
$registry->bind(Contract::class)->qualifier(Archive::class)->to(ArchiveImplementation::class);
$registry->bind(Report::class)->notShared();
$registry->bind(Contract::class)->to(Implementation::class)->liminal();
$registry->bind(Contract::class)->to(Implementation::class)->lazily();
| Builder method | Effect |
|---|---|
to(string|object $concrete) |
A class-string sets the concrete class. An object sets both the concrete class, as its class, and the instance. |
as(string ...$aliases) |
Sets the aliases, replacing any set before. When a concrete class is set, it is also an alias. |
using(Closure $factory) |
Resolves the binding by invoking the factory through the container, so the factory's own parameters are supplied. |
named(string $name) |
Identifies the binding as the child selected by that name. |
qualifier(string $qualifier) |
Identifies the binding as the child selected by that qualifier attribute class. |
liminal() |
Holds the shared instance weakly. |
lazily() |
Resolves the binding as a lazy proxy. |
notShared() |
Resolves a new instance every time. |
A Binding holds the binding can also be reached through class names other than its abstract, the concrete class, the instance, the aliases, the factory, a map of named child
bindings keyed by nameits aliases, a map so that
code depending on any of qualified child bindings keyed by qualifier class, and them is given what the liminalbinding produces. as() sets them, lazy and shared
flagsreplacing any set before. Bindings are shared unless marked otherwiseWhen a
concrete class is set, it is also an alias.
BindingCatalogue::get(string $classAn abstract can have child bindings beside its main one, ?Named $named = nulleach selected by a name or by a
qualifier class, ?Qualifier $qualifier = nullas described under choosing between bindings below. named() looks and
qualifier() make a builder's binding up:one of those children.
- An alias is replaced by the abstract it points to.
- With no binding for the class, the result is
null. - With a name, the result is the named child binding, or
null. - With a qualifier, the result is the child binding for the qualifier's class, or
null. - Otherwise, the result is the binding itself.
Named and qualified bindings
Named bindings suit registries and managers, where resolved instances share a class but their contents depend on the
name. A dependency selects a named binding with the Named attribute, and a resolution with named().
$registry->bind(ServerRepository::class)->to(DatabaseServerRepository::class);
$registry->bind(ServerRepository::class)->to(new InMemoryServerRepository());
$registry->bind(NodeClient::class)->using(fn (HttpClient $http) => new NodeClient($http));
$registry->bind(ServerRepository::class)->to(DatabaseServerRepository::class)->as(ServerLookup::class);
$registry->bind(Connection::class)->named('replica')->to(ReplicaConnection::class);
$registry->bind(Storage::class)->qualifier(Archive::class)->to(ArchiveStorage::class);
$registry->bind(ServerReport::class)->notShared();
$registry->bind(NodeClient::class)->to(HttpNodeClient::class)->liminal();
$registry->bind(NodeClient::class)->to(HttpNodeClient::class)->lazily();
A binding first says how its instance is produced, where constructing the abstract itself would not do. to() given a
class-string sets the concrete class to construct in place of the abstract. to() given an
object sets that object as the instance, and its class as the concrete class. Where construction needs logic of its own,
using() sets a factory, a closure the container invokes when the binding is resolved, supplying the factory's own
parameters as it would a constructor's.
Last, a binding says how long its instance lives and when it is produced. A binding is shared
unless marked otherwise, so its instance is resolved once and returned on every later resolution. notShared() resolves
a new instance every time instead. liminal() keeps the instance shared but holds it weakly, so it can be garbage
collected once nothing else uses it. lazily() defers producing it, resolving the binding as a
lazy proxy.
The container will find a binding in the BindingCatalogue by class, and by name or qualifier where the resolution has
one. An alias is first replaced by the abstract it points to. With no binding for the class, the result is null.
Given a name, the result is the named child binding, or null if there is none. Given a qualifier, it is the child
binding for the qualifier's class, or null. Otherwise it is the binding itself. The lookup is
BindingCatalogue::get(), which takes the class with an optional Named attribute and an optional qualifier.
Choosing between bindings of one type
A named binding suits registries and managers, where resolved instances share a class
but their contents depend on the name. A dependency will select one with the Named
attribute, and a resolution with named().
public function __construct(
#[Named('replica')] private Connection $connection,
) {}
Qualified bindings suit A qualified binding suits cases where more than a name is needed to resolve. A qualifier A
qualifier is an attribute class
class implementing Qualifier, and the qualifier's class is the the
key: it selects the child binding, and any value the
the attribute carries is ignored. The Because the
attribute is unique to one binding outcome, so one qualifier class cannot be reused
reused across different types. A dependency selects dependency
will select a qualified binding by carrying the attribute, and a resolution with
with qualifiedBy().
#[Attribute(Attribute::TARGET_PARAMETER)]
final readonly class Archive implements Qualifier {}
public function __construct(
#[Archive] private Storage $storage,
) {}
Shared The shared instances of a qualified binding are will be cached per qualifier class. Selecting an an
instance by a value, such as a
a region, is the job of a custom resolver. A dependency cannot cannot
be both named and qualified.
ResolutionResolving a class
A resolution is resolution will be requested with Container::resolve(), describing it with given a Resolution that
describes it:
$instance = $container->resolve(Resolution::for(Contract::class));
$instance = $container->resolve(
Resolution::for(Contract::class)
->with(['name' => 'value'])
->named('secondary')
->lazily(),
);
Resolution method |
Effect |
|---|---|
for(string $class) |
Starts a resolution for the class. |
with(array $arguments) |
Supplies constructor arguments by parameter name, merged with any supplied before. |
named(string $name) |
Selects the named binding. |
qualifiedBy(Qualifier $qualifier) |
Selects the qualified binding. |
resolveWith(Resolvable $resolvable) |
Resolves the class through the resolver paired with the resolvable attribute. |
lazily() |
Returns a lazy proxy. |
liminal() |
Holds the shared instance weakly. |
Resolving The container will resolve a class follows in these steps:
- Cached instance. If a shared instance is cached for the resolution, it is returned: by name for a named
resolution, by qualifier class for a qualified one, from the weak cache for a
liminal oneliminal one while the instanceisis still alive, and otherwise by class. - Lazy proxy. If the resolution is lazy, a lazy proxy is returned, and the steps below run when it is first used.
- Binding. The
bindingbinding for the class, name and qualifier is looked up. - Instance. If the binding holds an instance, that instance is the result. If it has a factory, the factory is
invoked through the container and its return value is the result. If it has a
concreteconcrete class, that classisis constructed in place of the abstract. - Automatic construction. Otherwise the
class is constructed bycontainer constructs thecontainerclass itself. A class markedNoResolutioncannotbebe constructed this way, and throws. A class that is not instantiable throws. A class with noconstructorconstructor isinstantiatedinstantiated directly, and a class with one has its constructor invoked through the container, soitsits parametersareare supplied as described underInvocationinvocation below. - Class attributes. A class marked
Lazyis always resolved as a lazy proxy, and a class markedLiminalis always held weakly, regardless of any binding or argument. - Sharing. Unless a binding marks it not shared, the instance is cached: weakly if liminal, by name or by qualifier where the resolution has one, and otherwise by class. The cache key is the binding's abstract, or the requested class where there is no binding.
When a lazy proxy is first used, it resolves will resolve the same resolution with the lazy resolution step skipped, so the proxy's own
initialisation cannot produce another proxy.
A resolution given a resolvable attribute with resolveWith() is resolved through the resolver paired with that
attribute, as a dependency carrying the attribute would be.
Lazy proxies
Lazy resolution uses the lazy objects introduced in PHP 8.4. A lazy proxy ghost object is always a proxy: when a property an object of the concrete class itself,
created uninitialised. When it is first
first accessed, the container resolves the real instanceits constructor will be invoked on that same object through the
container, and the proxy forwards to it from then on. A class with no
properties that could trigger initialisation on it is the final instance in every meaningful way, rather than a proxy in front of one. A
dependency will be resolved straight away.as a ghost with the Ghost attribute:
Ghost objects
A GhostResolver will create the ghost is an object of for the binding's concrete class, created uninitialised. When it class where there is first accessed, its constructor is
invoked on that same object through the containerone, and from then on it is and
for the final instance in every meaningful way,
rather than a proxy in front of oneparameter's class otherwise. A dependency is resolved as a ghost with the Ghost attribute:can only be created for a class or interface type.
public function __construct(
#[Ghost] private ExpensiveService $service,
) {}
Any callable, method or constructor will be invocable with its parameters supplied by the container, given an
GhostResolverInvocationuses the binding's concrete class where there is one, and that describes the parameter's class otherwise. A ghost
can only be created for a class or interface type.call:
Invocation
Any callablewith() supplies arguments by parameter name, method or constructor can be invoked merged with its parameters any supplied by before. A callable is called with its
parameters supplied. A method must be public. A static method is called statically, and a method on an object is
called on that object. A method named on a class-string is called on an instance of the class resolved through the
container, describing the
call with an Invocation:except the constructor, which creates a new instance.
$result = $container->invoke(Invocation::callable($closure));
$result = $container->invoke(Invocation::method($object, 'handle'));
$result = $container->invoke(Invocation::method(Handler::class, 'handle')->with(['input' => $input]));
$object = $container->invoke(Invocation::constructor(Implementation::class));
Invocation method |
Effect |
|---|---|
callable(callable $function) |
Invokes a callable. |
method(object|string $on, string $method) |
Invokes a method on an object or a class. |
constructor(string|object $class) |
Invokes a class's constructor. |
with(array $arguments) |
Supplies arguments by parameter name, merged with any supplied before. |
Invoking follows these rules:
- A callable is called with its parameters supplied.
- A method must be public. A static method is called statically. A method on an object is called on that object. A method on a class-string is called on an instance of the class resolved through the container, except the constructor, which creates a new instance.
Parameters are supplied in declaration order:
- A parameter with an argument supplied under its name receives that argument.
- A variadic parameter ends the list. Variadic parameters are never supplied by the container.
- Any other parameter becomes a
Dependency, carrying its name, type, whether it is optional, its default, and itsNamed, qualifier, resolvable andLiminalattributes. The dependency is resolved by the resolver for its resolvable attribute if it has one, and by the default resolver otherwise.
$repository = $container->resolve(Resolution::for(ServerRepository::class));
$client = $container->resolve(
Resolution::for(NodeClient::class)
->with(['node' => $node])
->named('primary')
->lazily(),
);
A Resolution carries what the class alone does not say about one request. for() names the class. with() carries
constructor arguments by parameter name, merged with any supplied before, for values the caller holds, such as the node
a client is for. named() and qualifiedBy() select a named binding or a
qualified binding, the same choice a dependency makes
with an attribute. A resolution can also ask for what its binding does not impose: lazily() asks for a
lazy proxy, and liminal() asks for the shared instance to be
held weakly. Last, it can hand the request to a custom resolver: resolveWith(), given a
resolvable attribute, resolves the class through the resolver paired with that
attribute, as a dependency carrying the attribute would be.
Deferring construction
A lazy proxy will use the lazy objects introduced in PHP 8.4, and will always stay a proxy: when a property is first accessed, the container resolves the real instance, and the proxy forwards to it from then on. A class with no properties that could trigger initialisation will be resolved straight away instead.
public function __construct(
#[Ghost] private NodeInventory $inventory,
) {}
Invoking with supplied parameters
$result = $container->invoke(Invocation::callable($closure));
$result = $container->invoke(Invocation::method($handler, 'handle'));
$result = $container->invoke(Invocation::method(StartServer::class, 'handle')->with(['server' => $server]));
$client = $container->invoke(Invocation::constructor(HttpNodeClient::class));
Parameters will be supplied in declaration order. A parameter with an argument supplied under its name receives that
argument. A variadic parameter ends the list, because the container never supplies variadic parameters. Any other
parameter becomes a dependency, carrying its name, type, whether it is optional, its
default, its Named attribute, its qualifier, its
resolvable attribute and its Liminal attribute. The dependency is resolved by
the resolver paired with its resolvable attribute if it has one, and by the default resolver
otherwise.
Resolvers
A resolver will resolve one dependency:
interface Resolver
{
public function resolve(Dependency $dependency, Container $container, array $arguments = []): mixed;
}
A resolvable attribute is an attribute implementing the Resolvable marker
contract. A ResolverRegistry sets will set the default resolver and registers register a resolver against each each
resolvable attribute class. The
, and the ResolverCatalogue the container is is
constructed with maps will map each resolvable attribute to its resolver. A resolver is
is itself resolved through the container container
the first time it is needed, and the same instance is reused afterwards. A
A dependency carrying a resolvable attribute attribute
with no registered resolver throws.
Ghost is the resolvable attribute defined here, paired with GhostResolver, is the resolvable attribute defined here. Other components will define their own
their
own resolvable attributes and resolvers in the same way.
GenericResolver, the default, resolves will resolve a dependency by its type:
- A class or interface type is resolved through the container, carrying over the dependency's name
, qualifier, qualifier andliminalliminal flag. - A scalar or other non-class type receives its default value if it has one, or
nullif the type allows it, and throws otherwise. - An intersection type needs a
bindingbinding for at least one of its member types. Eachsuchsuch binding is tried in turn,, using its instance, resolving itsconcreteconcrete class or invokingitsits factory, and the first result that satisfieseveryevery member type is used. Bindings whose concrete class does notexistexist are skipped. If none satisfies the type,thethe default value is used if there is one, and otherwise it throws. - A union type is resolved when exactly one of its members is a class, an interface or an intersection, by
resolving that member. Otherwise the default value is used if there is one,
nullif the type allows it, and it throws if neither. - No type receives the default value if there is one, and throws otherwise.
AttributesAttributes the container handles itself
| Attribute | Targets | Meaning |
|---|---|---|
Named(string $name) |
Parameter | Resolves the dependency from the named binding. |
A Qualifier attribute |
Parameter | Resolves the dependency from the qualified binding. |
Lazy |
Class, parameter | On a class, the class is always resolved as a lazy proxy. On a parameter, that dependency is resolved as a lazy proxy. |
Liminal |
Class, parameter | On a class, the class is always held weakly. On a parameter, that dependency is resolved liminally. |
NoResolution |
Class, parameter | On a class, the class is never constructed automatically: it must be bound with custom resolution logic, or have a factory bound to it. On a parameter, that dependency is never resolved automatically: it has to be supplied as an argument, and resolving it without one throws. |
Ghost |
Parameter | Resolves the dependency as a ghost object, through GhostResolver. |
and Lazy, LiminalNamedNoResolutionqualifier are handled by the container itselfattributes go on parameters only, as special cases of resolution, and do
not go through resolvers. does Ghost , which is the first first
attribute to use the custom resolver mechanism.
CachingShared instances
Shared The container will keep shared instances live for its own lifetime. There will be one instance per
class, one per class and name for named resolutions, and one per class and qualifier class for qualified resolutions. A
liminal resolution will keep a weak reference per class, returning the lifetime of instance only while it
is still alive. Instances that are not shared are never cached. Each resolver instance is
cached by the container:resolver catalogue.
- one instance per class
- one instance per class and name, for named resolutions
- one instance per class and qualifier class, for qualified resolutions
- a weak reference per class, for liminal resolutions, returning the instance only while it is still alive
Instances that are not shared are never cached. Resolver instances are cached by the resolver catalogue.
Lazy, Liminal and NoResolution will be special cases of resolution, handled by the
container itself rather than by resolvers, and each can be placed on a class or on a
parameter. On a class, Lazy always resolves the class as a lazy proxy, and on a parameter
it resolves that dependency as one. On a class, Liminal always holds the class weakly,
and on a parameter it resolves that dependency liminally. On a class, NoResolution means the
class is never constructed automatically: it must be bound with custom resolution logic, or have a factory bound to it.
On a parameter, it means that dependency is never resolved automatically and has to be supplied as an argument, and
resolving it without one throws.
Errors
Every exception implements the container throws will implement ContainerException.
| Exception | Thrown when |
|---|---|
UnresolvableClassException |
A class or dependency marked NoResolution would be resolved automatically. |
NotInstantiableException |
A class to be constructed is abstract, an interface, or otherwise not instantiable. |
DependencyResolutionException |
A dependency cannot be resolved: a type with no default that does not allow null, an unsatisfiable intersection or union type, a ghost requested for a non-class type, or a dependency both named and qualified. |
InvalidResolverException |
A dependency's resolvable attribute has no registered resolver. |
InvalidInvocationException |
A method to be invoked is not public, or an invocation is not callable or does not name a method. |
InvalidClassException, InvalidMethodException |
A class or method cannot be reflected. |
MethodCallException |
Calling a reflected method fails. |
Out of scope
- Assembling catalogues. The container is constructed with a
BindingCatalogueand aResolverCatalogue. Building catalogues. Building the catalogues from registered builders belongs to themodulemodule lifecycle. - Compiling and caching the catalogues for production.
- Module scope. A
BindingRegistryis created for a module scope, andeach bindingeach binding records the scope itwaswas registered under. What a scope means belongs to themodulemodule system.
Alternatives considered
The decisions this This design rests on are three decisions recorded separately, each with the alternatives each one it rejected::
ADR-0002, on how a
dependency selects its instance through named and qualified bindings or a
resolvable attribute paired with a resolver;
ADR-0003, on sealing each mutable
registry into an immutable catalogue; and
ADR-0004, on not implementing PSR-11.
No other alternatives were weighed.
Backwards compatibility
Nothing breaks. This is the first component, and the repository has no source code yet.
Open questions
Changelog
Sources
- Issue #21, Engine - Dependency Injection: the goals in its original text of , and the features added
later the same day, in its edit history.
createdis its date. - Resolution and invocation, the handling of
Lazy,LiminalandNoResolutionby the container rather than by resolvers, and ghosts as the first custom resolver: part of the original plan but not written into the issue, and first written down on . - A qualifier's class being the key with any value ignored,
resolveWith()resolving through the paired resolver,LazyandNoResolutionapplying on parameters, and class attributes applying regardless of binding: first written down on . The code at 728ad64 differs on each of these points, and the design here is what was intended. - The code at 728ad64 also differs from this design:
- a resolution's arguments are never read, so
with()supplies nothing to a constructor - an instance is cached only where a binding exists, because
sharedis read as false without one, so an auto-wired class is constructed again on every resolution Liminalon a parameter is routed to a resolver, asLazyandNoResolutionare, because all three implementResolvableQualifierdeclaresequals(), which the container calls when matching a cached qualified instance and which the qualifier example above does not implement- a binding does not carry the module scope its builder was created for, which the binding catalogue holds separately
BindingNotFoundExceptionandInvalidFunctionExceptionalso implementContainerExceptionand are absent from the errors above, and nothing throws the first
- a resolution's arguments are never read, so
- PR #23, feat(container): Dependency Injection, merged : the implementation, whose merge is
decided. Its commits land onmainindividually, ending at 728ad64. The API, the resolution and invocation steps, the resolver behaviour and the exceptions are described fromsrc/Containerat 728ad64 andtests/Unit/Containerat 728ad64. - Commit 7fad8cd, the initial commit: placeholder files under
src/and no source code.
Source rfc/0001-dependency-injection-container.md · commit 9444a99 · published