Catene sequenziali
Il modello di workflow più comune è una catena lineare di passaggi. Ogni passaggio viene eseguito dopo il completamento del precedente, ricevendo lo stato accumulato.
Il metodo ->then()
Usate ->then() per aggiungere passaggi sequenziali a un workflow:
use Queuety\Queuety;
Queuety::workflow( 'onboarding' )
->then( CreateAccountHandler::class )
->then( SendWelcomeEmailHandler::class )
->then( NotifyAdminHandler::class )
->dispatch( [ 'email' => 'user@example.com' ] );
I passaggi vengono eseguiti nell'ordine in cui sono aggiunti. Il workflow avanza solo quando il passaggio corrente viene completato correttamente.
L'interfaccia Step
I gestori dei passaggi del workflow implementano l'interfaccia Queuety\Step:
use Queuety\Step;
class CreateAccountHandler implements Step {
public function handle( array $state ): array {
$user_id = wp_create_user( $state['email'], wp_generate_password() );
return [ 'user_id' => $user_id ];
}
public function config(): array {
return [
'max_attempts' => 3,
];
}
}
Differenze principali rispetto all'interfaccia Handler:
Handler (job) |
Step (workflow) |
|
|---|---|---|
| Firma del metodo | handle(array $payload): void |
handle(array $state): array |
| Input | Payload del job | Stato accumulato del workflow |
| Output | Nessuno (void) | Dati da unire allo stato |
Flusso dello stato
Ogni passaggio riceve lo stato accumulato completo e restituisce un array di nuove coppie chiave-valore. I dati restituiti vengono uniti allo stato per i passaggi successivi:
class FetchUserHandler implements Step {
public function handle( array $state ): array {
// $state contains: ['user_id' => 42]
$user = get_user_by( 'ID', $state['user_id'] );
return [ 'user_name' => $user->display_name, 'user_email' => $user->user_email ];
}
public function config(): array {
return [];
}
}
class GenerateReportHandler implements Step {
public function handle( array $state ): array {
// $state contains: ['user_id' => 42, 'user_name' => 'Alice', 'user_email' => 'alice@example.com']
$report = build_report( $state['user_name'] );
return [ 'report_url' => $report->url ];
}
public function config(): array {
return [];
}
}
Configurazione dei passaggi
Il metodo config() supporta le seguenti chiavi:
| Chiave | Tipo | Predefinito | Descrizione |
|---|---|---|---|
max_attempts |
int |
3 |
Numero massimo di tentativi per questo passaggio |
backoff |
string |
exponential |
Strategia di attesa tra i tentativi |
Esempio di pipeline LLM
Un caso d'uso comune consiste nel concatenare chiamate API LLM con l'elaborazione dei dati:
use Queuety\Step;
class BuildPromptHandler implements Step {
public function handle( array $state ): array {
$user = get_user_by( 'ID', $state['user_id'] );
$posts = get_posts( [ 'author' => $user->ID, 'numberposts' => 10 ] );
$context = implode( "\n", array_map( fn( $p ) => $p->post_content, $posts ) );
return [
'prompt' => "Summarize this author's recent work:\n\n{$context}",
];
}
public function config(): array {
return [];
}
}
class CallOpenAIHandler implements Step {
public function handle( array $state ): array {
$response = wp_remote_post( 'https://api.openai.com/v1/chat/completions', [
'timeout' => 120,
'headers' => [
'Authorization' => 'Bearer ' . OPENAI_API_KEY,
'Content-Type' => 'application/json',
],
'body' => json_encode( [
'model' => 'gpt-4',
'messages' => [ [ 'role' => 'user', 'content' => $state['prompt'] ] ],
] ),
] );
$body = json_decode( wp_remote_retrieve_body( $response ), true );
return [ 'summary' => $body['choices'][0]['message']['content'] ];
}
public function config(): array {
return [ 'max_attempts' => 5 ];
}
}
class SaveSummaryHandler implements Step {
public function handle( array $state ): array {
$post_id = wp_insert_post( [
'post_title' => "Summary for user #{$state['user_id']}",
'post_content' => $state['summary'],
'post_status' => 'publish',
] );
return [ 'summary_post_id' => $post_id ];
}
public function config(): array {
return [];
}
}
Avviate la pipeline:
Queuety::workflow( 'summarize_author' )
->then( BuildPromptHandler::class )
->then( CallOpenAIHandler::class )
->then( SaveSummaryHandler::class )
->on_queue( 'llm' )
->max_attempts( 5 )
->dispatch( [ 'user_id' => 42 ] );
Se la chiamata OpenAI va in timeout, il worker riprova solo quel passaggio. Il prompt creato nel passaggio 0 è già memorizzato in modo sicuro nello stato del workflow.