举个Demo来说明接口的作用。
有这么一个类。
class DocumentStore
{
protected $data = [];
public function addDocument(Documentable $document)
{
$key = $document->getId();
$value = $document->getContent();
$this->data[$key] = $value;
}
public function getDocuments()
{
return $this->data;
}
}
其中Documentable
就是接口。定义如下:
interface Documentable
{
public function getId();
public function getContent();
}
在未来的业务开发中,我们不必关心具体的Document的获取场景,只需要确定,这个Document实现了这个接口,拥有这两个方法即可。实现了业务细节和整体架构抽象的解耦。
举个例子:
class HtmlDocument implements Documentable
{
protected $url;
public function __construct($url)
{
$this->url = $url;
}
public function getId()
{
return $this->url;
}
public function getContent()
{
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $this->url);
// opt etc
$html = curl_exec($ch);
curl_close($ch);
return $htl;
}
}
再举个例子:
class StreamDocument implements Documentable
{
protected $resource;
protected $buffer;
public function __construct($resource, $buffer = 4096)
{
$this->resource = $resource;
$this->buffer = $buffer;
}
public function getId()
{
return 'resource-' . (int)$this->resource;
}
public function getContent()
{
$streamContent = '';
rewind($this->resource);
while (feof($this->resource) === false) {
$streamContent .= fread($this->resource, $this->buffer);
}
return $streamContent;
}
}
再举个例子:
class CommandOutputDocument implements Documentable
{
protected $command;
public function __construct($command)
{
$this->command = $command;
}
public function getId()
{
return $this->command;
}
public function getContent()
{
return shell_exec($this->command);
}
}
使用方法:
<?php
$documentStore = new DocumentStore();
$htmlDoc = new HtmlDocument('https://php.net');
$documentStore->addDocument($htmlDoc);
$streamDoc = new StreamDocument(fopen('stream.txt', 'rb'));
$streamDoc->addDocument($streamDoc);
$cmdDoc = new CommandOutputDocument('cat /etc/hosts');
$documentStore->addDocument($cmdDoc);
print_r($documentStore->getDocuments());
参考:
Modern PHP
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。