10up/async-transients

当内容过期后异步重新生成,同时在等待过程中提供过时内容

安装: 9,551

依赖项: 0

建议者: 0

安全: 0

星标: 124

关注者: 14

分支: 10

开放问题: 4

类型:wordpress-library

1.0.0 2018-01-09 15:53 UTC

This package is auto-updated.

Last update: 2024-09-12 20:34:11 UTC


README

在后台重新生成新过时数据的同时,提供过时数据的transients。

Support Level Release Version MIT License

背景与目的

transients非常适合存储难以重新生成的数据,但一旦transient过期,我们仍然需要同步重新生成这些数据。这个库通过在transient过期后提供过时数据,并在请求完成后处理重新生成回调,从而解决了这个问题,这样最终用户就永远不会看到重新生成transient的影响。

要求

需要支持fastcgi_finish_request,否则transients将立即重新生成过期数据。

安装

这个库旨在与composer一起使用。要安装,请运行composer require 10up/async-transients。库已设置为使用composer的自动加载器,所以请确保您正在加载您的vendor/autoload.php文件。

用法

用法类似于标准的WordPress transient函数,您提供transient密钥和过期时间,但不同之处在于您还必须提供回调函数,以及传递给回调函数的任何(可选)参数,该回调函数将在transient过期时被调用以重新生成transient数据。

示例用法

// Function to regenerate expired transient
function get_data_from_api( $user_id ) {
	// Fake function, that we assume is really time consuming to run
	$my_result = get_api_data_for_user( $user_id );

	\TenUp\AsyncTransients\set_async_transient( 'transient-key-' . $user_id, $my_result, MINUTE_IN_SECONDS );
}

// This would very likely not be hardcoded...
$user_id = 1;

// If the transient is expired get_data_from_api() is called, with $user_id as a parameter
$transient_value = \TenUp\AsyncTransients\get_async_transient( 'transient-key-' . $user_id, 'get_data_from_api', array( $user_id ) );

// Outputs the value stored in the transient
// If the transient is expired, it will still show the last known data, while queueing the transient to be updated behind the scenes.
var_dump( $transient_value );

这一切是如何工作的?

首先,在调用get_async_transient时,您现在必须传递一个回调函数,以及可选地传递任何传递给回调函数的参数。然后检索transient,就像WordPress核心会检索它一样,但有一个关键的区别。如果transient已过期,我们不会返回任何内容,而是返回最后已知值,并将回调函数和参数添加到队列中,稍后处理。到请求结束时,我们有一个队列,其中包含所有已访问的transient的回调函数,这些transient具有过时数据。

接下来,我们挂钩到WordPress的shutdown操作。该操作在PHP关闭执行之前运行。Transient类挂钩到该操作,并调用fastcgi_finish_request函数(如果可用)。该函数将所有响应数据刷新到客户端,从浏览器的角度来看,请求已经完成,然而,PHP仍然可以在后台继续运行。

在此阶段,我们遍历队列中的所有回调函数,然后重新生成所有已访问但过期的transient数据。

问题

如果您发现任何错误或有任何改进插件的想法,请打开问题。我们非常期待看到社区对这个项目的看法,我们很高兴看到您的反馈!

支持级别

稳定: 10up不打算为这个库开发任何新功能,但仍然会回应错误报告和安全问题。我们欢迎PRs,但任何包含新功能的人都应该是小的、易于整合的,并且不应包含破坏性更改。我们打算保持库与WordPress最新版本兼容。

喜欢你所看到的吗?