How to override autowired symfony service?

Member

by kadin , in category: PHP Frameworks , 2 months ago

How to override autowired symfony service?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

Member

by deron , 2 months ago

@kadin 

To override an autowired service in Symfony, you can follow these steps:

  1. Create a new service class that extends the original service class you want to override.
1
2
3
4
5
6
use AppServiceOriginalService;

class OverriddenService extends OriginalService
{
    // custom implementation
}


  1. Create a new service definition in the services.yaml file and specify the class of the overridden service.
1
2
3
services:
    AppServiceOriginalService:
        class: AppServiceOverriddenService


  1. Clear the Symfony cache to make sure the changes are reflected.
1
bin/console cache:clear


After performing the above steps, whenever you autowire the original service in your code, Symfony will use the overridden service instead.