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');

由原来的两层结构,中间又加一层封装,变成三层,提高了代码的重用性、扩展性和可维护性。这正是我们写程序时应该追求的。

你可能感兴趣的:(数据结构,PHP,cache,wordpress,UP)