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.
Start by installing via Composer: composer require laminas/laminas-servicemanager. Then create a basic configuration file (config/services.php) returning an associative array with services, aliases, and factories keys. Define your first service as an invokable or factory, e.g., 'logger' => \App\Logger\StdoutLogger::class, and instantiate the container with new ServiceManager($config). Retrieve services via $container->get(LoggerInterface::class). This enables immediate inversion of control—ideal for bootstrapping middleware, repository classes, or domain services in frameworks like Expressive or custom apps.
class LoggerFactory implements FactoryInterface) for complex dependencies, especially when constructor injection requires non-type-hinted parameters or external configuration.AbstractPluginManager to expose controlled sets of同类 services (e.g., CachePluginManager for Redis/Memcached implementations), enforcing type safety and preventing arbitrary classes from being instantiated.DelegatorFactoryInterface implementations to inject cross-cutting concerns like profiling, logging, or retry logic without modifying the original class.InitializerInterface to auto-inject common dependencies (e.g., injecting ContainerInterface into all classes implementing ServiceConsumerInterface)—great for traits or BC layers.config/config.local.php) to swap dbal implementations in tests (InMemoryDatabase::class) vs production.ServiceManager::setThrowExceptionInCreation(true) or use ContainerInterface::has() to guard before get().automaticInjection, ensure constructor types are strictly typed and hintable—scalar参数 (e.g., string $dsn) won’t resolve unless config['parameters'] is provided.SomeServiceFactory isn’t used, check for a conflicting AbstractFactory or misconfigured alias.ServiceManager::compile()) or use ProxyManager integration for lazy-loading heavy services—avoid runtime compilation in CLI scripts or CLI-to-web switches.ContainerInterface type-hint and getContainer()->set(Service::class, $mock) over mocking ServiceManager directly—simpler, safer, and more aligned with DI best practices.How can I help you explore Laravel packages today?