您好,登錄后才能下訂單哦!
代理模式是很好用的,不過我們經常用JS來實現(xiàn)一些圖片的懶加載,而且現(xiàn)在有很多繼承好的js
對于PHP的,肯定不僅僅限于圖片,不過這次的例子還是PHP的圖片代理,是可以直接顯示圖片的,修改下路徑就好。
應用情境:1.圖片代理,2.遠程代理,3.智能指引,4.虛擬代理,5.動態(tài)代理
一般是開啟多線程。代理對象中一個線程向客戶端瀏覽器加載一個小圖片,第二個線程調用大圖片加載程序第三個線程,當用戶瀏覽大圖還沒有加載出來就顯示 相應的提示信息 (這個示例沒有利用線程)
這樣的話就完全將加載圖片放在了后臺,同樣處理其他的業(yè)務也是可以借鑒
上代碼:
<?php //多用于功能列表,繼承一些公用的接口函數(shù) interface Image{ public function getWidth(); public function getHeight(); public function getPath(); /** * @return string the p_w_picpath's byte stream */ public function dump(); } //可以多體會下抽象對象的用法,不能實例化 abstract class AbstractImage implements Image{ protected $_width; protected $_height; protected $_path; protected $_data; protected $_type; public function getWidth(){ return $this->_width; } public function getHeight(){ return $this->_height; } public function getPath(){ return $this->_path; } } //具體的實體對象 繼承抽象類對于接口的重寫 //可以直接使用抽象對象的通用屬性width,height,path,data //包括可以直接重新定義接口里的函數(shù) //這是實際的圖片對象 class RawImage extends AbstractImage{ public function __construct($path){ $this->_path = $path; //list() 函數(shù)用數(shù)組中的元素為一組變量賦值。按照數(shù)組的數(shù)字索引 依次賦值 //注意,與 array() 類似,list() 實際上是一種語言結構,不是函數(shù)。 list($this->_width,$this->_height) = getp_w_picpathsize($path); $this->_type = getp_w_picpathsize($path)['mime']; //file_get_contents() 函數(shù)把整個文件讀入一個字符串中。 //和 file() 一樣,不同的是 file_get_contents() 把文件讀入一個字符串。 //file_get_contents() 函數(shù)是用于將文件的內容讀入到一個字符串中的首選方法。如果操作系統(tǒng)支持,還會使用內存映射技術來增強性能。 $this->_data = file_get_contents($path); } public function dump_type(){ return $this->_type; } public function dump(){ return $this->_data; } } //它和實際的圖片對象繼承同一個抽象接口,基本上就是同樣的 //這時候就可以增加很多人性化的功能,與圖片無關,與用戶體驗有關 class ImageProxy extends AbstractImage{ protected $_realImage; public function __construct($path){ $this->_path = $path; list($this->_width,$this->_height) = getp_w_picpathsize($path); $this->_type = getp_w_picpathsize($path)['mime']; //這里就沒必要獲取圖片的真實數(shù)據(jù),畢竟很大 } /** * Creates a RawImage and exploits its functionalities. */ //這里去獲取真實圖片的所有數(shù)據(jù) protected function _lazyLoad(){ if($this->_realImage === null){ $this->_realImage = new RawImage($this->_path); } } public function dump_type(){ return $this->_type; } public function dump(){ $this->_lazyLoad(); return $this->_realImage->dump(); } } //基本上一個很簡單的代理寫完了,如何發(fā)揮更多的效用,需要好好引進去很多處理思路,但是位置一定是寫在代理里面 //下面就是客戶端類 class Client{ public function tag(Image $img){ $type=$img->dump_type(); header("content-type:$type"); echo $img->dump(); } } $path = 'd:/p_w_picpath/timg3.jpg'; $client = new Client(); $p_w_picpath = new ImageProxy($path); //$p_w_picpath = new RawImage($path); $client->tag($p_w_picpath); ?>
愿法界眾生,皆得安樂。
免責聲明:本站發(fā)布的內容(圖片、視頻和文字)以原創(chuàng)、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關證據(jù),一經查實,將立刻刪除涉嫌侵權內容。