PHP|PHP的接口使用示例

发布时间:2019-08-07 发布网站:脚本宝典
脚本宝典收集整理的这篇文章主要介绍了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);
    }
}

使用方法:

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

参考:

  1. Modern PHP

脚本宝典总结

以上是脚本宝典为你收集整理的PHP|PHP的接口使用示例全部内容,希望文章能够帮你解决PHP|PHP的接口使用示例所遇到的问题。

如果觉得脚本宝典网站内容还不错,欢迎将脚本宝典推荐好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。