接口:
应用场景:将注册日志写入文件系统
<?php
class FileLogger
{
public function save($message)
{
//将日志写入文件中
var_dump('log into file '. $message);
}
}
class UsersController
{
protected $logger;
public function __construct(FileLogger $logger)
{
$this->logger = $logger;
}
public function register()
{
$user = 'liang';
$this->logger->save($user);
}
}
$controller = new UsersController(new FileLogger());
$controller->register();
现在需求改变了,需要将注册日志写入数据库。
解决办法:
<?php
interface Logger
{
public function save($message);
}
class FileLogger implements Logger
{
public function save($message)
{
//将日志写入文件中
var_dump('log into file '. $message);
}
}
class DatabaseLogger implements Logger
{
public function save($message)
{
//将日志写入数据库
var_dump('log into database '. $message);
}
}
class UsersController
{
protected $logger;
public function __construct(Logger $logger)
{
$this->logger = $logger;
}
public function register()
{
$user = 'liang';
$this->logger->save($user);
}
}
$controller = new UsersController(new DatabaseLogger());
$controller->register();
总结:
- 采用OOP的面向接口编程,从而提高代码的可维护性。
- laravel/framework/src/Illuminate/Contracts/ 里面的类基本是interface
可以把接口比喻成Contracts(契约)
契约上面的条款就好比implements了接口的类
当你要执行某一条条款的时候,可以通过契约(依赖注入)调用条款。