@@ -6,11 +6,26 @@ How to Define Controllers as Services
6
6
7
7
In Symfony, a controller does *not * need to be registered as a service. But if you're
8
8
using the :ref: `default services.yaml configuration <service-container-services-load-example >`,
9
- your controllers *are * already registered as services. This means you can use dependency
9
+ and that your controllers extend the `AbstractController `_ class,
10
+ they *are * already registered as services. This means you can use dependency
10
11
injection like any other normal service.
11
12
12
- Referencing your Service from Routing
13
- -------------------------------------
13
+ If your controllers don't extend the `AbstractController `_ class, you must explicitly mark your controller
14
+ services as ``public ``.
15
+ Alternatively, you can also tag controller services with the ``controller.service_arguments ``.
16
+ This will make the tagged services ``public `` and will allow you to inject services in method parameters:
17
+
18
+ .. configuration-block ::
19
+
20
+ .. code-block :: yaml
21
+
22
+ # config/services.yaml
23
+
24
+ # controllers are imported separately to make sure services can be injected
25
+ # as action arguments even if you don't extend any base controller class
26
+ App\Controller\ :
27
+ resource : ' ../src/Controller/'
28
+ tags : ['controller.service_arguments']
14
29
15
30
Registering your controller as a service is the first step, but you also need to
16
31
update your routing config to reference the service properly, so that Symfony
@@ -222,5 +237,4 @@ If you want to know what type-hints to use for each service, see the
222
237
223
238
.. _`Controller class source code` : https://github.com/symfony/symfony/blob/master/src/Symfony/Bundle/FrameworkBundle/Controller/AbstractController.php
224
239
.. _`AbstractController` : https://github.com/symfony/symfony/blob/master/src/Symfony/Bundle/FrameworkBundle/Controller/AbstractController.php
225
- .. _`AbstractController` : https://github.com/symfony/symfony/blob/master/src/Symfony/Bundle/FrameworkBundle/Controller/AbstractController.php
226
240
.. _`ADR pattern` : https://en.wikipedia.org/wiki/Action%E2%80%93domain%E2%80%93responder
0 commit comments