Architecture and request · Question 9 of 12
A controller requires a GeocoderInterface in its constructor. The extension contains two implementations, OpenStreetMapGeocoder and GoogleGeocoder. The container reports an error. How do you define the default implementation?
2 answers are correct. Medium
Show answer
Answer
- A Define an alias in Services.yaml: Vendor\
MyExt\ Geocoder\ GeocoderInterface: '@Vendor\ MyExt\ Geocoder\ OpenStreetMapGeocoder' - B Add the attribute #[AsAlias(GeocoderInterface::class)] to the class OpenStreetMapGeocoder
Explanation
If there is exactly one implementation, Symfony links it to the interface automatically when loading the classes. With two candidates the container does not know which one to use and aborts. An alias answers exactly that question, either with #[AsAlias] (Symfony DependencyInjection) directly on the class or in Services.yaml. public: true only makes a service retrievable from outside, and SingletonInterface only controls whether makeInstance reuses an instance.