laminas/laminas-servicemanager
Powerful dependency injection and service container for PHP. Manage factories, abstract factories, delegators, aliases, and shared services, with PSR-11 interoperability and robust configuration for complex applications.
Writing a factory class for each and every service that has dependencies can be tedious, particularly in early development as you are still sorting out dependencies.
laminas-servicemanager ships with Laminas\ServiceManager\AbstractFactory\ReflectionBasedAbstractFactory,
which provides a reflection-based approach to instantiation, resolving
constructor dependencies to the relevant services. The factory may be used as
either an abstract factory, or mapped to specific service names as a factory:
use Laminas\ServiceManager\AbstractFactory\ReflectionBasedAbstractFactory;
return [
/* ... */
'service_manager' => [
'abstract_factories' => [
ReflectionBasedAbstractFactory::class,
],
'factories' => [
'MyModule\Model\FooModel' => ReflectionBasedAbstractFactory::class,
],
],
/* ... */
];
Mapping services to the factory is more explicit and even more performant than in v3.0 due to the ahead of time factory generation.
The factory operates with the following constraints/features:
$config typehinted as an array will receive the
application "config" service (i.e., the merged configuration).$config, will
be injected with an empty array.$options passed to the factory are ignored in all cases, as we cannot
make assumptions about which argument(s) they might replace.
Once your dependencies have stabilized, we recommend providing a dedicated factory, as reflection introduces a performance overhead.
There are two ways to provide dedicated factories for services consuming ReflectionBasedAbstractFactory:
You may also use the Config Abstract Factory, which gives slightly more flexibility in terms of mapping dependencies:
ConfigAbstractFactory.'config' service), choose the ConfigAbstractFactory.ConfigAbstractFactory or create a custom factory.This feature was inspired by a blog post by Alexandre Lemaire.
How can I help you explore Laravel packages today?