Back to symfony.com

Lesson 6 of 11 · 4 min

Click any paragraph or press to highlight its code

Services & autowiring

Your app's logic lives in services: plain PHP classes like this one. There's nothing to register or configure: create the class and it's ready to use anywhere.

To use a service, type-hint it in the constructor. This is autowiring: Symfony reads the type and injects the right object. This design (dependency injection) keeps your classes decoupled and easy to test.

It works the same for the hundreds of services provided by Symfony and its ecosystem: here, a PSR-3 logger, ready to use by adding one constructor argument.

<?phpnamespace App\Service;class GreetingGenerator{    public function getRandomGreeting(string $name): string    {        $greeting = ['Hey', 'Yo', 'Aloha'][random_int(0, 2)];        return "$greeting $name!";    }}
<?phpnamespace App\Controller;use App\Service\GreetingGenerator;use Psr\Log\LoggerInterface;use Symfony\Component\HttpFoundation\Response;use Symfony\Component\Routing\Attribute\Route;class GreetingController{    public function __construct(        private GreetingGenerator $greetingGenerator,        private LoggerInterface $logger,    ) {    }    #[Route('/greet/{name}')]    public function greet(string $name): Response    {        $this->logger->info("Greeting $name");        $greeting = $this->greetingGenerator->getRandomGreeting($name);        return new Response($greeting);    }}