PHP 属性
Queuety 支持 PHP 8 属性,可实现零配置处理程序注册。为处理程序类添加 #[QueuetyHandler] 注解,并使用自动发现一次性注册所有处理程序。
#[QueuetyHandler] 属性
PHP
use Queuety\Handler;
use Queuety\Attributes\QueuetyHandler;
#[QueuetyHandler( name: 'send_email', queue: 'emails', max_attempts: 5 )]
class SendEmailHandler implements Handler {
public function handle( array $payload ): void {
wp_mail( $payload['to'], $payload['subject'], $payload['body'] );
}
public function config(): array {
return [];
}
}
属性参数:
| 参数 | 类型 | 默认值 | 说明 |
|---|---|---|---|
name |
string |
(必填) | 用于分派的处理程序名称 |
queue |
string |
'default' |
此处理程序的默认队列 |
max_attempts |
int |
3 |
任务被搁置前的最大运行次数 |
needs_wordpress |
bool |
false |
存储在属性上;Queuety 目前不会读取它 |
自动发现
扫描目录中的带注解处理程序类并全部注册:
PHP
use Queuety\Queuety;
$count = Queuety::discover_handlers(
__DIR__ . '/handlers', // directory to scan
'MyPlugin\\Handlers' // PSR-4 namespace prefix
);
// $count = number of handlers registered
此操作会扫描目录及其子目录中的每个 .php 文件,根据命名空间前缀和文件路径推导每个类名,通过自动加载器加载该类,并注册带有 #[QueuetyHandler] 属性且实现 Handler、Step 或 Contracts\Job 的类。
通过 CLI 自动发现
命令行
# Preview discovered handlers
wp queuety discover /path/to/handlers MyPlugin\\Handlers
# Discover and register
wp queuety discover /path/to/handlers MyPlugin\\Handlers --register
输出示例:
代码
+-----------------------------------+----------+------------+
| class | type | name |
+-----------------------------------+----------+------------+
| MyPlugin\Handlers\SendEmailHandler | handler | send_email |
| MyPlugin\Handlers\SyncDataHandler | handler | sync_data |
| MyPlugin\Handlers\BuildPromptStep | step | (none) |
+-----------------------------------+----------+------------+
最佳实践
在插件初始化时注册处理程序:
PHP
add_action( 'plugins_loaded', function () {
Queuety::discover_handlers(
__DIR__ . '/src/Handlers',
'MyPlugin\\Handlers'
);
} );
这样就无需为每个处理程序手动调用 Queuety::register()。将带有该属性的新处理程序类添加到目录后,系统会自动发现它们。
与手动注册结合使用
自动发现的处理程序和手动注册的处理程序可以共存于同一个注册表中。你可以在同一个项目中同时使用这两种方式:
PHP
// Auto-discover the bulk of handlers
Queuety::discover_handlers( __DIR__ . '/handlers', 'MyPlugin\\Handlers' );
// Manually register a handler without the attribute
Queuety::register( 'legacy_handler', LegacyHandler::class );