【问题标题】:Smarty cache site properties in databaseSmarty 在数据库中缓存站点属性
【发布时间】:2011-12-04 14:57:12
【问题描述】:

我将在数据库中构建一个具有动态内容(标题、url 等属性)的站点。我想每次都查询所有内容并分配变量是非常不必要的,所以我已经阅读了有关缓存的内容。

我使用 Smarty 模板,系统。

   include('libs/Smarty/Smarty.class.php');

    $smarty = new Smarty;
    $smarty->setCaching(true);

    if (!$smarty->isCached('index.tpl')) {

    //query here and assign..
    $smarty->assign('title', 'Test');
    }

    $smarty->display('themes/simple/index.tpl');
  1. 上面的代码什么时候重新检查缓存?如果我对我的数据库站点属性进行更改,我希望立即更改我的站点,这可能是非常重要的事情,例如将站点进行维护等。
  2. 我真的需要在每次页面加载时一次又一次地查询所有数据以获取站点信息,还是有任何解决方案,例如使用缓存检查数据库行结构或类似的东西?

解决方案,我需要!


更新: 我尝试了clearCache的方法,但似乎不能正常工作。我更新了数据库,但是“clearCache”方法,好像没有触发,什么的。

$smarty = new Smarty;
$smarty->setCaching(Smarty::CACHING_LIFETIME_CURRENT);

//just to test
$smarty->clearCache('index.tpl');


if (!$smarty->isCached('index.tpl')) {



//do stuff here

【问题讨论】:

  • 好吧,如果您希望用户可以立即使用更改,则根本不应该使用缓存,就是这样 :-)
  • 有没有办法像检查数据库表是否已更改,如果更改,则重新查询所有内容,这样应该可以节省一些时间?还是我弄错了?
  • 必须查询数据库,这是您要避免的。

标签: php caching smarty


【解决方案1】:

当修改数据库中的内容时,通知 Smarty 清除相关缓存 clearCache()。

您还可以根据存储在数据库中的某个时间戳检查缓存的修改时间。

<?php
$smarty = new Smarty();
$tpl = $smarty->createTemplate($template_file, $cache_id);
$databaseLastModified = strtotime("yesterday"); // determine when the database was modified last
if (!$tpl->isCached() || $tpl->cached->timestamp < $databaseLastModified) {
  $tpl->force_cache = true; // in case of timestamp < modified
  // load data for smarty to process
  $tpl->assign('your', 'stuff');
}
$tpl->display();

【讨论】:

  • 好吧,如果您使用 PhpMyAdmin 之类的工具处理数据库,您显然无法清除 Smarty 的缓存。您需要在管理工具中使用 ->clearCache()。
  • 如果您更喜欢使用其他工具来处理数据库,那么您应该添加一列来记录上次更新时间(使用 TRIGGER 非常简单)并尝试上述代码。
  • 这个想法是尝试“clearcache”功能,这样我就可以看到,如果我在 phpmyadmin 中更新,然后更新/刷新页面,缓存已被清除,我的 if 语句被执行
猜你喜欢
  • 1970-01-01
  • 2010-12-27
  • 2016-09-26
  • 1970-01-01
  • 1970-01-01
  • 2010-12-06
  • 2015-06-27
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多