Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

I was going through the Laravel's Illuminate and I noticed it has an interface for nearly every implementation.

What's the exact purpose of this? Does it have any current use, or is it more to make the framework as scaleable as possible?

like image 815
Melvin Koopmans Avatar asked Feb 20 '17 08:02

Melvin Koopmans


1 Answers

In software engineering contracts are more valuable than their implementations.

Here's a few reasons:

  1. You can test classes which depend on an interface without relying on an interface implementation (which itself may be buggy). 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
    
  2. You can write a class which uses a contract without needing an implementation e.g.

    function dependentFunction(MyInterface $interface) {
         $interface->contractMethod(); // Assume it's there even though it's not yet implemented. 
    }
    
  3. Have a single contract but multiple implementations.

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

Laravel offers support of the last one using its service container as follows:

$app->bind(FTPUploader::class, SFTPUploader::class); 

resolve(FTPUploader::class); //Gets an SFTPUploader object

Then there's also the fact that its easier to document interfaces since there's no actual implementations in there so they're still readable.

like image 58
apokryfos Avatar answered Sep 20 '22 01:09

apokryfos