0

I want to know. I found this in Symfony2 TranslationLoader class:

public function addLoader($format, LoaderInterface $loader)
{
    $this->loaders[$format] = $loader;
}

I found LoaderInterface there is only one method. But how we know the realization of this interface ? This is Interface Injection ?

nowiko
  • 2,507
  • 6
  • 38
  • 82
  • 1
    If you're "injecting" interface - then you're relying only on fact, that your parameter follows the contract, provided be that interface. The whole idea of interface is that contract - and you shouldn't be aware neither of specific implementation details, nor even what would be that implementation – Alma Do Jan 20 '15 at 13:01
  • @AlmaDo, so if I understand you, If my SomeClass will iplement LoaderInterface, and then I will call addLoader($format, SomeClass $loader) , it will be fine ? – nowiko Jan 20 '15 at 13:04
  • 1
    If you have a class that implements `LoaderInterface` it will have to contain all of the methods that the interface states, in this case just `public function load($resource, $locale, $domain = 'messages')` (https://github.com/symfony/Translation/blob/master/Loader/LoaderInterface.php). The interface is just an empty class that state what methods must be present in any class that implements it. – qooplmao Jan 20 '15 at 13:11
  • @Qoop, I know what is the interface, I didnt know how TranslationLoader class will be know what realization hidden behind LoaderInterface $loader load() method, but now I think it more clearly for me. – nowiko Jan 20 '15 at 13:17

1 Answers1

1

Interface injection is a thing, but really what you see in the snippet is Type Hinting, a form of strong typing.

What this does, is enforce at runtime that the value passed into $loader must match the definition of the interface (or class) specified in the type hint. Basically, an answer to the question:

Does $loader implement all the methods of LoaderInterface?

If it doesn't, you'll get a catchable fatal error.

Community
  • 1
  • 1
Peter Bailey
  • 105,256
  • 31
  • 182
  • 206