Skip to content
Advertisement

symfony 5.1: how to define a controller as a service

I’m a bit of a noob when it comes to Symfony. I am attempting to create a bundle with a controller that accepts a service as a constructor argument; however, I am receiving this error:

JavaScript

This is the Resources/config/services.xml:

JavaScript

This is the Resources/config/routes.xml:

JavaScript

The main Symfony app’s config/routes.yaml:

JavaScript

The Controller/HeartbeatController.php:

JavaScript

This is the Service/HeartbeatService.php:

JavaScript

Could someone tell me what I’m doing wrong?

Advertisement

Answer

Since Symfony 4, the preferred way of service naming is to use the FQCN as the service id in order to ease autowiring. You have used an old-style string id so even though the class matches, when Symfony looks it up by the expected id, it cannot find it.

It’s an easy fix, either change the definition to

JavaScript

Or add an alias:

JavaScript

You could also change your route definition to the registered service id (acme_heartbeat.controller.heartbeat_controller::index), but I’d follow the recommendations and go with the first option.

User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement