Dirthara Container
Dirthara Container is a dependency injection container that implements the
PSR-11 ContainerInterface. Any library that accepts a PSR-11 container can use
it, and code written against the interface can swap it for another implementation. Registering entries has an
interface of its own, ContainerConfigurator; see depending on the interfaces.
The container resolves an entry from the first of these sources that has it:
| Source | Registered with | Resolves to |
|---|---|---|
| Instance | instance() or scopedInstance() | The value that was registered, every time, or until the scope is reset. |
| Binding | bind(), singleton(), or scoped() | A factory's result, another entry, or a class, built on each request, once, or once per scope. |
| Delegate | delegate() | What another PSR-11 container returns for the identifier. |
| Attribute | #[BoundTo], #[Singleton], or #[Scoped] on the type | A class, as a binding with the same attributes would. |
| Autowiring | Nothing | Any instantiable class, built with its constructor dependencies resolved from the container. |
use Dirthara\Container\Container;
$container = new Container();
$container->bind(LoggerInterface::class, FileLogger::class);
$mailer = $container->get(Mailer::class);
Mailer is not registered, so the container autowires it: it reads the constructor, resolves a LoggerInterface
argument to a new FileLogger, and builds the Mailer.
Attributes let a type declare its own default implementation and lifetime, such as
#[BoundTo(SystemClock::class)] on a Clock interface or #[Singleton] on a class, and a parameter declare which
entry it receives with #[Inject('mail.transport')].
Contextual bindings change what one class receives without changing it for the rest:
$container->when(Mailer::class)->needs(LoggerInterface::class)->give(MailLogger::class).
$container->make(Report::class, ['title' => 'Sales']) builds a new instance with some constructor parameters given,
and $container->call([$controller, 'show']) calls a method with its parameters filled in; see
making and calling.
Start with installation and the getting started guide, then read how autowiring fills in constructor parameters and how the container reports errors.