wordpress緩存類WP_Object_Cache分析【續三】


/**
* 顯示緩存狀態
*
* 顯示緩存取值成功、失敗的次數和所有的緩存分組及組下的數據
*
*/
function stats() {
echo "<p>";
echo "<strong>Cache Hits:</strong> {$this->cache_hits}<br />";
echo "<strong>Cache Misses:</strong> {$this->cache_misses}<br />";
echo "</p>";

foreach ($this->cache as $group => $cache) {
echo "<p>";
echo "<strong>Group:</strong> $group<br />";
echo "<strong>Cache:</strong>";
echo "<pre>";
print_r($cache);
echo "</pre>";
}
}

/**
* PHP4風格的構造函數; 調用PHP 5風格的構造函數

* @返回值 WP_Object_Cache
*/
function WP_Object_Cache() {
return $this->__construct();
}

/**
* Sets up object properties; PHP 5 style constructor
*
* @since 2.0.8
* @返回值 null|WP_Object_Cache If cache is disabled, returns null.
*/
function __construct() {
/**
* @todo This should be moved to the PHP4 style constructor, PHP5
* already calls __destruct()
*/
//註冊一個結束時的回調函數
register_shutdown_function(array(&$this, "__destruct"));
}

/**
* 析構函數 *
* Called upon object destruction, which should be when PHP ends
*
* @返回值 bool True value. Won't be used by PHP
*/
function __destruct() {
return true;
}

總體分析,wp的緩存類,實現了數據庫一樣的增刪改查功能。只不過數據是保存在內存裏,而不是數據庫中。

wp中調用緩存對象的方法是並不是直接在代碼中像這樣調用

global $wp_object_cache;

return $wp_object_cache->add($key, $data, $flag, $expire);

而是封裝在一個方法裏:

function wp_cache_add($key, $data, $flag = '', $expire = 0) {
global $wp_object_cache;

return $wp_object_cache->add($key, $data, $flag, $expire);
}

調用的時候,像這樣調用:

wp_cache_add($comment->comment_ID, $comment, 'comment');

由原來的兩層結構,中間又加一層封裝,變成三層,提高了代碼的重用性、擴展性和可維護性。這正是我們寫程序時應該追求的。
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章