百科.dev
全部条目在线工具AI 编程趋势榜开源项目技术资讯提交条目
登录
< 返回工具列表
W

workflow

> 编程语言
开源

针对 PHP 的声明性工作流引擎,具有自动依赖解析、同步/异步任务执行和类型安全的响应链。

172 stars0 点赞2 次浏览
访问官网GitHub

工具介绍

针对 PHP 的声明性工作流引擎,具有自动依赖解析、同步/异步任务执行和类型安全的响应链。

Workflow

Summary

Chevere Workflow is a PHP library for building and executing multi-step procedures with automatic dependency resolution. Define independent jobs that can run synchronously or asynchronously, pass data between them using typed responses, and let the engine handle execution order automatically.

Key features:

  • Declarative job definitions: Define what to do, not how to orchestrate it
  • Automatic dependency graph: Jobs execute in optimal order based on their dependencies
  • Sync and async execution: Mix blocking and non-blocking jobs freely
  • Type-safe responses: Access job outputs with full type safety
  • Conditional execution: Run jobs based on variables or previous responses
  • Built-in retry policies: Handle transient failures automatically
  • Testable: Each job is independently testable and workflow graph can be verified

You define jobs and how they connect and depend on each other, Chevere Workflow figures out the execution order and runs them accordingly.

Integrations

  • VS Code Extension: Complete language server support plus graph visualization
  • Laravel Integration: Package for integrating with Laravel applications

Installing

Workflow is available through Packagist and the repository source is at chevere/workflow.

bash
composer require chevere/workflow

Quick Start

Here's a minimal example to get you started:

php
use function Chevere\Workflow\{workflow, sync, variable, run};

// 1. Define a workflow with jobs
$workflow = workflow(
    greet: sync(
        fn(string $name): string => "Hello, {$name}!",
        name: variable('username')
    )
);

// 2. Run with variables
$result = run($workflow, username: 'World');

// 3. Get typed responses
echo $result->response('greet')->string();
// Output: Hello, World!

Core Concepts

Workflow is built around four main concepts:

Concept Description
Job A unit of work that produces a response
Variable External input provided when running the workflow
Response Reference to output from a previous job
Graph Automatic execution order based on job dependencies

How It Works

  1. You define jobs using sync() or async() functions
  2. Jobs declare their inputs: literal values, variable() references, or response() from other jobs
  3. The engine builds a dependency graph automatically
  4. Jobs execute in optimal order (parallel when possible)
  5. Access typed responses after execution

Functions Reference

Function Purpose
workflow() Create a workflow from named jobs
sync() Create a synchronous (blocking) job
async() Create an asynchronous (non-blocking) job
variable() Declare a runtime variable
response() Reference another job's output
run() Execute a workflow with variables

Jobs

Jobs are the building blocks of a workflow. Each job wraps an executable unit (Action, Closure, Invocable class, or any PHP callable) and declares its input arguments.

Creating Jobs with Closures

Use closures for simple, inline operations:

php
use function Chevere\Workflow\{workflow, sync, async, variable, response, run};

$workflow = workflow(
    // Simple calculation
    add: sync(
        fn(int $a, int $b): int => $a + $b,
        a: 10,
        b: variable('number')
    ),
    // Format the result
    format: sync(
        fn(int $sum): string => "Sum: {$sum}",
        sum: response('add')
    )
);

$result = run($workflow, number: 5);
echo $result->response('format')->string(); // Sum: 15

Creating Jobs with Action Classes

For complex or reusable logic, use Action classes as these additionally support method definitions for acceptParameters() and acceptReturn() to define parameter and return rules that are automatically applied at runtime.

php
use Chevere\Action\Action;

class FetchUser extends Action
{
    public function __invoke(int $userId): array
    {
        // Fetch user from database
        return ['id' => $userId, 'name' => 'John', 'email' => '[email protected]'];
    }
}

class SendEmail extends Action
{
    public function __invoke(string $email, string $subject): bool
    {
        // Send email logic
        return true;
    }
}
php
$workflow = workflow(
    user: sync(
        FetchUser::class,
        userId: variable('id')
    ),
    notify: sync(
        SendEmail::class,
        email: response('user', 'email'),
        subject: 'Welcome!'
    )
);

$result = run($workflow, id: 123);

Creating Jobs with Invocable Classes

Use invocable classes (classes with __invoke method) for reusable logic without needing Action base class:

php
class CalculateTotal
{
    public function __invoke(array $items, float $taxRate): float
    {
        $subtotal = array_sum(array_column($items, 'price'));
        return $subtotal * (1 + $taxRate);
    }
}

class FormatCurrency
{
    public function __invoke(float $amount, string $currency = 'USD'): string
    {
        return $currency . ' ' . number_format($amount, 2);
    }
}
php
$workflow = workflow(
    total: sync(
        CalculateTotal::class,
        items: variable('items'),
        taxRate: 0.08
    ),
    formatted: sync(
        FormatCurrency::class,
        amount: response('total'),
        currency: 'EUR'
    )
);

$result = run($workflow, items: [
    ['name' => 'Item 1', 'price' => 10.00],
    ['name' => 'Item 2', 'price' => 20.00]
]);
echo $result->response('formatted')->string(); // EUR 32.40

Creating Jobs with Callables

Use any PHP callable including array callbacks, function names, or static methods:

php
class StringHelper
{
    public static function uppercase(string $text): string
    {
        return strtoupper($text);
    }

    public function reverse(string $text): string
    {
        return strrev($text);
    }
}
php
$helper = new StringHelper();

$workflow = workflow(
    // Using built-in PHP function
    trim: sync(
        'trim',
        string: variable('input')
    ),
    // Using static method
    upper: sync(
        [StringHelper::class, 'uppercase'],
        text: response('trim')
    ),
    // Using instance method
    reversed: sync(
        [$helper, 'reverse'],
        text: response('upper')
    )
);

$result = run($workflow, input: '  hello  ');
echo $result->response('reversed')->string(); // OLLEH

Sync vs Async Jobs

Synchronous jobs (sync) block execution until complete. Use for operations that must run in sequence:

php
workflow(
    first: sync(ActionA::class),  // Runs first
    second: sync(ActionB::class), // Waits for first
    third: sync(ActionC::class),  // Waits for second
);
// Graph: first → second → third

Asynchronous jobs (async) run concurrently when they have no dependencies:

php
workflow(
    resize1: async(ResizeImage::class, size: 'thumb'),
    resize2: async(ResizeImage::class, size: 'medium'),
    resize3: async(ResizeImage::class, size: 'large'),
    store: sync(StoreFiles::class, files: response('resize1'), ...)
);
// Graph: [resize1, resize2, resize3] → store

Job Arguments

Jobs accept three types of arguments:

php
workflow(
    example: sync(
        MyAction::class,
        literal: 'fixed value',           // Literal value
        dynamic: variable('userInput'),   // Runtime variable
        chained: response('otherJob'),    // Previous job output
    )
);

Jobs can define I/O rules via chevere/parameter. Workflow derives parameter and return definitions from the callable signature or Action reflection and validates inputs and responses at runtime.

Integration with Chevere

Workflow works seamlessly with the chevere/parameter and chevere/action packages. When you declare parameter rules with chevere/parameter (types, ranges, or custom validators), those rules travel with the job definitions and are applied automatically at runtime. Workflow performs the validation layer for you before invoking jobs so callers don't need to repeat input or response checks. The same integration applies to chevere/action Action classes: parameter and return definitions are derived from action signatures and validated by Workflow.

These integrations are optional extras. You do not have to use chevere/parameter or chevere/action to use Workflow, but opting in gives stronger guarantees and reduces validation boilerplate across jobs.


Variables

Variables are placeholders for values provided at runtime. Declare them with variable():

php
$workflow = workflow(
    job1: sync(
        SomeAction::class,
        name: variable('userName'),
        age: variable('userAge')
    )
);

// Provide values when running
$result = run($workflow, userName: 'Alice', userAge: 30);

All declared variables must be provided when running the workflow.


Responses

Use response() to pass output from one job to another. This automatically establishes a dependency.

php
$workflow = workflow(
    fetch: sync(
        FetchData::class,
        url: variable('endpoint')
    ),
    process: sync(
        ProcessData::class,
        data: response('fetch')  // Gets entire response from 'fetch'
    ),
    extract: sync(
        ExtractField::class,
        value: response('fetch', 'items')  // Gets 'items' key from response
    )
);

Accessing Nested Response Keys/Properties

When a job returns array or object, access specific keys/properties directly in response():

php
response('user')           // job:user       Entire response object
response('user', 'id')     // job:user->id   id property from object response
response('post', 'id')     // job:post['id'] id key from array response

Execution Graph

The workflow engine automatically builds an execution graph based on job dependencies. Jobs without dependencies run in parallel (when using async), while dependent jobs wait for their dependencies.

…
mermaid
graph TD
    thumb --> store
    medium --> store
    large --> store

Mermaid Graphs

Workflow's graph can be rendered as a Mermaid flowchart for visualization. Each job is a node, and edges represent dependencies. Job conditions are annotated on the node labels.

Generate a Mermaid flowchart using Mermaid::generate():

…
mermaid
graph TB;
    ja("`ja`");
    j1("`j1`");
    j2("`j2`");
    jb("`jb
*if* res(ja)
*ifNot* var(var)`");
    j3("`j3`");
    j4("`j4`");

    j1-->|"j1->id @ j2(n:)
j1->name @ j2(m:)"|j2;
    ja-->jb;
    jb-->|"jb @ j3(a:)"|j3;
    j2-->|"j2 @ j4(i:)"|j4;
    j3-->|"j3 @ j4(j:)"|j4;

Where:

  • if res(ja) Job jb runs only if job ja response is truthy
  • ifNot var(var) Job jb runs only if var variable is not falsy
  • j1->id @ j2(n:) Job j1 response key/property id is used as argument n for job j2
  • j1->name @ j2(m:) Job j1 response key/property name is used as argument m for job j2
  • jb @ j3(a:) Job jb response is used as argument a for job j3
  • j2 @ j4(i:) Job j2 response is used as argument i for job j4
  • j3 @ j4(j:) Job j3 response is used as argument j for job

Issues· 3 开放

查看全部 Issues在 GitHub 打开

暂无开放 Issues,或尚未同步最近议题。

> 标签

PHPasynccheverephpworkflow

暂无评论,来聊聊你的看法吧

> 工具信息

发布日期2026年8月1日
最后更新2026年9月18日
分类编程语言
定价开源

> 相关工具

T
TypeScript
JavaScript 的超集,为前端与全栈提供静态类型
P
Python
通用编程语言,广泛用于 Web、数据与 AI
G
Go
Google 推出的简洁高效系统语言