工作流模板
工作流模板可让你一次定义工作流的步骤结构,然后按名称多次分派。当同一个多步骤流程需要使用不同负载运行时,这种方式很有用。
定义模板
使用 Queuety::define_workflow() 构建模板,然后注册:
PHP
use Queuety\Queuety;
use Queuety\Enums\Priority;
$builder = Queuety::define_workflow( 'onboarding' )
->on_queue( 'pipelines' )
->with_priority( Priority::Normal )
->max_attempts( 5 )
->then( CreateAccountHandler::class )
->then( SendWelcomeEmailHandler::class )
->then( NotifyAdminHandler::class );
Queuety::register_workflow_template( $builder );
尽早注册模板,例如在插件的初始化钩子中:
PHP
add_action( 'init', function () {
$builder = Queuety::define_workflow( 'onboarding' )
->then( CreateAccountHandler::class )
->then( SendWelcomeEmailHandler::class )
->then( NotifyAdminHandler::class );
Queuety::register_workflow_template( $builder );
} );
运行模板
使用 Queuety::run_workflow() 按名称分派已注册的模板:
PHP
$workflow_id = Queuety::run_workflow( 'onboarding', [ 'email' => 'user@example.com' ] );
第二个参数是初始负载/状态,与构建器上的 ->dispatch() 相同。返回的整数是工作流 ID。
如果模板尚未注册,则会抛出 RuntimeException。
列出已注册的模板
访问模板注册表:
PHP
$registry = Queuety::workflow_templates();
$template = $registry->get( 'onboarding' ); // WorkflowTemplate or null
完整示例
PHP
// Register templates on init.
add_action( 'init', function () {
// User onboarding pipeline
$onboarding = Queuety::define_workflow( 'onboarding' )
->on_queue( 'users' )
->then( CreateAccountHandler::class )
->then( SetupDefaultsHandler::class )
->then( SendWelcomeEmailHandler::class );
Queuety::register_workflow_template( $onboarding );
// Content generation pipeline
$content = Queuety::define_workflow( 'generate_content' )
->on_queue( 'llm' )
->max_attempts( 5 )
->then( BuildPromptHandler::class )
->then( CallLLMHandler::class )
->then( ReviewOutputHandler::class )
->then( PublishHandler::class );
Queuety::register_workflow_template( $content );
} );
// Dispatch them anywhere in your application.
$wf1 = Queuety::run_workflow( 'onboarding', [ 'email' => 'alice@example.com' ] );
$wf2 = Queuety::run_workflow( 'generate_content', [ 'topic' => 'WordPress performance' ] );
模板与内联工作流
| 内联工作流 | 模板 | |
|---|---|---|
| 定义 | 分派时 | 注册时一次定义 |
| 分派 | Queuety::workflow('name')->then(...)->dispatch() |
Queuety::run_workflow('name', $payload) |
| 复用 | 每次都构建步骤链 | 注册一次,多次分派 |
| 适用场景 | 一次性或动态组合的工作流 | 标准化、可重复的流程 |