1
1
.. index ::
2
- single: DependencyInjection; Service Locators
2
+ single: DependencyInjection; Service Subscribers
3
3
4
- Service Locators
5
- ================
4
+ Service Subscribers & Locators
5
+ ==============================
6
+
7
+ .. versionadded :: 3.3
8
+ Service subscribers and locators were introduced in Symfony 3.3.
6
9
7
10
Sometimes, a service needs access to several other services without being sure
8
11
that all of them will actually be used. In those cases, you may want the
@@ -77,15 +80,178 @@ However, injecting the entire container is discouraged because it gives too
77
80
broad access to existing services and it hides the actual dependencies of the
78
81
services.
79
82
80
- **Service Locators ** are intended to solve this problem by giving access to a
81
- set of predefined services while instantiating them only when actually needed.
83
+ **Service Subscribers ** are intended to solve this problem by giving access to a
84
+ set of predefined services while instantiating them only when actually needed
85
+ through a **Service Locator **, a separate lazy-loaded container.
86
+
87
+ Defining a Service Subscriber
88
+ -----------------------------
89
+
90
+ First, turn ``CommandBus `` into an implementation of :class: `Symfony\\ Component\\ DependencyInjection\\ ServiceSubscriberInterface `.
91
+ Use its ``getSubscribedServices() `` method to include as many services as needed
92
+ in the service subscriber and change the type hint of the container to
93
+ a PSR-11 ``ContainerInterface ``::
94
+
95
+ // src/AppBundle/CommandBus.php
96
+ namespace AppBundle;
97
+
98
+ use AppBundle\CommandHandler\BarHandler;
99
+ use AppBundle\CommandHandler\FooHandler;
100
+ use Psr\Container\ContainerInterface;
101
+ use Symfony\Component\DependencyInjection\ServiceSubscriberInterface;
102
+
103
+ class CommandBus implements ServiceSubscriberInterface
104
+ {
105
+ private $locator;
106
+
107
+ public function __construct(ContainerInterface $locator)
108
+ {
109
+ $this->locator = $locator;
110
+ }
111
+
112
+ public static function getSubscribedServices()
113
+ {
114
+ return [
115
+ 'AppBundle\FooCommand' => FooHandler::class,
116
+ 'AppBundle\BarCommand' => BarHandler::class,
117
+ ];
118
+ }
119
+
120
+ public function handle(Command $command)
121
+ {
122
+ $commandClass = get_class($command);
123
+
124
+ if ($this->locator->has($commandClass)) {
125
+ $handler = $this->locator->get($commandClass);
126
+
127
+ return $handler->handle($command);
128
+ }
129
+ }
130
+ }
131
+
132
+ .. tip ::
133
+
134
+ If the container does *not * contain the subscribed services, double-check
135
+ that you have :ref: `autoconfigure <services-autoconfigure >` enabled. You
136
+ can also manually add the ``container.service_subscriber `` tag.
137
+
138
+ The injected service is an instance of :class: `Symfony\\ Component\\ DependencyInjection\\ ServiceLocator `
139
+ which implements the PSR-11 ``ContainerInterface ``, but it is also a callable::
140
+
141
+ // ...
142
+ $locateHandler = $this->locator;
143
+ $handler = $locateHandler($commandClass);
144
+
145
+ return $handler->handle($command);
146
+
147
+ Including Services
148
+ ------------------
149
+
150
+ In order to add a new dependency to the service subscriber, use the
151
+ ``getSubscribedServices() `` method to add service types to include in the
152
+ service locator::
153
+
154
+ use Psr\Log\LoggerInterface;
155
+
156
+ public static function getSubscribedServices()
157
+ {
158
+ return [
159
+ // ...
160
+ LoggerInterface::class,
161
+ ];
162
+ }
163
+
164
+ Service types can also be keyed by a service name for internal use::
165
+
166
+ use Psr\Log\LoggerInterface;
167
+
168
+ public static function getSubscribedServices()
169
+ {
170
+ return [
171
+ // ...
172
+ 'logger' => LoggerInterface::class,
173
+ ];
174
+ }
175
+
176
+ Optional Services
177
+ ~~~~~~~~~~~~~~~~~
178
+
179
+ For optional dependencies, prepend the service type with a ``? `` to prevent
180
+ errors if there's no matching service found in the service container::
181
+
182
+ use Psr\Log\LoggerInterface;
183
+
184
+ public static function getSubscribedServices()
185
+ {
186
+ return [
187
+ // ...
188
+ '?'.LoggerInterface::class,
189
+ ];
190
+ }
191
+
192
+ .. note ::
193
+
194
+ Make sure an optional service exists by calling ``has() `` on the service
195
+ locator before calling the service itself.
196
+
197
+ Aliased Services
198
+ ~~~~~~~~~~~~~~~~
199
+
200
+ By default, autowiring is used to match a service type to a service from the
201
+ service container. If you don't use autowiring or need to add a non-traditional
202
+ service as a dependency, use the ``container.service_subscriber `` tag to map a
203
+ service type to a service.
204
+
205
+ .. configuration-block ::
206
+
207
+ .. code-block :: yaml
208
+
209
+ // app/config/services.yml
210
+ services :
211
+ AppBundle\CommandBus :
212
+ tags :
213
+ - { name: 'container.service_subscriber', key: 'logger', id: 'monolog.logger.event' }
214
+
215
+ .. code-block :: xml
216
+
217
+ <!-- app/config/services.xml -->
218
+ <?xml version =" 1.0" encoding =" UTF-8" ?>
219
+ <container xmlns =" http://symfony.com/schema/dic/services"
220
+ xmlns : xsi =" http://www.w3.org/2001/XMLSchema-instance"
221
+ xsi : schemaLocation =" http://symfony.com/schema/dic/services http://symfony.com/schema/dic/services/services-1.0.xsd" >
222
+
223
+ <services >
224
+
225
+ <service id =" AppBundle\CommandBus" >
226
+ <tag name =" container.service_subscriber" key =" logger" id =" monolog.logger.event" />
227
+ </service >
228
+
229
+ </services >
230
+ </container >
231
+
232
+ .. code-block :: php
233
+
234
+ // app/config/services.php
235
+ use AppBundle\CommandBus;
236
+
237
+ // ...
238
+
239
+ $container
240
+ ->register(CommandBus::class)
241
+ ->addTag('container.service_subscriber', array('key' => 'logger', 'id' => 'monolog.logger.event'))
242
+ ;
243
+
244
+ .. tip ::
245
+
246
+ The ``key `` attribute can be omitted if the service name internally is the
247
+ same as in the service container.
82
248
83
249
Defining a Service Locator
84
250
--------------------------
85
251
86
- First, define a new service for the service locator. Use its `` arguments ``
87
- option to include as many services as needed to it and add the
88
- `` container.service_locator `` tag to turn it into a service locator:
252
+ To manually define a service locator, create a new service definition and add
253
+ the `` container.service_locator `` tag to it. Use its `` arguments `` option to
254
+ include as many services as needed in it.
89
255
90
256
.. configuration-block ::
91
257
@@ -128,7 +294,7 @@ option to include as many services as needed to it and add the
128
294
use Symfony\Component\DependencyInjection\ServiceLocator;
129
295
use Symfony\Component\DependencyInjection\Reference;
130
296
131
- //...
297
+ // ...
132
298
133
299
$container
134
300
->register('app.command_handler_locator', ServiceLocator::class)
@@ -144,7 +310,7 @@ option to include as many services as needed to it and add the
144
310
The services defined in the service locator argument must include keys,
145
311
which later become their unique identifiers inside the locator.
146
312
147
- Now you can use the service locator injecting it in any other service:
313
+ Now you can use the service locator by injecting it in any other service:
148
314
149
315
.. configuration-block ::
150
316
@@ -188,45 +354,4 @@ Now you can use the service locator injecting it in any other service:
188
354
If the service locator is not intended to be used by multiple services, it's
189
355
better to create and inject it as an anonymous service.
190
356
191
- Usage
192
- -----
193
-
194
- Back to the previous ``CommandBus `` example, it looks like this when using the
195
- service locator::
196
-
197
- // ...
198
- use Psr\Container\ContainerInterface;
199
-
200
- class CommandBus
201
- {
202
- /**
203
- * @var ContainerInterface
204
- */
205
- private $handlerLocator;
206
-
207
- // ...
208
-
209
- public function handle(Command $command)
210
- {
211
- $commandClass = get_class($command);
212
-
213
- if (!$this->handlerLocator->has($commandClass)) {
214
- return;
215
- }
216
-
217
- $handler = $this->handlerLocator->get($commandClass);
218
-
219
- return $handler->handle($command);
220
- }
221
- }
222
-
223
- The injected service is an instance of :class: `Symfony\\ Component\\ DependencyInjection\\ ServiceLocator `
224
- which implements the PSR-11 ``ContainerInterface ``, but it is also a callable::
225
-
226
- // ...
227
- $locateHandler = $this->handlerLocator;
228
- $handler = $locateHandler($commandClass);
229
-
230
- return $handler->handle($command);
231
-
232
357
.. _`Command pattern` : https://en.wikipedia.org/wiki/Command_pattern
0 commit comments