Joomla!-开源天空

2008-10-12
首页 专栏热点 Joomla! 源代码分析 Joomla 如何采用缓存加速你的代码(二)


Joomla 如何采用缓存加速你的代码(二)

E-mail

3. 缓存对象

首先,要确认你在全局配置设置了允许缓存项。

我们可以通过Jfactory取得缓存对象

<?php
$cache = & JFactory::getCache();
?>

如果你想在组件中获得缓存,即使全局配置没有启用,你也可以通过以下代码启用缓存:

<?php
$cache->setCaching( 1 );
?>

接下来调用我们的函数


<?php
$rows = $cache->call( array( 'TestClass', 'testMethod' ) );
?>

如果你要缓存一个不是在类中的函数,可以不必使用数组,就如以下的代码

<?php
$rows  = $cache->call( 'testFunction' );
?>

可以使用以下代码清除缓存

<?php
$cache->cleanCache();
?>

这将删除缓存目录中的所有缓存的文件和目录。

4. 整合

为了比较,我们将调用两次,一次缓存,一次不缓存,并且我们把两次调用包含在一个profiler中,从而我们可以看清不同。


<?php

class TestClass {

    function testMethod() {

        $db = & JFactory::getDBO();
        for( $i=0; $i<250; $i++) {
            $db->setQuery( 'SELECT * FROM #__content' );
            $rows = $db->loadObjectList();
        }

        return $rows;
    }
}

$cache = & JFactory::getCache();

$profiler = new JProfiler();
$rows = TestClass::testMethod();
echo $profiler->mark( ' without caching' );


$profiler = new JProfiler();
$rows  = $cache->call( array( 'TestClass', 'testMethod' ) );
echo $profiler->mark( ' with caching' );

?>

现在执行 index.php?option=com_testcache. 结果如下:

2.093 without caching
2.160 with caching

第二个稍慢,刷新页面,结果如下:

2.073 without caching
0.008 with caching

在设置的缓存期限内,这个结果大体如此。

相关文章:
Joomla相关文章模块的改进--相关文章的插件
Joomla-开源天空的首页恢复
Joomla 缓存应该支持单一页面,或者菜单
开发安全的Joomla组件,插件和模块(九) 怎样获取原始组件的输出
开发安全的Joomla组件,插件和模块(八) 怎样获取原始组件的输出
开发安全的Joomla组件,插件和模块(七) 检查用户权限
开发安全的Joomla组件,插件和模块(三) 防止远程文件包含
开发安全的Joomla组件,插件和模块(二) 防止直接访问
开发安全的Joomla组件,插件和模块(一) 序言
Joomla 怎样判断用户在访问首页


收藏此文章:
Digg! Reddit! Del.icio.us! JoomlaVote! Google! Live! Facebook! StumbleUpon! Yahoo! Free social bookmarking plugins and extensions for Joomla! websites!
User Reviews(3)
 回复:[文章评论]--Joomla 如何采用缓存加速你的代码(二)
作者:一笑而过 星期二, 26 二月 2008 18:49
谢谢!
 更正:原文中cleanCache()错误
作者:admin 星期二, 26 二月 2008 18:04
Joomla! 1.5正式版中应该是:$cache->clean()吧!
以下是我修改后代码:
function testMethod() {

$db = & JFactory::getDBO();
for( $i=0; $isetQuery( 'SELECT * FROM #__content' );
$rows = $db->loadObjectList();
}

return $rows;
}

$cache = & JFactory::getCache();
$cache->setCaching( 1 );

$profiler = new JProfiler();
$rows = testMethod();
echo $profiler->mark( ' without caching' );


$profiler = new JProfiler();
$rows = $cache->call('testMethod');
echo $profiler->mark( ' with caching' );

$cache->clean();
要加上:
jimport( 'joomla.utilities.profiler');
这段啊!
 更正
作者:df 星期五, 14 三月 2008 21:03
loadObjectList();
}

return $rows;
}
}

$cache = & JFactory::getCache();
$cache->setCaching( 2 );

$profiler = new JProfiler();
$rows = TestClass::testMethod();
echo $profiler->mark( ' without caching' ).'';


$profiler = new JProfiler();
$rows = $cache->call( array( 'TestClass', 'testMethod' ) );
echo $profiler->mark( ' with caching' );
$cache->clean();
?>

发表您的文章评论

您的姓名 (昵称)
标题:
评分: 很差一般较好很好
评论:
验证码:
请输入验证码