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.

Certifications & exams

Which exam comes next?

You can already practise for 19 exams, and 21 are up for a vote. See all certifications with their official information, cast your vote or suggest your exam.

See all certifications