Declarative workflow engine for PHP with automatic dependency resolution, sync/async job execution, and type-safe response chaining.
Declarative workflow engine for PHP with automatic dependency resolution, sync/async job execution, and type-safe response chaining.
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:
You define jobs and how they connect and depend on each other, Chevere Workflow figures out the execution order and runs them accordingly.
Workflow is available through Packagist and the repository source is at chevere/workflow.
composer require chevere/workflowHere's a minimal example to get you started:
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!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 |
sync() or async() functionsvariable() references, or response() from other jobs| 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 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.
Use closures for simple, inline operations:
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: 15For 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.
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;
}
}$workflow = workflow(
user: sync(
FetchUser::class,
userId: variable('id')
),
notify: sync(
SendEmail::class,
email: response('user', 'email'),
subject: 'Welcome!'
)
);
$result = run($workflow, id: 123);Use invocable classes (classes with __invoke method) for reusable logic without needing Action base class:
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);
}
}$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.40Use any PHP callable including array callbacks, function names, or static methods:
class StringHelper
{
public static function uppercase(string $text): string
{
return strtoupper($text);
}
public function reverse(string $text): string
{
return strrev($text);
}
}$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(); // OLLEHSynchronous jobs (sync) block execution until complete. Use for operations that must run in sequence:
workflow(
first: sync(ActionA::class), // Runs first
second: sync(ActionB::class), // Waits for first
third: sync(ActionC::class), // Waits for second
);
// Graph: first → second → thirdAsynchronous jobs (async) run concurrently when they have no dependencies:
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] → storeJobs accept three types of arguments:
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.
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 are placeholders for values provided at runtime. Declare them with variable():
$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.
Use response() to pass output from one job to another. This automatically establishes a dependency.
$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
)
);When a job returns array or object, access specific keys/properties directly in response():
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 responseThe 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.
…graph TD
thumb --> store
medium --> store
large --> storeWorkflow'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():
…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:
jb runs only if job ja response is truthyjb runs only if var variable is not falsyj1 response key/property id is used as argument n for job j2j1 response key/property name is used as argument m for job j2jb response is used as argument a for job j3j2 response is used as argument i for job j4j3 response is used as argument j for jobNo open issues yet, or sync has not completed.