为什么Laravel几乎拥有所有合同/界面?

Mel*_*ans 5 php laravel laravel-5

我正在浏览Laravel的Illuminate,我发现它几乎每个实现都有一个界面.

这个的确切目的是什么?它是否有任何当前用途,或者更多的是使框架尽可能可扩展?

apo*_*fos 5

在软件工程中,合同比它们的实现更有价值.

这有以下几个原因:

  1. 您可以测试依赖于接口的类,而不依赖于接口实现(它本身可能是错误的).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
    
    Run Code Online (Sandbox Code Playgroud)
  2. 您可以编写一个使用合同而无需实现的类,例如

    function dependentFunction(MyInterface $interface) {
         $interface->contractMethod(); // Assume it's there even though it's not yet implemented. 
    }
    
    Run Code Online (Sandbox Code Playgroud)
  3. 有一个合同但有多个实现.

     interface FTPUploader { /* Contract */ }
    
     class SFTPUploader implements FTPUploader { /* Method implementation */ }
     class FTPSUploader implements FTPUploader { /* Method implementation */ }
    
    Run Code Online (Sandbox Code Playgroud)

Laravel使用其服务容器提供对最后一个的支持,如下所示:

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

resolve(FTPUploader::class); //Gets an SFTPUploader object
Run Code Online (Sandbox Code Playgroud)

然后还有一个事实是它更容易记录接口,因为那里没有实际的实现,所以它们仍然可读.