📡 You're offline — showing cached content
New version available!
Quick Access
Tutorials Zend Framework / Laminas ServiceManager (DI Container)

ServiceManager (DI Container)

6 min read Quiz at the end
Register services, aliases, and factories in the ServiceManager (PSR-11 IoC container).

ServiceManager — Dependency Injection

// In module.config.php
use LaminasServiceManagerFactoryInvokableFactory;

return [
    "service_manager" => [
        "factories" => [
            // Service factory
            ModelPostTable::class => function($container) {
                $adapter = $container->get(AdapterInterface::class);
                return new ModelPostTable($adapter);
            },
            // Using InvokableFactory for no-dependency classes
            ServiceEmailService::class => InvokableFactory::class,
        ],
        "aliases" => [
            "PostTable" => ModelPostTable::class,
        ],
    ],
    "controllers" => [
        "factories" => [
            ControllerPostController::class => function($container) {
                $postTable = $container->get(ModelPostTable::class);
                return new ControllerPostController($postTable);
            },
        ],
    ],
];

// Fetch from container
$postTable = $container->get(ModelPostTable::class);
$email     = $container->get("PostTable"); // using alias
Topic Quiz · 2 questions

Test your understanding before moving on

1. What is the ServiceManager used for?
💡 The ServiceManager is the IoC container that creates services and resolves dependencies.
2. What does InvokableFactory create?
💡 InvokableFactory uses new ClassName() for classes with no dependencies.