techcrunch / wp-async-task
在WordPress中运行长时间运行操作的后台任务
Requires (Dev)
- 10up/wp_mock: dev-master
- phpunit/phpunit: *@stable
This package is not auto-updated.
Last update: 2024-09-21 01:08:17 UTC
README
为TechCrunch.com提供的TechCrunch WP异步任务插件
快速开始
WP Async Task可以作为插件安装,也可以捆绑在其他插件或主题中。类的定义被包装在 class_exists
检查中,因此永远不会存在意外重复定义的风险。只需确保以某种方式包含插件文件即可。
接下来,您需要扩展该类以实现自己的实现。扩展 WP_Async_Task
类的实现会在任意动作上操作(例如,'save_post'
等)。任何扩展 WP_Async_Task
的类都必须包含以下三个部分
- 受保护的
$action
属性 - 受保护的
prepare_data()
方法 - 受保护的
run_action()
方法
<?php class JPB_Async_Task extends WP_Async_Task { protected $action = 'save_post'; /** * Prepare data for the asynchronous request * * @throws Exception If for any reason the request should not happen * * @param array $data An array of data sent to the hook * * @return array */ protected function prepare_data( $data ) {} /** * Run the async task action */ protected function run_action() {} }
$action
受保护的 $action
属性应设置为要附加异步任务的动作。例如,如果您想在保存帖子时启动异步任务,请将其设置为 save_post
。
prepare_data( $data )
使用此方法来准备动作数据,以便在异步过程中使用。数据将以索引数组的形式提供给 prepare_data()
,就像使用 func_get_args()
获取函数参数一样。此方法需要返回一个包含数据的更有用格式的数组。由于这些值将发送在 POST
请求中,因此建议大部分使用标量值。例如,在 'save_post'
中,动作提供了 $post_id
和 $post
对象,因此我们可能做这样
protected function prepare_data($data){ $post_id = $data[0]; return array( 'post_id' => $post_id ); }
如果出于任何原因需要取消异步任务,您需要抛出异常
protected function prepare_data($data){ $post_id = $data[0]; $post = $data[1]; if( 'post' !== $post->post_type ) { throw new Exception( 'We only want async tasks for posts' ); } return array( 'post_id' => $post_id ); }
库将处理捕获异常,并在捕获异常时防止请求运行。
run_action()
此方法负责运行应触发需要在异步请求内部运行的函数的动作。惯例是使用 "wp_async_$this->action"
,但这取决于实现。
protected function run_action() { $post_id = $_POST['post_id']; $post = get_post( $post_id ); if ( $post ) { // Assuming $this->action is 'save_post' do_action( "wp_async_$this->action", $post->ID, $post ); } }
确保只实例化一次异步任务。这最早应该在 'plugins_loaded'
动作中完成。
最后,更新任何您希望移动到异步任务的作业的动作。
例如,您可能需要将此
add_action( 'save_post', 'really_slow_process', 10, 2 );
更改为此
add_action( 'wp_async_save_post', 'really_slow_process', 10, 2 );
贡献
要贡献,请从github仓库分叉并提交一个pull请求。
在提交pull请求时,请确保您的更改不会导致任何单元测试失败。要运行单元测试套件,请确保您已安装了composer并运行以下命令安装测试工具:
composer install
安装开发工具后,通过运行以下命令来运行单元测试:
vendor/bin/phpunit
版权
© TechCrunch 2014
许可
此库根据MIT许可证授权。有关更多详细信息,请参阅LICENSE.md。