PHP|PHP的接口使用示例

举个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);    }}

使用方法:

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());

参考:

  1. Modern PHP

关键字:php, interface, #this-# function

版权声明

本文来自互联网用户投稿,文章观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处。如若内容有涉嫌抄袭侵权/违法违规/事实不符,请点击 举报 进行投诉反馈!

立即
投稿

微信公众账号

微信扫一扫加关注

返回
顶部