首页 / PHP / PHP接口的使用技巧
PHP接口的使用技巧
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了PHP接口的使用技巧,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含3001字,纯文字阅读大概需要5分钟。
内容图文
![PHP接口的使用技巧](/upload/InfoBanner/zyjiaocheng/143/ceeeabc56b304058973d35fd7fb95223.jpg)
摘要:在编程的过程中我们应该学会如何使用接口来给变我们的生活,极大的提升自我能力。接口不是新特性,但是非常重要,下面我们来撸个接口的小例子。 ...
虚构一个DocumentStore的类,这个类负责从不同的资源收集文本。可以从远程url读取html,也可以读取资源,也可以收集终端命令输出。
定义DocumentStore类
class DocumentStore{ protected $data = []; public function addDocument(Documenttable $document){ $key = $document->getId(); $value = $document->getContent(); $this->data[key] = $value; } public function getDocuments(){ return $this->data; } }
既然addDocument()方法的参数只能是Documenttable的类的实例,这样定义DocumentStore的类怎么行呢? 其实Documenttable不是类,是接口;
定义Documenttable
interface Documenttable{ public function getId(); public function getContent(); }
这个接口定义表名,实现Documenttable接口的任何对象都必须提供一个公开的getId()方法和一个公开的getContent()方法。
可是这么做有什么用呢?这么做的好处就是,我们可以分开定义获取稳定的类,而且能使用十分不同的方法。下面是一种实现方式,这种方式使用curl从远程url获取html。
定义HtmlDocument类
class HtmlDocument implements Documenttable{ 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); curl_setopt($ch,CURLOPT_RETURNTRANSFER,1); curl_setopt($ch,CURLOPT_CONNECTTIMEOUT,3); curl_setopt($ch,CURLOPT_FOLLOWLOCATION,1); curl_setopt($ch,CURLOPT_MAXREDIRS,3); curl_close($ch); return $thml; } }
下面一个方法是获取流资源。
class StreamDocument implements Documenttable{ 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 CommandOutDocument implements Documenttable{ protected $command; public function __construct($command) { $this->command=$command; } public function getId(){ return $this->command; } public function getContent(){ return shell_exec($this->command); } }
下面我们来演示一下借助上面的三个类来实现DocumentStore类。
$documentStore = new DocumentStore();//添加html文档$htmlDoc = new HtmlDocument('https:// www.i360.me'); $documentStore->addDocument($htmlDoc);//添加流文档$streamDOC = new StreamDocument(fopen('stream.txt','rb')); $documentStore->addDocument($streamDOC);//添加终端命令文档$cmdDoc = new CommandOutDocument('cat /etc/hosts'); $documentStore->addDocument($command); print_r($documentStore->getDocuments());die;
这里HtmlDocument,StreamDocument,CommandOutDocument这三个类没有任何共同点,只是实现了同一个接口。
以上就是PHP接口的使用技巧的详细内容,更多请关注Gxl网其它相关文章!
内容总结
以上是互联网集市为您收集整理的PHP接口的使用技巧全部内容,希望文章能够帮你解决PHP接口的使用技巧所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。