How to Define Controllers as Services

How to Define Controllers as Services

In Symfony, a controller does not need to be registered as a service. But if you’re using the default services.yaml configuration, your controllers are already registered as services. This means you can use dependency injection like any other normal service.

Referencing your Service from Routing

Registering your controller as a service is the first step, but you also need to update your routing config to reference the service properly, so that Symfony knows to use it.

Use the service_id::method_name syntax to refer to the controller method. If the service id is the fully-qualified class name (FQCN) of your controller, as Symfony recommends, then the syntax is the same as if the controller was not a service like: App\Controller\HelloController::index:

  • Annotations

    1. // src/Controller/HelloController.php
    2. namespace App\Controller;
    3. use Symfony\Component\Routing\Annotation\Route;
    4. class HelloController
    5. {
    6. /**
    7. * @Route("/hello", name="hello", methods={"GET"})
    8. */
    9. public function index()
    10. {
    11. // ...
    12. }
    13. }
  • YAML

    1. # config/routes.yaml
    2. hello:
    3. path: /hello
    4. controller: App\Controller\HelloController::index
    5. methods: GET
  • XML

    1. <!-- config/routes.xml -->
    2. <?xml version="1.0" encoding="UTF-8" ?>
    3. <routes xmlns="http://symfony.com/schema/routing"
    4. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    5. xsi:schemaLocation="http://symfony.com/schema/routing
    6. https://symfony.com/schema/routing/routing-1.0.xsd">
    7. <route id="hello" path="/hello" controller="App\Controller\HelloController::index" methods="GET"/>
    8. </routes>
  • PHP

    1. // config/routes.php
    2. use App\Controller\HelloController;
    3. use Symfony\Component\Routing\Loader\Configurator\RoutingConfigurator;
    4. return function (RoutingConfigurator $routes) {
    5. $routes->add('hello', '/hello')
    6. ->controller([HelloController::class, 'index'])
    7. ->methods(['GET'])
    8. ;
    9. };

Invokable Controllers

Controllers can also define a single action using the __invoke() method, which is a common practice when following the ADR pattern (Action-Domain-Responder):

  • Annotations

    1. // src/Controller/Hello.php
    2. namespace App\Controller;
    3. use Symfony\Component\HttpFoundation\Response;
    4. use Symfony\Component\Routing\Annotation\Route;
    5. /**
    6. * @Route("/hello/{name}", name="hello")
    7. */
    8. class Hello
    9. {
    10. public function __invoke($name = 'World')
    11. {
    12. return new Response(sprintf('Hello %s!', $name));
    13. }
    14. }
  • YAML

    1. # config/routes.yaml
    2. hello:
    3. path: /hello/{name}
    4. controller: app.hello_controller
  • XML

    1. <!-- config/routes.xml -->
    2. <?xml version="1.0" encoding="UTF-8" ?>
    3. <routes xmlns="http://symfony.com/schema/routing"
    4. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    5. xsi:schemaLocation="http://symfony.com/schema/routing
    6. https://symfony.com/schema/routing/routing-1.0.xsd">
    7. <route id="hello" path="/hello/{name}">
    8. <default key="_controller">app.hello_controller</default>
    9. </route>
    10. </routes>
  • PHP

    1. // app/config/routing.php
    2. $collection->add('hello', new Route('/hello', [
    3. '_controller' => 'app.hello_controller',
    4. ]));

Alternatives to base Controller Methods

When using a controller defined as a service, you can still extend the AbstractController base controller and use its shortcuts. But, you don’t need to! You can choose to extend nothing, and use dependency injection to access different services.

The base Controller class source code is a great way to see how to accomplish common tasks. For example, $this->render() is usually used to render a Twig template and return a Response. But, you can also do this directly:

In a controller that’s defined as a service, you can instead inject the twig service and use it directly:

  1. // src/Controller/HelloController.php
  2. namespace App\Controller;
  3. use Symfony\Component\HttpFoundation\Response;
  4. use Twig\Environment;
  5. class HelloController
  6. {
  7. private $twig;
  8. public function __construct(Environment $twig)
  9. {
  10. $this->twig = $twig;
  11. }
  12. public function index($name)
  13. {
  14. $content = $this->twig->render(
  15. 'hello/index.html.twig',
  16. ['name' => $name]
  17. );
  18. return new Response($content);
  19. }
  20. }

You can also use a special action-based dependency injection to receive services as arguments to your controller action methods.

Base Controller Methods and Their Service Replacements

The best way to see how to replace base Controller convenience methods is to look at the ControllerTrait that holds its logic.

If you want to know what type-hints to use for each service, see the getSubscribedServices() method in AbstractController.

This work, including the code samples, is licensed under a Creative Commons BY-SA 3.0 license.