PHP interface(接口)的示例代码
2016-11-26 21:57
609 查看
<?php 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; } } interface Documentable { public function getId(); public function getContent(); } 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); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 3); curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1); curl_setopt($ch, CURLOPT_MAXREDIRS, 3); $html = curl_exec($ch); curl_close($ch); return $html; } } 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); } } $documentStore = new DocumentStore(); //添加HTML文档 $htmlDoc = new HtmlDocument('https://php.net'); $documentStore->addDocument($htmlDoc); //添加流文档 $streamDoc = new StreamDocument(fopen('stream.txt', 'rb')); $documentStore->addDocument($streamDoc); //添加终端命令文档 $cmdDoc = new CommandOutputDocument('cat /etc/hosts'); $documentStore->addDocument($cmdDoc); print_r($documentStore->getDocuments());
相关文章推荐
- 基于PHP的聚合数据车辆违章查询接口调用代码示例
- php 接口与前端数据交互实现示例代码
- 基于PHP的短信接口调用示例代码模板
- 基于PHP的短信接口调用示例代码
- php请求接口的方法代码示例
- php版淘宝网查询商品接口代码示例
- php 微信接口API之长链接转短链接代码示例
- eoLinker-API_Shop_短信服务接口-调用示例代码,支持PHP、Python、Java等语言
- 话费充值接口示例代码_PHP DEMO
- php版淘宝网查询商品接口代码示例
- PHP支付宝接口示例代码-demo
- 聚合短信PHP代码示例短信接口调用CURL方法
- [Web开发] 微软的 PHP+IIS+WinServer 开发培训资料/示例代码
- php中DOMDocument简单用法示例代码(XML创建、添加、删除、修改)
- php header示例代码(推荐)
- .NET调用新浪微博开放平台接口的代码示例
- .NET调用新浪微博开放平台接口的代码示例
- HessianCSharp 1.3.3版本前使用泛型以及接口interface继承问题解决方案!!(实例代码)
- php 代码优化之经典示例
- PHP生成验证码的简单代码示例