原帖:http://www.discuz.net/thread-2087076-1-1.html
Discuz! X系列中加入了全新的缓存机制,我们在开发插件或者是增加新的功能的时候可以很方便的为系统增加一个全新的缓存,并在任何页面中使用。
下面以一个 名为 example 的缓存为例,详细说一下这个机制。
新建一个文件:
- <?php
- if(!defined('IN_DISCUZ')) {
- exit('Access Denied');
- }
- function build_cache_example() {
- $data = array();
- $data[] = 'Hello World';
- $data[] = 'Hello Discuz!';
- save_syscache('example', $data);
- }
- ?>
这就是一个标准的生成缓存的文件。其中有几点重要的为:
需要生成名字为 example 的缓存,那么这个文件的名字需要命名为:cache_example.php
文件中的 build_cache_xxxx 类似的这个函数名应为 build_cache_example
save_syscache('xxxx', $data); 应该为 save_syscache('example', $data);
为了安全性,文件头部必须增加
- if(!defined('IN_DISCUZ')) {
- exit('Access Denied');
- }
其中 build_cache_example 函数就是主要的对需要缓存的数据做处理的函数,所有的组织数据,都可以放到这个函数里面执行,或者放到多个小函数,然后统一在这个函数中执行。而且结尾必须要以 save_syscache('example', $data); 结尾,才能写入缓存数据。
现在缓存文件有了,我们可以把 cache_example.php 文件放到 source/function/cache 目录中。这样在的 Discuz! 文件中就可以调用这个缓存了。
更新缓存的方法:
- require_once libfile('function/cache');
- updatecache('example');
调用缓存的方法:
- require_once libfile('function/cache');
- loadcache('example');
执行后,缓存在:$_G['cache']['example'] 变量中;
测试代码:
- require_once libfile('function/cache');
- updatecache('example');
- loadcache('example');
- print_r($_G['cache']['example']);exit;
输出结果:
- Array ( [0] => Hello World [1] => Hello Discuz! )
转载于:https://blog.51cto.com/kelson/1194419