On this page
Quick Start
The Service Manager is a modern, fast, and easy-to-use implementation of the Service Locator design pattern. The implementation implements the Container Interop interfaces, providing interoperability with other implementations.
The following is a "quick start" tutorial intended to get you up and running with the most common features of the Service manager.
1. Install Laminas Service Manager
If you haven't already, install Composer. Once you have, you can install the service manager:
$ composer require laminas/laminas-servicemanager
2. Configuring a service manager
You can now create and configure a service manager. The service manager constructor accepts a simple array:
use Laminas\ServiceManager\ServiceManager;
use Laminas\ServiceManager\Factory\InvokableFactory;
use stdClass;
$serviceManager = new ServiceManager([
'factories' => [
stdClass::class => InvokableFactory::class,
],
]);
The service manager accepts a variety of keys; refer to the Configuring service manager section for full details.
3. Retrieving objects
Finally, you can retrieve instances using the get()
method:
$object = $serviceManager->get(stdClass::class);
By default, all objects created through the service manager are shared. This
means that calling the get()
method twice will return the exact same object:
$object1 = $serviceManager->get(stdClass::class);
$object2 = $serviceManager->get(stdClass::class);
var_dump($object1 === $object2); // prints "true"
You can use the build()
method to retrieve discrete instances for a service:
$object1 = $serviceManager->build(stdClass::class);
$object2 = $serviceManager->build(stdClass::class);
var_dump($object1 === $object2); // prints "false"