The DI component provides an auto wiring strategy which implements constructor injection.
Before starting, make sure laminas-di is installed and configured.
2. Configuring the injector
You can now create and configure an injector instance. The injector accepts an
Laminas\Di\ConfigInterface. This can be provided by passing
Laminas\Di\Config, which accepts a PHP array to its constructor:
use Laminas\Di\Injector; use Laminas\Di\Config; $injector = new Injector(new Config([ 'preferences' => [ MyInterface::class => MyImplementation::class, ], ]));
This config implementation accepts a veriety of options. Refer to the Configuration chapter for full details.
3. Creating instances
Finally, you can create new instances of a specific class or alias by using the
$instance = $injector->create(MyClass::class);
The only precondition is that the class you provide to
create() must exist (or
be autoloadable). If this is not the case, the injector will fail with an
create() method will always create a new instance of the given class. If
you need a shared instance, you can associate an IoC container implementing
PSR-11 with the injector:
$injector = new Injector($config, $container); $sharedInstance = $injector->getContainer()->get(MyClass::class);
By default, the injector creates and uses an instance of
Laminas\Di\DefaultContainer if no container is provided to it. This
implementation is quite limited, however, and we recommend you use a more
featureful container with the injector, such as
Refer to the Usage with PSR-11 containers
and Usage with laminas-servicemanager
chapters for details.