CodeIgniter(CI)缓存分析

本文深入探讨了CodeIgniter中的缓存机制,包括如何启用缓存、配置缓存路径、缓存文件的创建与删除流程,以及缓存系统的内部实现原理。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

codeigniter 中的缓存系统分析

ci中自带了一套自己的缓存系统这套缓存系统

使用方法如下:
只需要在controller或是model之中打开model中打开即可 
$this->output->cache( 3 );//缓存时间为3分钟

关于cache的配置项
位于config/config.php文件中
$config[ 'cache_path' ] = '';//设置文件路径

从CodeIgniter.php文件里可以看出缓存的使用过程

首先进入这里

/*
   文件:CodeIgniter.php
 * ------------------------------------------------------
 *  Instantiate the output class
 * ------------------------------------------------------
 */

$OUT =& load_class('Output', 'core');

/*
 * ------------------------------------------------------
 *	Is there a valid cache file?  If so, we're done...
 * ------------------------------------------------------
 */

if( $EXT->_call_hook( 'cache_override' ) === FALSE )
{
	if ($OUT->_display_cache($CFG, $URI) == TRUE)//使用缓存文件或是删除过期文件
	{
		exit;
	}
}


/**
 * Output.php
 * Update/serve a cached file
 * 使用缓存文件 删除过期的文件
 * @access	public
 * @param 	object	config class
 * @param 	object	uri class
 * @return	void
 */
function _display_cache(&$CFG, &$URI)
{
	$cache_path = ($CFG->item('cache_path') == '') ? APPPATH.'cache/' : $CFG->item('cache_path');
	// Build the file path.  The file name is an MD5 hash of the full URI
	$uri =	$CFG->item('base_url').
	$CFG->item('index_page').
	$URI->uri_string;
	$filepath = $cache_path.md5($uri);
	if ( ! @file_exists($filepath))
	{
		return FALSE;
	}
	if ( ! $fp = @fopen($filepath, FOPEN_READ))
	{
		return FALSE;
	}
	flock($fp, LOCK_SH);
	$cache = '';
	if(filesize($filepath) > 0)
	{
		$cache = fread($fp, filesize($filepath));
	}
	flock($fp, LOCK_UN);
	fclose($fp);
	// Strip out the embedded timestamp
	if ( ! preg_match("/(\d+TS--->)/", $cache, $match))
	{
		return FALSE;
	}
	// Has the file expired? If so we'll delete it.
	if(time() >= trim(str_replace('TS--->', '', $match['1'])))
	{
		if (is_really_writable($cache_path))
		{
			@unlink($filepath);
			log_message('debug', "Cache file has expired. File deleted");
			return FALSE;
		}
	}

	// Display the cache
	$this->_display(str_replace($match['0'], '', $cache));
	log_message('debug', "Cache file is current. Sending it to browser.");
	return TRUE;//

}
以下代码显示输出(在未使用cache文件或cache文件过期情况下)

/* CodeIgniter.php
 * ------------------------------------------------------
 *  Send the final rendered output to the browser
 * ------------------------------------------------------
 */

if ($EXT->_call_hook('display_override') === FALSE)
{
	$OUT->_display();
}

若存在$this->output->cache( n ); //n > 0;

/**
		 *  Output.php
 * Set Cache
 *
 * @access	public
 * @param	integer
 * @return	void
 */
function cache($time)
{
	$this->cache_expiration = ( ! is_numeric($time)) ? 0 : $time;

	return $this;
}

	  如果设置了缓存时间则需要写cache文件

//Output.php

// Do we need to write a cache file?  Only if the controller does not have its
// own _output() method and we are not dealing with a cache file, which we
// can determine by the existence of the $CI object above
if ($this->cache_expiration > 0 && isset($CI) && ! method_exists($CI, '_output'))
{
	$this->_write_cache($output);
}

//Output.php
function _write_cache($output)
{//写缓存文件
	$CI =& get_instance();
	$path = $CI->config->item('cache_path');
	$cache_path = ($path == '') ? APPPATH.'cache/' : $path;
	if ( ! is_dir($cache_path) OR ! is_really_writable($cache_path))
	{
		log_message('error', "Unable to write cache file: ".$cache_path);
		return;
	}
	$uri =	$CI->config->item('base_url').
	$CI->config->item('index_page').
	$CI->uri->uri_string();
	$cache_path .= md5($uri);
	if ( ! $fp = @fopen($cache_path, FOPEN_WRITE_CREATE_DESTRUCTIVE))
	{
		log_message('error', "Unable to write cache file: ".$cache_path);
		return;
	}
	$expire = time() + ($this->cache_expiration * 60);
	if (flock($fp, LOCK_EX))
	{
		fwrite($fp, $expire.'TS--->'.$output);//写缓存文件
		flock($fp, LOCK_UN);
	}
	else
	{
		log_message('error', "Unable to secure a file lock for file at: ".$cache_path);
		return;
	}
	fclose($fp);
	@chmod($cache_path, FILE_WRITE_MODE);
	log_message('debug', "Cache file written: ".$cache_path);
}


### 实现 CodeIgniter 4 中的缓存功能 在 CodeIgniter 4 (CI4) 中,缓存机制被设计得非常灵活且易于使用。框架提供了多种方式来处理不同类型的缓存需求。 #### 缓存驱动程序支持 CodeIgniter 支持多个缓存存储选项,包括文件系统、APC、Memcached 和 Redis 等[^1]。开发者可以根据具体的应用场景选择最适合的一种或几种组合使用。 #### 配置缓存设置 要启用并配置缓存,在 `app/Config/Cache.php` 文件内定义所需的参数: ```php public $handler = 'file'; // 可选值有 file, apc, memcached 或者 redis public $backupHandler = null; public $storePrefix = ''; ``` 对于 Memcached 或 Redis 这样的分布式内存对象缓存系统,则需进一步指定服务器连接详情: ```php public $memcached = [ ['hostname' => 'localhost', 'port' => 11211, 'weight' => 1], ]; public $redis = [ 'socket_type' => 'tcp', 'host' => 'localhost', 'password' => '', 'port' => 6379, 'timeout' => 0, ]; ``` #### 使用 Cache 类操作数据 通过加载 Cache 库可以方便地执行保存、获取以及删除缓存项的操作: ```php $cache = \Config\Services::cache(); // 设置缓存条目,默认有效期为五分钟 $cache->save('my_key', 'value_to_cache', 300); // 获取特定键对应的缓存内容 $cachedValue = $cache->get('my_key'); if ($cachedValue === false){ echo "Cache miss"; } else { echo "Cached value found!"; } // 清除单个缓存项目 $cache->delete('my_key'); ``` 此外还存在一些辅助方法用于批量清除缓存或是检查某个给定名称是否存在有效期内的数据副本。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值