【发布时间】:2017-09-24 10:58:25
【问题描述】:
我是一名自学成才的程序员,目前正在学习 Zend Framework 2。
我总是想知道为什么每次我尝试包含某个服务时,他们总是要求我使用它的接口版本。
例如,如果我尝试使用服务定位器,我必须包含 serviceLocatorInterface 才能使用服务定位器。 为什么我不能只使用服务定位器类本身。
这里来自抽象工厂类。
use Zend\ServiceManager\ServiceLocatorInterface;
那我就这样用吧
public function canCreateServiceWithName(ServiceLocatorInterface $serviceLocator, $name, $requestedName)
这是 Zend 教程中的另一个示例,https://framework.zend.com/manual/2.4/en/in-depth-guide/services-and-servicemanager.html#bringing-the-service-into-the-controller
use Blog\Service\PostServiceInterface;
我们包括PostServiceInterface。为什么不只是 PostService?
public function __construct(PostServiceInterface $postService)
我们在这里使用PostServiceInterface。为什么不把 PostService 作为一个类型。
我相信这是一个所有学生都可以回答的非常简单的答案,但是由于我是自己学习的,所以我很难理解它。
PS。我确实了解接口和继承的概念。我只是不知道为什么我们以这种方式包含接口。
编辑:在回答之后,我找到了一个链接,可以帮助我更好地理解为什么人们将接口作为类型依赖项而不是具体类型传递。
What is the difference between an interface and abstract class?
http://kristopherwilson.com/2015/03/26/using-interfaces-effectively-in-php/
我希望这些链接也对其他人有所帮助。
【问题讨论】:
标签: php oop interface namespaces zend-framework2