How to inject service as argument in symfony?

Member

by ryleigh , in category: PHP Frameworks , 6 months ago

How to inject service as argument in symfony?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

by arnoldo.moen , a month ago

@ryleigh 

In Symfony, you can inject a service as an argument by simply type-hinting the service's class in the constructor or method that requires the service.


For example, if you have a service called my_custom_service that you want to inject into a controller, you would modify the controller's constructor to include a parameter for the service:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
use AppServiceMyCustomService;

class MyController extends AbstractController
{
    private $myCustomService;

    public function __construct(MyCustomService $myCustomService)
    {
        $this->myCustomService = $myCustomService;
    }

    // ...
}


Then in your services.yaml file, you would configure the service to be injected into the controller:

1
2
3
4
services:
    AppControllerMyController:
        arguments:
            $myCustomService: '@AppServiceMyCustomService'


Now, whenever you instantiate MyController, Symfony will automatically inject an instance of MyCustomService into the controller's constructor.