<?php /** * 演示代码:php新特性之“接口” */ namespace test; interface Documentable { public function getId(); public function getContent(); } 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 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 DocumentStore { protected $data = []; public function addDocument(Documentable $document) { $key = $document->getId(); $value = $document->getContent(); $this->data[$key] = $value; } public function getDocuments() { return $this->data; } } function test() { $document_store = new \test\DocumentStore(); $resource = @fopen('test.txt', 'r'); if (false === $resource) { exit('no suche file: test.txt'); } $stream_document = new \test\StreamDocument($resource); $document_store->addDocument($stream_document); $url = 'http://www.baidu.com'; $html_document = new \test\HtmlDocument($url); $document_store->addDocument($html_document); $data = $document_store->getDocuments(); var_dump($data); } test();
php新特性之“接口”
猜你喜欢
转载自canlynet.iteye.com/blog/2376004
今日推荐
周排行