markjaquith / wp-tlc-transients
支持软过期和后台更新transients的WP transient接口。
1.0
2013-05-07 18:12 UTC
This package is auto-updated.
Last update: 2024-09-10 04:25:16 UTC
README
一个支持软过期(使用旧内容直到新内容可用)、后台更新transients(无需等待cron作业)的WordPress transient接口,并提供链式语法,允许使用单行代码。
许可
TLC Transients遵循GPL,版本2.0或任何后续版本。请参阅LICENSE
。
示例
在这个简单的例子中,我们定义了一个feed抓取回调,然后使用tlc_transient
链式调用指向该回调并使用它,所有这些都只在一行中完成。请注意,由于我们没有使用background_only()
,初始加载此页面将暂停。
<?php // Define your callback (other examples use this) function my_callback() { return wp_remote_retrieve_body( wp_remote_get( 'http://example.com/feed.xml', array( 'timeout' => 30 ) ) ); } // Grab that feed echo tlc_transient( 'example-feed' ) ->updates_with( 'my_callback' ) ->expires_in( 300 ) ->get(); ?>
这次,我们在链中设置background_only()
。这意味着如果已经进行了硬缓存刷新,或者这是第一次请求,它将返回false。因此,您的代码必须能够优雅地降级,如果feed尚未可用。这当然会触发后台更新。一旦它可用,它将开始返回内容。
<?php echo tlc_transient( 'example-feed' ) ->updates_with( 'my_callback' ) ->expires_in( 300 ) ->background_only() ->get(); ?>
当然,我们不必链式调用。
<?php $t = tlc_transient( 'example-feed' ); if ( true ) { $t->updates_with( 'my_callback' ); } else { $t->updates_with( 'some_other_callback' ); } $t->expires_in( 300 ); echo $t->get(); ?>
我们甚至可以向我们的回调传递参数。
<?php // Define your callback function my_callback_with_param( $param ) { return str_replace( 'foo', $param, wp_remote_retrieve_body( wp_remote_get( 'http://example.com/feed.xml', array( 'timeout' => 30 ) ) ), ); } // Grab that feed echo tlc_transient( 'example-feed' ) ->updates_with( 'my_callback_with_param', array( 'bar' ) ) ->expires_in( 300 ) ->background_only() ->get(); ?>
注意事项
上下文
需要注意的是,当回调异步运行时,您无法控制上下文。您注册回调时的上下文与回调实际运行时的上下文无关。因此,如果您的回调函数中存在任何假设(无论是当前用户,已查询的特定帖子等),您必须重新编写回调函数,以便这些假设不成立,并且将这些上下文以参数的形式传递,然后您的回调使用这些参数来重新创建所需的上下文。