`
天梯梦
  • 浏览: 13730751 次
  • 性别: Icon_minigender_2
  • 来自: 洛杉矶
社区版块
存档分类
最新评论

利用 Cache_Lite代替codeigniter中的cache功能

阅读更多

codeigniter的功能纵然强大,也有不足之处。其cache模式在于针对不同的uri就会生成cache文件,如果URL中参数不同,则 cache文件就会不同,从而产生了漏洞。如果访问者构建自动生成URI,不断向服务器发起请求,就会瞬间产生大量的垃圾文件,导致系统文件臃肿。

 

参看CI中国论坛:脆弱的CI缓存系统,1天攻陷你的CI网站http://codeigniter.org.cn/forums/thread- 1690-1-1.html

 

因此如果要用到cache功能就必须找到第三方的开发库。Pear中,Cache_Lite属于较为轻量级的缓存系统,且功能强大,可以作为CI原 生cache的替代品,将其加入自定义的library文件即可完成。

 

步骤如下:

 

1. 下载Cache_Lite

 

http://download.pear.php.net/package/Cache_Lite-1.7.7.tgz

 

解压缩后,将Cache_Lite.php和Lite文件夹复制到 system/application/libraries中。并在Cache_Lite.php中加入:if (!defined(’BASEPATH’)) exit(’No direct script access allowed’);
 

2. 在要使用Cache_Lite的Controller中,加入:

 

 $ops = array(
‘cacheDir’ => BASEPATH.’/cache/’, //cache文件存储位置
‘lifeTime’ => 3600, //cache的有效期
);
// ;

$this->load->library(”Cache_Lite”,$ops,”cc”); //cc为Cache_Lite的别名, 然后在要利用Cache的位置使用Cache_Lite自带的函数就可以拉。
 

如:读取缓存:$string = $this->cc->get($id);
生成缓存:$this->cc->save($outputString);

 

推荐一个更好的CI缓存类:MP_Cache

首先,在config.php中设置一下缓存目录,这个目录要存在且可写入

 

 $config['mp_cache_dir'] = 'application/mp_cache/';

 

现在看看代码

 

/*加载library,可以放在构造函数中*/
$this->load->library('MP_Cache');
/*抓取名为listNews的缓存*/
$listNews = $this->mp_cache->get('listNews');
if($listNews===false){
    //没有缓存数据,则查询数据库
     $listNews = $this->News_model->getNewslist('guest')->result();
     //创建缓存,命名为listNews。在mp_cache目录下就生成了listNews.cache文件,内容是序列化的数据
     $this->mp_cache->write($listNews, 'listNews');
}
$data['listNews']= $listNews;
$this->layout->view('news', $data);
 

两个注意点:
1,缓存数据,必须是data,而不是resource id。如,在使用AR后用result(),result_array()等返回的数据
2,缓存名不要重复。可以使用子文件夹分隔。如,$listNews = $this->mp_cache->get(‘news/listNews’);同样创建缓存数据片段 用$this->mp_cache->write($listNews, ‘news/listNews’);(php5下news文件夹会自动创建)
其他方法:

 

$this->mp_cache->delete($filename)
 

删除名为$filename的cache.

 

 $this->mp_cache->delete_all($dirname)
 

删除 $dirname目录及其下所有缓存.如果$dirname没有设置,则删除所有缓存.

 


http://mpsimple.mijnpraktijk.com/mp_cache/user_guide.htm

 

MP_Cache was written as a more flexible caching solution than those offered by CodeIgniter. As such it offers you a way to cache anything from a single variable, to a SQL query or the fully generated page. MP_Cache saves these entries serialized to files and has functions to retrieve and delete these.

Additionally you can set expiration time and dependencies to force a main cache to refresh itself after one of its subcaches has been refreshed or deleted.

Installing MP_Cache

  • Download the file here and unzip it to your application/libraries directory.
  • Create a directory for you cache, for example application/mp_cache
  • Add a value 'mp_cache_dir' to an autoloaded config file, for instance application/config/config.php and set it to the mp_cache directory relative to your index.php file.
    For example: $config['mp_cache_dir'] = APPPATH.'mp_cache/';
  • Optional: add a value 'mp_cache_default_expires' to the same autoloaded config file and set it to a default expiration time in seconds if you want it set by default. You can still make something never expire by setting it to 0.
  • That's it, you can start using MP_Cache.

Initializing MP_Cache

Like most other classes in CodeIgniter, the MP_Cache class is initialized in your controller using the

 

$this->load->library function :

 

$this->load->library('MP_Cache');

 

Once the library is loaded it will be ready for use. The MP_Cache library object you will use to call all functions is: $this->mp_cache .

Basic caching without additional settings

To just cache something within your controller or model, the usage is like this:

 

$data = $this->mp_cache->get('example');
if ($data === false)
{
    // example model-function that generates your $data variable

    $data = $this->Pages->read($page);
    
    $this->mp_cache->write($data, 'example');
}
 

The variable to be cached can be of any kind, though object-references will be lost when loaded from cache.

Alternative syntax for the example above

You can also use the cache in a more object oriented way. In this case you always call the set_name() method before any other because it will reset the object to its default state.

 

$data = $this->mp_cache->set_name('example')->get();

if ($data === false)
{
     // example model-function that generates your $data variable

    $data = $this->Pages->read($page);
    
    $this->mp_cache->set_contents($data)->write();
}
 

Warning: You can't combine the syntaxes, using the parameterized versions of write() and get() will reset the mp_cache object to prevent contamination of your current cache operation from a previous one.

Using subdirectories

For PHP5 subdirectories with virtual unlimited depth are supported, PHP4 only supports 1 level. You can set subdirectories by simply adding them in the cache name. The first line of the alternative syntax example is below in the directory "directory " which in turn is in the directory "sub ".

 

$data = $this->mp_cache->set_name('sub/directory/example')->get();
 

Adding an expiration time

Expiration time is added when writing the cache. Exparation is set to NULL by default which means using the default expiration, you can set it to 0 for no experation (if the default is set to something larger than 0). If you want it to expire after a certain time you have to specify it in seconds after it was generated. To do so you have to change the write function like this when using the write() function with parameters:

 

// Cache it for 2 hours (7200 seconds = 60 seconds * 60 minutes * 2 hours)

$this->mp_cache->write($data, 'example', 7200);

 

Or do it by using the set_expires() function:

 

$this->mp_cache->set_name('example')->set_contents($data)->set_expires(7200)->write();
 

Adding dependencies

You can add cache file on which the expiration of the current cache file is dependend. When one of those files has been deleted or refreshed after the current cache was made, the current cache will be deleted. So lets say we have a menu called mainmenu which we have cached in a subdirectory called menus . Using the parameterized write() function you can add the dependency like this (expiration set to none):

 

$this->mp_cache->write($data, 'example', null, array('menus/mainmenu'));
 

Or using the set_dependencies() function (which takes an array or a string):

 

 

$this->mp_cache->set_name('example')->set_contents($data)->set_dependencies('menus/mainmenu')->write();
 

Deleting individual caches

You can delete cache by using the delete() function:

 

$this->mp_cache->delete('example');
 

Or in the alternative way:

 

 

$this->mp_cache->set_name('example')->delete();
 

Deleting the entire cache or subdirectories of it

To delete the entire cache you can use the delete_all() function:

 

 

$this->mp_cache->delete_all();
 

Or you can delete a subdirectory of the main cache, like all the menus from the example for dependencies:

 

$this->mp_cache->delete_all('menus');
 

This will delete all the files in the subdirectory menus of the main cache. All the subdirectories of the menus directory and files within them will also be deleted.

Full functions overview

reset()

Resets the current state of the mp_cache object. It is called automatically from the set_name() function or when the write() & get() functions are used with parameters. This is done to prevent any previous usage of the mp_cache object from contaminating your current usage with settings you would expect to be the default ones.

 

$this->mp_cache->reset();
 

set_name() & get_name()

Sets or returns the full filename of the cache.
Warning: the set_name() function automatically calls reset(), so always use it as the first function when using the alternative syntax.

 

$this->mp_cache->set_name('example');
// after this is set the variable below will be set to the string 'example'

$var = $this->mp_cache->get_name();
 

set_contents() & get_contents()

Sets or returns the contents you are caching or retrieving.

 

$this->mp_cache->set_contents(array(1,2,3,4,5));
// The function below will return the array set above

$array = $this->mp_cache->get_contents();
 

set_dependencies(), add_dependencies() & get_dependencies()

Sets the dependencies, adds to the current dependencies or returns the set dependencies.

 

$this->mp_cache->set_dependencies('example');
// this sets the dependencies to the 'example' cache file

$this->mp_cache->set_dependencies(array('cachefile1', 'cachefile2'));
// this has overwritten the first statement and set the dependencies to 'cachefile1' & 'cachefile2'

$this->mp_cache->add_dependencies('example')
// this has added 'example' as a dependency in addition to 'cachefile1' & 'cachefile2'
 

 

All functions take both strings and arrays of strings.

set_expires() & get_expires()

Sets the expiration time and retrieves the time on which the cache will expire.

 

 

$this->mp_cache->set_expires(7200);
// sets the expiration to a timestamp 2 hours from now

$expires = $this->mp_cache->get_expires();
// $expires is set to the timestamp 2 hours from now as defined by set_expires()
 

get_created()

Returns the timestamp from the moment the retrieved cache was created, returns NULL when used while writing cache.

 

$created_on = $this->mp_cache->get_created();
 

 

分享到:
评论

相关推荐

    MP_Cache用户指南(中英文对译版)

    MP_Cache 是一个针对 CodeIgniter 框架设计的高级缓存解决方案,它提供了比 CodeIgniter 内置缓存机制更为灵活的功能。MP_Cache 的主要目标是帮助开发者更高效地存储和管理各种类型的数据,从简单的单个变量到复杂的...

    dx_auth codeigniter权限控制库

    DX_AUTH是专为CodeIgniter框架设计的一个强大的权限控制库,它提供了细粒度的访问控制功能,使得开发者能够轻松管理用户角色、权限以及访问规则。CodeIgniter是一款流行的PHP框架,以其轻量级、高效性和易用性而受到...

    jqgrid_codeigniter_library

    总之,`jqgrid_codeigniter_library`是将`jqGrid`的强大功能与CodeIgniter的MVC架构相结合的工具,便于开发高效、功能丰富的数据管理界面。通过理解和掌握上述知识点,开发者能够更好地利用这个库来提升Web应用的...

    telegram_bot_message_with_php_codeigniter:从php codeigniter发送Bot消息到电报

    步骤1 :在电报中搜索“僵尸”并输入 第2步:发送消息“ / newbot” 步骤3 :因此,它将询问机器人名称,然后输入机器人名称(例如:“ telegram_bot_message”),然后询问机器人的用户名,并应以_bot结尾,例如...

    sist_ord_servi_vend_Codeigniter:Codeigniter的Criando sistema de ordemserviçoe vendas com-udemy 2020

    发布信息此存储库包含将来版本的开发中代码。 要下载最新的稳定版本,请访问页面。变更日志和新功能您可以在 找到每个版本的所有更改的列表。服务器要求建议使用PHP 5.6或更高版本。 它也应该在5.3.7上运行,但是...

    ciswoole:带有 Swoole_Http_Server 的 CodeIgniter 2.2

    带有 Swoole Http_Server 的 CodeIgniter 2.2 要求 PHP 5.3+ Swoole 1.7.16 Linux、OS X 和基本的 Windows 支持(认为 cygwin) 安装 Swoole 通过pecl安装 pecl install swoole 从源安装 sudo apt-get install ...

    CI_HMVC_LoReg:Codeigniter HMVC登录注册系统

    在 Codeigniter 2.1 中设置 HMVC 这假设您已经安装了 Codeigniter 2.1.x 在下载 codeigniter-modular-extensions-hmvc。 解压存档将所有文件从提取的存档核心目录移动到 Codeigniter 实例的 /application/core 目录...

    Codeigniter-breadcrumbs, 用于CodeIgniter的小breadcrumb库.zip

    Codeigniter-breadcrumbs, 用于CodeIgniter的小breadcrumb库 Breadcrumbs是一个小型库,它帮助你使用CodeIgniter管理HTML面包屑。 * 不再维护 Instalation将 Breadcrumbs.php 放在应用程序/库文件夹中将 Breadcrumbs...

    carrito_code:CodeIgniter 中的购物车

    在CodeIgniter中,购物车通常通过使用内置的Session库来实现。Session库允许开发者存储用户数据,如添加到购物车的商品,即使在页面之间跳转也能保持这些信息。在"carrito_code"项目中,我们可能会看到如何创建类和...

    Admin_Manager:Codeigniter管理员经理

    在"Admin_Manager"项目中,Codeigniter作为基础架构,提供了路由、模型-视图-控制器(MVC)架构、数据库交互等功能,使得开发者可以更专注于业务逻辑而不是底层细节。 其次,admin LTE2是一款基于Bootstrap的开源...

    CI3_Plugin_System:CodeIgniter 3的插件系统

    稍后我会在自述文件中添加更多信息,但现在,只需将其放入到帮助器/模型/库中,将表导入.sql文件,然后在application / controllers / Plugins.php中查找一些信息,并查看plugins / hello_world / hello_world.php中...

    ci_product_fuzzy_search:CodeIgniter 产品模糊搜索

    CodeIgniter 产品模糊搜索需要 CodeIgniter 2.2.0(未在其他版本上测试)使用说明要快速试用,请按照以下步骤操作: 在 CI 连接的数据库上执行 product.sql 以创建 Product 表在表中加载一些示例产品数据将存储库中...

    CodeIgniter简体中文语言包

    CodeIgniter是一个轻量级、高性能的PHP框架,它被广泛用于快速开发高效、优雅的Web应用程序。...通过合理利用这个语言包,你可以更好地发挥CodeIgniter的潜力,开发出更加符合中文用户需求的Web应用。

    mult_db_codeigniter

    Codeigniter 2.2.2 HMVC具有站点和单个配置的HMVC多个站点在同一布局中 有时我们有一个项目,我们希望有多个具有相同接口的客户端,但是具有单独的数据库和配置。 在此示例中,我表明可以使用Codeigniter Framework...

    ci_shop:使用codeigniter的在线商店

    组件(模型,控制器和视图)排列在应用程序子目录中。 我发现HMVC模式比MVC模式有几个好处,尤其是: 减少应用程序不同部分之间的依赖关系。 组织化,每个相关三合会都有一个文件夹,可以减轻工作量。 阅读有关...

    ConnectWise_PHP:CodeIgniter库和用于与ConnectWise API接口的常规PHP类

    在这里,我有几个PHP库,一个用于CodeIgniter,另一个是常规PHP类。 CI_Library-... 两者的工作原理非常相似,请在您感兴趣的目录中查看相应的README.md。 您必须使用带有curl支持PHP编译它们才能正常工作。

    codeigniter中文手册教程

    这个“codeigniter中文手册教程”是你个人制作并基于官网资料改编的,旨在为开发者提供更便捷的学习途径。在解压文件后,只需通过浏览器打开`index.html`,你就可以开始学习CodeIgniter的相关知识。 CodeIgniter的...

    codeigniter3_hmvc_ion_auth:带有 HMVC 和 Ion_Auth 的 CodeIgniter 3.0

    带有 HMVC 和 Ion_Auth 的 CodeIgniter 3.0-dev 我的第一个 Github 存储库,我只是将 CI3.0-dev 与 Wiredesignz HMVC 模块和 Ion_Auth 结合起来。 还包括一个模板模块。 文档将很快提供。 同时,此处提供有关 HMVC ...

Global site tag (gtag.js) - Google Analytics