我是小站长 發表於 2019-6-3 10:56:56

Discuz! X系列,缓存扩展机制说明

<br /><br /><font face="Tahoma, &amp;quot;">Discuz! X系列中加入了全新的缓存机制,我们在开发插件或者是增加新的功能的时候可以很方便的为系统增加一个全新的缓存,并在任何页面中使用。</font><br /><font face="Tahoma, &amp;quot;">下面以一个 名为 example 的缓存为例,详细说一下这个机制。</font><br /><br /><font face="Tahoma, &amp;quot;">新建一个文件:</font><ol><li>&lt;?php<br /><li>if(!defined('IN_DISCUZ')) {<br /><li>&nbsp; &nbsp;&nbsp; &nbsp;&nbsp;&nbsp;exit('Access Denied');<br /><li>}<br /><li><br /><li>function build_cache_example() {<br /><li>&nbsp; &nbsp;&nbsp; &nbsp;&nbsp;&nbsp;$data = array();<br /><li>&nbsp; &nbsp; $data[] = 'Hello World';<br /><li>&nbsp; &nbsp; $data[] = 'Hello Discuz!';<br /><li>&nbsp; &nbsp;&nbsp; &nbsp;&nbsp;&nbsp;save_syscache('example', $data);<br /><li>}<br /><li><br /><li>?&gt;</ol><font face="Tahoma, &amp;quot;">这就是一个标准的生成缓存的文件。其中有几点重要的为:</font><br /><ul type="1" class="litype_1"><li>需要生成名字为 example 的缓存,那么这个文件的名字需要命名为:cache_example.php<li>文件中的 build_cache_xxxx 类似的这个函数名应为 build_cache_example<li>save_syscache('xxxx', $data);&nbsp;&nbsp;应该为&nbsp;&nbsp;save_syscache('example', $data);<li><font color="DarkOrange">为了安全性,文件头部必须增加</font><ol><li>if(!defined('IN_DISCUZ')) {<br /><li>&nbsp; &nbsp;&nbsp; &nbsp;&nbsp;&nbsp;exit('Access Denied');<br /><li>}</ol><br /></ul>其中 build_cache_example 函数就是主要的对需要缓存的数据做处理的函数,所有的组织数据,都可以放到这个函数里面执行,或者放到多个小函数,然后统一在这个函数中执行。而且结尾必须要以&nbsp;&nbsp;save_syscache('example', $data); 结尾,才能写入缓存数据。<br /><br />现在缓存文件有了,我们可以把 cache_example.php 文件放到 source/function/cache 目录中。这样在的 Discuz! 文件中就可以调用这个缓存了。<br />更新缓存的方法:<ol><li>require_once libfile('function/cache');<br /><li>updatecache('example');</ol><font face="Tahoma, &amp;quot;">调用缓存的方法:</font><br /><ol><li>require_once libfile('function/cache');<br /><li>loadcache('example');</ol><font face="Tahoma, &amp;quot;">执行后,缓存在:$_G['cache']['example']&nbsp;&nbsp;变量中;</font><br /><font face="Tahoma, &amp;quot;">测试代码:</font><br /><ol><li>require_once libfile('function/cache');<br /><li>updatecache('example');<br /><li>loadcache('example');<br /><li>print_r($_G['cache']['example']);exit;</ol><font face="Tahoma, &amp;quot;">输出结果:</font><br /><ol><li>Array ( =&gt; Hello World =&gt; Hello Discuz! )</ol><font face="Tahoma, &amp;quot;">请大家在开发插件或者增加功能的时候,为了自己和别人网站的稳定,为每个结果量很大的查询结果增加缓存~~</font><br />缓存<em>, </em>Tahoma<em>, </em>quot<em>, </em>增加

耗子 發表於 2019-6-7 22:49:42

感谢分享!
頁: [1]
查看完整版本: Discuz! X系列,缓存扩展机制说明