YII Framework架構教程之緩衝用法詳解,yiiframework
本文執行個體講述了YII Framework架構緩衝用法。分享給大家供大家參考,具體如下:
緩衝的產生原因眾所周知。於是YII作為一個高效,好用的架構,不能不支援緩衝。所以YII對各種流行的緩衝都提供了介面,你可以根據你的需要使用不同的緩衝。
1.YII中的緩衝介紹
YII中的緩衝是通過組件方式定義的,具體在如下目錄
/yii_dev/yii/framework/caching# tree
.
├── CApcCache.php
├── CCache.php
├── CDbCache.php
├── CDummyCache.php
├── CEAcceleratorCache.php
├── CFileCache.php
├── CMemCache.php
├── CWinCache.php
├── CXCache.php
├── CZendDataCache.php
└── dependencies
├── CCacheDependency.php
├── CChainedCacheDependency.php
├── CDbCacheDependency.php
├── CDirectoryCacheDependency.php
├── CExpressionDependency.php
├── CFileCacheDependency.php
└── CGlobalStateCacheDependency.php
1 directory, 17 files
官方原文解釋如下:
Yii 提供了不同的緩衝組件,可以將快取資料儲存到不同的媒介中。例如, CMemCache 組件封裝了 PHP 的 memcache 擴充並使用記憶體作為緩衝儲存媒介。 CApcCache 組件封裝了 PHP APC 擴充; 而 CDbCache 組件會將緩衝的資料存入資料庫。下面是一個可用緩衝組件的列表:
CMemCache: 使用 PHP memcache 擴充.
CApcCache: 使用 PHP APC 擴充.
CXCache: 使用 PHP XCache 擴充。注意,這個是從 1.0.1 版本開始支援的。
CEAcceleratorCache: 使用 PHP EAccelerator 擴充.
CDbCache: 使用一個資料表格儲存體快取資料。預設情況下,它將建立並使用在 runtime 目錄下的一個 SQLite3 資料庫。 你也可以通過設定其 connectionID 屬性指定一個給它使用的資料庫。
CZendDataCache: 使用 Zend Data Cache 作為後台緩衝媒介。注意,這個是從 1.0.4 版本開始支援的。
CFileCache: 使用檔案儲存體快取資料。這個特別適合用於儲存大塊資料(例如頁面)。注意,這個是從 1.0.6 版本開始支援的。
CDummyCache: 目前 dummy 緩衝並不實現緩衝功能。此組件的目的是用於簡化那些需要檢查緩衝可用性的代碼。 例如,在開發階段或者伺服器尚未支援實際的緩衝功能,我們可以使用此緩衝組件。當啟用了實際的緩衝支援後,我們可以切換到使用相應的緩衝組件。 在這兩種情況中,我們可以使用同樣的代碼Yii::app()->cache->get($key) 擷取資料片段而不需要擔心 Yii::app()->cache 可能會是 null。此組件從 1.0.5 版開始支援。
提示: 由於所有的這些緩衝組件均繼承自同樣的基類 CCache,因此無需改變使用緩衝的那些代碼就可以切換到使用另一種緩衝方式。
緩衝可以用於不同的層級。最低層級中,我們使用緩衝儲存單個資料片段,例如變數,我們將此稱為 資料緩衝(data caching)。下一個層級中,我們在緩衝中儲存一個由視圖指令碼的一部分產生的頁面片段。 而在最進階別中,我們將整個頁面儲存在緩衝中並在需要時取回。
在接下來的幾個小節中,我們會詳細講解如何在這些層級中使用緩衝。
注意: 按照定義,緩衝是一個不穩定的儲存媒介。即使沒有逾時,它也並不確保快取資料一定存在。 因此,不要將緩衝作為持久儲存空間使用。(例如,不要使用緩衝儲存 Session 資料)。
2.緩衝的配置和調用方式
yii中的緩衝主要是通過組件的方式實現的,具體需要配置方式可以通過緩衝的類說明進行配置。
通常是指定緩衝組件的類
例如apc
'cache'=>array( 'class'=>'system.caching.CApcCache'),
memcache的配置方式可能是
* array(* 'components'=>array(* 'cache'=>array(* 'class'=>'CMemCache',* 'servers'=>array(* array(* 'host'=>'server1',* 'port'=>11211,* 'weight'=>60,* ),* array(* 'host'=>'server2',* 'port'=>11211,* 'weight'=>40,* ),* ),* ),* ),* )
使用方式:
yii封裝了對不同快取作業的方法,主要集中在CCache。CCache是所有Cache類的基類。所以配置好緩衝後可以調用方式很簡單:
<?php/** * CCache is the base class for cache classes with different cache storage implementation. * * A data item can be stored in cache by calling {@link set} and be retrieved back * later by {@link get}. In both operations, a key identifying the data item is required. * An expiration time and/or a dependency can also be specified when calling {@link set}. * If the data item expires or the dependency changes, calling {@link get} will not * return back the data item. * * Note, by definition, cache does not ensure the existence of a value * even if it does not expire. Cache is not meant to be a persistent storage. * * CCache implements the interface {@link ICache} with the following methods: *
*
- {@link get} : retrieve the value with a key (if any) from cache
*
- {@link set} : store the value with a key into cache
*
- {@link add} : store the value only if cache does not have this key
*
- {@link delete} : delete the value with the specified key from cache
*
- {@link flush} : delete all values from cache
*
* * Child classes must implement the following methods: *
*
- {@link getValue}
*
- {@link setValue}
*
- {@link addValue}
*
- {@link deleteValue}
*
- {@link flush} (optional)
*
* * CCache also implements ArrayAccess so that it can be used like an array. * * @author Qiang Xue * @version $Id: CCache.php 3001 2011-02-24 16:42:44Z alexander.makarow $ * @package system.caching * @since 1.0 */abstract class CCache extends CApplicationComponent implements ICache, ArrayAccess{
根據CCache類說明可以看出,常見的快取作業方法get,set,add,delete,flush
/** * Retrieves a value from cache with a specified key. * @param string $id a key identifying the cached value * @return mixed the value stored in cache, false if the value is not in the cache, expired or the dependency has changed. */public function get($id){ if(($value=$this->getValue($this->generateUniqueKey($id)))!==false) { $data=unserialize($value); if(!is_array($data)) return false; if(!($data[1] instanceof ICacheDependency) || !$data[1]->getHasChanged()) { Yii::trace('Serving "'.$id.'" from cache','system.caching.'.get_class($this)); return $data[0]; } } return false;}/** * Retrieves multiple values from cache with the specified keys. * Some caches (such as memcache, apc) allow retrieving multiple cached values at one time, * which may improve the performance since it reduces the communication cost. * In case a cache doesn't support this feature natively, it will be simulated by this method. * @param array $ids list of keys identifying the cached values * @return array list of cached values corresponding to the specified keys. The array * is returned in terms of (key,value) pairs. * If a value is not cached or expired, the corresponding array value will be false. * @since 1.0.8 */public function mget($ids){ $uniqueIDs=array(); $results=array(); foreach($ids as $id) { $uniqueIDs[$id]=$this->generateUniqueKey($id); $results[$id]=false; } $values=$this->getValues($uniqueIDs); foreach($uniqueIDs as $id=>$uniqueID) { if(!isset($values[$uniqueID])) continue; $data=unserialize($values[$uniqueID]); if(is_array($data) && (!($data[1] instanceof ICacheDependency) || !$data[1]->getHasChanged())) { Yii::trace('Serving "'.$id.'" from cache','system.caching.'.get_class($this)); $results[$id]=$data[0]; } } return $results;}/** * Stores a value identified by a key into cache. * If the cache already contains such a key, the existing value and * expiration time will be replaced with the new ones. * * @param string $id the key identifying the value to be cached * @param mixed $value the value to be cached * @param integer $expire the number of seconds in which the cached value will expire. 0 means never expire. * @param ICacheDependency $dependency dependency of the cached item. If the dependency changes, the item is labeled invalid. * @return boolean true if the value is successfully stored into cache, false otherwise */public function set($id,$value,$expire=0,$dependency=null){ Yii::trace('Saving "'.$id.'" to cache','system.caching.'.get_class($this)); if($dependency!==null) $dependency->evaluateDependency(); $data=array($value,$dependency); return $this->setValue($this->generateUniqueKey($id),serialize($data),$expire);}/** * Stores a value identified by a key into cache if the cache does not contain this key. * Nothing will be done if the cache already contains the key. * @param string $id the key identifying the value to be cached * @param mixed $value the value to be cached * @param integer $expire the number of seconds in which the cached value will expire. 0 means never expire. * @param ICacheDependency $dependency dependency of the cached item. If the dependency changes, the item is labeled invalid. * @return boolean true if the value is successfully stored into cache, false otherwise */public function add($id,$value,$expire=0,$dependency=null){ Yii::trace('Adding "'.$id.'" to cache','system.caching.'.get_class($this)); if($dependency!==null) $dependency->evaluateDependency(); $data=array($value,$dependency); return $this->addValue($this->generateUniqueKey($id),serialize($data),$expire);}/** * Deletes a value with the specified key from cache * @param string $id the key of the value to be deleted * @return boolean if no error happens during deletion */public function delete($id){ Yii::trace('Deleting "'.$id.'" from cache','system.caching.'.get_class($this)); return $this->deleteValue($this->generateUniqueKey($id));}/** * Deletes all values from cache. * Be careful of performing this operation if the cache is shared by multiple applications. * @return boolean whether the flush operation was successful. */public function flush(){ Yii::trace('Flushing cache','system.caching.'.get_class($this)); return $this->flushValues();}
即:
Yii::app()->cache->xxx
xxx對應具體的方法。
例如:
$id = 'key1';$value = 'cache value';Yii::app()->cache->add($id, $value);var_dump(Yii::app()->cache->get($id));
下面是yii官方給出的幾種緩衝方式的使用說明,這裡就麻木不仁,照搬了
3.緩衝的使用:資料緩衝
資料緩衝
資料緩衝即儲存一些 PHP 變數到緩衝中,以後再從緩衝中取出來。出於此目的,緩衝組件的基類 CCache 提供了兩個最常用的方法: set() 和 get()。
要在緩衝中儲存一個變數 $value ,我們選擇一個唯一 ID 並調用 set() 儲存它:
Yii::app()->cache->set($id, $value);
緩衝的資料將一直留在緩衝中,除非它由於某些緩衝策略(例如緩衝空間已滿,舊的資料被刪除)而被清除。 要改變這種行為,我們可以在調用 set() 的同時提供一個到期參數,這樣在設定的時間段之後,快取資料將被清除:
// 值$value 在緩衝中最多保留30秒Yii::app()->cache->set($id, $value, 30);
稍後當我們需要訪問此變數時(在同一個或不同的 Web 請求中),就可以通過 ID 調用 get() 從緩衝中將其取回。 如果返回的是 false,表示此值在緩衝中不可用,我們應該重建它。
$value=Yii::app()->cache->get($id);if($value===false){ // 因為在緩衝中沒找到 $value ,重建它 , // 並將它存入緩衝以備以後使用: // Yii::app()->cache->set($id,$value);}
為要存入緩衝的變數選擇 ID 時,要確保此 ID 對應用中所有其他存入緩衝的變數是唯一的。 而在不同的應用之間,這個 ID 不需要是唯一的。緩衝組件具有足夠的智慧區分不同應用中的 ID。
一些緩衝儲存空間,例如 MemCache, APC, 支援以批量模式擷取多個緩衝值。這可以減少擷取快取資料時帶來的開銷。 從版本 1.0.8 起,Yii 提供了一個新的名為 mget() 的方法。它可以利用此功能。如果底層緩衝儲存空間不支援此功能,mget() 依然可以類比實現它。
要從緩衝中清除一個緩衝值,調用 delete(); 要清楚緩衝中的所有資料,調用 flush()。 當調用 flush() 時一定要小心,因為它會同時清除其他應用中的緩衝。
提示: 由於 CCache 實現了 ArrayAccess,緩衝組件也可以像一個數組一樣使用。下面是幾個例子:
$cache=Yii::app()->cache;$cache['var1']=$value1; // 相當於: $cache->set('var1',$value1);$value2=$cache['var2']; // 相當於: $value2=$cache->get('var2');
1. 緩衝依賴
除了到期設定,快取資料也可能會因為依賴條件發生變化而失效。例如,如果我們緩衝了某些檔案的內容,而這些檔案發生了改變,我們就應該讓緩衝的資料失效, 並從檔案中讀取最新內容而不是從緩衝中讀取。
我們將一個依賴關係表現為一個 CCacheDependency 或其子類的執行個體。 當調用 set() 時,我們連同要緩衝的資料將其一同傳入。
// 此值將在30秒後失效// 也可能因依賴的檔案發生了變化而更快失效Yii::app()->cache->set($id, $value, 30, new CFileCacheDependency('FileName'));
現在如果我們通過調用get() 從緩衝中擷取 $value ,依賴關係將被檢查,如果發生改變,我們將會得到一個 false 值,表示資料需要被重建。
如下是可用的緩衝依賴的簡要說明:
CFileCacheDependency: 如果檔案的最後修改時間發生改變,則依賴改變。
CDirectoryCacheDependency: 如果目錄和其子目錄中的檔案發生改變,則依賴改變。
CDbCacheDependency: 如果指定 SQL 陳述式的查詢結果發生改變,則依賴改變。
CGlobalStateCacheDependency: 如果指定的全域狀態發生改變,則依賴改變。全域狀態是應用中的一個跨請求,跨會話的變數。它是通過 CApplication::setGlobalState() 定義的。
CChainedCacheDependency: 如果鏈中的任何依賴發生改變,則此依賴改變。
CExpressionDependency: 如果指定的 PHP 運算式的結果發生改變,則依賴改變。此類從版本 1.0.4 起可用。
4.緩衝的使用:片段快取
片段快取(Fragment Caching)
片段快取指緩衝網頁某片段。例如,如果一個頁面在表中顯示每年的銷售摘要,我們可以儲存此表在緩衝中,減少每次請求需要重新產生的時間。
要使用片段快取,在控制器視圖指令碼中調用CController::beginCache() 和CController::endCache() 。這兩種方法開始和結束包括的頁面內容將被緩衝。類似data caching ,我們需要一個編號,識別被緩衝的片段。
...別的HTML內容...<?php if($this->beginCache($id)) { ?>...被緩衝的內容...<?php $this->endCache(); } ?>...別的HTML內容...
在上面的,如果beginCache() 返回false,緩衝的內容將此地方自動插入; 否則,在if語句內的內容將被執行並在endCache()觸發時緩衝。
1. 緩衝選項(Caching Options)
當調用beginCache(),可以提供一個數組由緩衝選項組成的作為第二個參數,以自訂片段快取。事實上為了方便,beginCache() 和endCache()方法是[ COutputCache ]widget的封裝。因此COutputCache的所有屬性都可以在緩衝選項中初始化。
有效期間(Duration)
也許是最常見的選項是duration,指定了內容在緩衝中多久有效。和CCache::set()到期參數有點類似。下面的代碼緩衝內容片段最多一小時:
...其他HTML內容...<?php if($this->beginCache($id, array('duration'=>3600))) { ?>...被緩衝的內容...<?php $this->endCache(); } ?>...其他HTML內容...
如果我們不設定期限,它將預設為60 ,這意味著60秒後緩衝內容將無效。
依賴(Dependency)
像data caching ,內容片段被緩衝也可以有依賴。例如,文章的內容被顯示取決於文章是否被修改。
要指定一個依賴,我們建立了dependency選項,可以是一個實現[ICacheDependency]的對象或可用於產生依賴對象的配置數組。下面的代碼指定片段內容取決於lastModified 列的值是否變化:
...其他HTML內容...<?php if($this->beginCache($id, array('dependency'=>array( 'class'=>'system.caching.dependencies.CDbCacheDependency', 'sql'=>'SELECT MAX(lastModified) FROM Post')))) { ?>...被緩衝的內容...<?php $this->endCache(); } ?>...其他HTML內容...
變化(Variation)
緩衝的內容可根據一些參數變化。例如,每個人的檔案都不一樣。緩衝的檔案內容將根據每個人ID變化。這意味著,當調用beginCache()時將用不同的ID。
COutputCache內建了這一特徵,程式員不需要編寫根據ID變動內容的模式。以下是摘要。
varyByRoute: 設定此選項為true ,緩衝的內容將根據route變化。因此,每個控制器和行動的組合將有一個單獨的緩衝內容。
varyBySession: 設定此選項為true ,緩衝的內容將根據session ID變化。因此,每個使用者會話可能會看到由緩衝提供的不同內容。
varyByParam: 設定此選項的數組裡的名字,緩衝的內容將根據GET參數的值變動。例如,如果一個頁面顯示文章的內容根據id的GET參數,我們可以指定varyByParam為array('id'),以使我們能夠緩衝每篇文章內容。如果沒有這樣的變化,我們只能能夠緩衝某一文章。
varyByExpression: by setting this option to a PHP expression, we can make the cached content to be variated according to the result of this PHP expression. This option has been available since version 1.0.4.
Request Types
有時候,我們希望片段快取只對某些類型的請求啟用。例如,對於某張網頁上顯示表單,我們只想要緩衝initially requested表單(通過GET請求)。任何隨後顯示(通過POST請求)的表單將不被緩衝,因為表單可能包含使用者輸入。要做到這一點,我們可以指定requestTypes 選項:
...其他HTML內容...<?php if($this->beginCache($id, array('requestTypes'=>array('GET')))) { ?>...被緩衝的內容...<?php $this->endCache(); } ?>...其他HTML內容...
2. 嵌套緩衝(Nested Caching)
片段快取可以嵌套。就是說一個緩衝片段附在一個更大的片段快取裡。例如,意見緩衝在內部片段快取,而且它們一起在外部緩衝中在文章內容裡緩衝。
...其他HTML內容...<?php if($this->beginCache($id1)) { ?>...外部被緩衝內容... <?php if($this->beginCache($id2)) { ?> ...內部被緩衝內容... <?php $this->endCache(); } ?>...外部被緩衝內容...<?php $this->endCache(); } ?>...其他HTML內容...
嵌套緩衝可以設定不同的緩衝選項。例如, 在上面的例子中內部緩衝和外部緩衝可以設定時間長短不同的持續值。當資料存放區在外部快取無效判定,內部緩衝仍然可以提供有效內部片段。 然而,反之就不行了。如果外部緩衝包含有效資料, 它會永遠保持快取複本,即使內容中的內部緩衝已經到期。
5.緩衝的使用:頁面緩衝
頁面緩衝
頁面緩衝指的是緩衝整個頁面的內容。頁面緩衝可以發生在不同的地方。 例如,通過選擇適當的頁面頭,用戶端的瀏覽器可能會緩衝網頁瀏覽有限時間。 Web應用程式本身也可以在緩衝中儲存網頁內容。 在本節中,我們側重於後一種辦法。
頁面緩衝可以被看作是 片段快取一個特殊情況 。 由於網頁內容是往往通過應用布局來產生,如果我們只是簡單的在布局中調用beginCache() 和endCache(),將無法正常工作。 這是因為布局在CController::render()方法裡的載入是在頁面內容產生之後。
如果想要緩衝整個頁面,我們應該跳過產生網頁內容的動作執行。我們可以使用COutputCache作為動作 過濾器來完成這一任務。下面的代碼示範如何配置緩衝過濾器:
public function filters(){ return array( array( 'COutputCache', 'duration'=>100, 'varyByParam'=>array('id'), ), );}
上述過濾器配置會使過濾器適用於控制器中的所有行動。 我們可能會限制它在一個或幾個行動通過使用外掛程式操作器。 更多的細節中可以看過濾器。
Tip: 我們可以使用COutputCache作為一個過濾器,因為它從CFilterWidget繼承過來, 這意味著它是一個工具(widget)和一個過濾器。事實上,widget的工作方式和過濾器非常相似: 工具widget (過濾器filter)是在action動作裡的內容執行前執行,在執行後結束。
6.緩衝的使用:動態內容
動態內容(Dynamic Content)
當使用fragment caching或page caching,我們常常遇到的這樣的情況 整個部分的輸出除了個別地方都是靜態。例如,協助頁可能會顯示靜態協助 資訊,而使用者名稱稱顯示的是目前使用者的。
解決這個問題,我們可以根據使用者名稱匹配緩衝內容,但是這將是我們寶貴空間一個巨大的浪費,因為緩衝除了使用者名稱其他大部分內容是相同的。我們還可以把網頁切成幾個片段並分別緩衝,但這種情況會使頁面和代碼變得非常複雜。更好的方法是使用由[ CController ]提供的動態內容dynamic content功能 。
動態內容是指片段輸出即使是在片段快取包括的內容中也不會被緩衝。即使是包括的內容是從緩衝中取出,為了使動態內容在所有時間是動態,每次都得重建。出於這個原因,我們要求 動態內容通過一些方法或函數產生。
調用CController::renderDynamic()在你想的地方插入動態內容。
...別的HTML內容...<?php if($this->beginCache($id)) { ?>...被緩衝的片段內容... <?php $this->renderDynamic($callback); ?>...被緩衝的片段內容...<?php $this->endCache(); } ?>...別的HTML內容...
在上面的, $callback指的是有效PHP回調。它可以是指向當前控制器類的方法或者全域函數的字串名。它也可以是一個數組名指向一個類的方法。其他任何的參數,將傳遞到renderDynamic()方法中。回調將返回動態內容而不是僅僅顯示它。
更多關於Yii相關內容感興趣的讀者可查看本站專題:《Yii架構入門及常用技巧總結》、《php優秀開發架構總結》、《smarty模板入門基礎教程》、《php日期與時間用法總結》、《php物件導向程式設計入門教程》、《php字串(string)用法總結》、《php+mysql資料庫操作入門教程》及《php常見資料庫操作技巧匯總》
希望本文所述對大家基於Yii架構的PHP程式設計有所協助。
您可能感興趣的文章:
- PHP YII架構開發小技巧之模型(models)中rules自訂驗證規則
- Nginx配置PHP的Yii與CakePHP架構的rewrite規則樣本
- 使用Composer安裝Yii架構的方法
- Yii使用migrate命令執行sql語句的方法
- YII Framework架構使用YIIC快速建立YII應用之migrate用法執行個體詳解
- YII Framework架構教程之使用YIIC快速建立YII應用詳解
- YII Framework架構教程之國際化實現方法
- YII Framework架構教程之安全方案詳解
- YII Framework架構教程之日誌用法詳解
- YII Framework教程之異常處理詳解
- Yii rules常用規則樣本
http://www.bkjia.com/PHPjc/1110085.htmlwww.bkjia.comtruehttp://www.bkjia.com/PHPjc/1110085.htmlTechArticleYII Framework架構教程之緩衝用法詳解,yiiframework 本文執行個體講述了YII Framework架構緩衝用法。分享給大家供大家參考,具體如下: 緩衝的產生原...