什么时候使用瞬态,什么时候不?

时间:2012-03-07 08:19:14

标签: php sql wordpress transient

我正在使用Wordpress并为其开发了一些特定于站点的插件,另外我的主题是根据后端插件的要求定制的。

最后几天,我在Wordpress中摆弄了瞬态。在一些教程中,他们说“如果您使用的是自定义查询,并且其结果是可缓存的:使用瞬态”。听起来不错,但我想知道何时使用瞬态来获得真正的优势。 我的意思是,即使使用瞬态,在后台必须至少有两个查询,不是吗?第一个用于检查有效性,第二个用于检测瞬态。

使用瞬态即自定义WP_Query是否真的有用? 非常感谢您的帮助和想法。

1 个答案:

答案 0 :(得分:3)

似乎相当简单。它是一个文字类助手,允许您以“memcache”类型的方式存储对象。您首先设置瞬态

function do_something_here($callback_param = 'value'){
  $key = 'do_something_' . $callback_param;//set the name of our transient equal to the value of the callback param being passed in the function.
  $my_query = get_transient($myKey);  //if we've stored this request before, then use it.
  if($my_query !=== false){
    //we found a previous existing version of this query. let's use it.
    return $my_query;
  }else{
    //it doesn't exist, we need to build the transient.
    //do our database querying here, global $wpdb; etc
    //We are going to pretend our returned variable is 'george'
    $value = george;
    $length = 60*60*24; //how long do we want the transient to exist? 1 day here.
    set_transient($key, $value, $length);
    return $value;
  }
}

现在我们已经创建了触发器并将其绑定到'$ key'的名称,我们可以使用key隐含的确切值(我们之前声明的)随时访问它。

echo 'I wanted to do something, so : ' . do_something('value') . ' is what i did! ';

通过使用此格式,您可以在“缓存”中保存查询,并使用它们生成您的回复。这与在MySql中使用“触发器”事件的方式类似。事实上,这是一种技术的部分,通常被称为长轮询。