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