当前位置: 首页 > 后端技术 > PHP

如何优雅地使用界面

时间:2023-03-30 02:22:08 PHP

嗯,6.1刚过,我们已经不是宝宝了,来,看一篇界面文章(interface)。在编程的过程中,我们应该学会如何使用接口来改变我们的生活,大大提高自我能力。接口不是一个新特性,但它非常重要。让我们举一个接口的小例子。组成一个DocumentStore类,负责从不同的资源中收集文本。可以从远程url读取html,也可以读取资源,还可以收集终端命令输出。定义DocumentStore类classDocumentStore{protected$data=[];publicfunctionaddDocument(Documenttable$document){$key=$document->getId();$value=$document->getContent();$this->data[key]=$value;}publicfunctiongetDocuments(){return$this->data;}}既然addDocument()方法的参数只能是Documenttable类的一个实例,那么如何定义DocumentStore类呢?该类是一个接口;定义DocumenttableinterfaceDocumenttable{publicfunctiongetId();公共函数getContent();}这个接口定义了表的名称,任何实现Documenttable接口的对象都必须提供一个publicgetId()方法和一个publicgetContent()方法。可是这样做有什么用呢?这样做的好处是我们可以分离定义来获得稳定的类,并且可以使用非常不同的方法。这是一种方法,这种方法使用curl从远程url获取html。定义HtmlDocument类classHtmlDocumentimplementsDocumenttable{protected$url;公共函数__construct($url){$this->url=$url;}publicfunctiongetId(){return$this->url;}公共函数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);返回$thml;}}下一个方法是获取流资源。类StreamDocument实现Documenttable{protected$resource;受保护的$缓冲区;公共函数__construct($resource,$buffer=4096){$this->resource=$resource;$this->缓冲区=$缓冲区;}publicfunctiongetId(){return'resource-'.(int)$this->resource;}公共函数getContent(){$streamContent='';倒带($this->资源);while(feof($this->resource)===false){$streamContent.=fread($this->resource,$this->buffer);}返回$streamContent;}}下面这个类就是获取终端命令行的执行结果。类CommandOutDocument实现Documenttable{protected$command;公共函数__construct($command){$this->command=$command;}publicfunctiongetId(){return$this->command;}publicfunctiongetContent(){returnshell_exec($this->command);}}下面我们来演示如何借助以上三个类来实现DocumentStore类。$documentStore=newDocumentStore();//添加html文档$htmlDoc=newHtmlDocument('https://www.i360.me');$documentStore->addDocument($htmlDoc);//添加流文档$streamDOC=newStreamDocument(fopen('stream.txt','rb'));$documentStore->addDocument($streamDOC);//添加终端命令文档$cmdDoc=newCommandOutDocument('cat/etc/hosts');$documentStore->addDocument($command);print_r($documentStore->getDocuments());死;在这里,HtmlDocument、StreamDocument和CommandOutDocument这三个类没有任何共同点,它们只是实现了相同的接口。