您好,欢迎来到三六零分类信息网!老站,搜索引擎当天收录,欢迎发信息

PHP接口的使用技巧

2025/8/8 12:19:37发布27次查看
摘要:在编程的过程中我们应该学会如何使用接口来给变我们的生活,极大的提升自我能力。接口不是新特性,但是非常重要,下面我们来撸个接口的小例子。 ...
虚构一个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接口的使用技巧的详细内容。
该用户其它信息

VIP推荐

免费发布信息,免费发布B2B信息网站平台 - 三六零分类信息网 沪ICP备09012988号-2
企业名录 Product