Why does Laravel have a contract / interface for almost everything?

I went through Laravel Illuminate, and I noticed that it has an interface for almost every implementation.

What is the purpose of this? Does it have any current use, or is it more to make the structure as scalable as possible?

+5
source share
1 answer

Software development contracts are more valuable than their implementation.

Here are a few reasons:

  • You can test classes that depend on the interface without relying on the implementation of the interface (which in itself may be a mistake). Example with PHPUnit:

    //Will return an object of this type with all the methods returning null. You can do more things with the mock builder as well $mockInterface = $this->getMockBuilder("MyInterface")->getMock(); $class = new ClassWhichRequiresInterface($mockInterface); //Test class using the mock 
  • You can write a class that uses a contract without the need for implementation, for example.

     function dependentFunction(MyInterface $interface) { $interface->contractMethod(); // Assume it there even though it not yet implemented. } 
  • Have one contract, but several implementations.

      interface FTPUploader { /* Contract */ } class SFTPUploader implements FTPUploader { /* Method implementation */ } class FTPSUploader implements FTPUploader { /* Method implementation */ } 

Laravel offers support for the latter using its service container as follows:

 $app->bind(FTPUploader::class, SFTPUploader::class); resolve(FTPUploader::class); //Gets an SFTPUploader object 

Then there is the fact that it is easier to document interfaces, since there are no real implementations, so they are still readable.

+5
source

Source: https://habr.com/ru/post/1264437/


All Articles