本文目录导读:

PHP 中实现流程管理器的方案取决于你的具体需求——是代码层面的流程控制,还是业务层面的工作流引擎,下面从这两个维度分别说明。
代码层面的流程管理(逻辑控制)
这是最基础的需求,PHP 提供了多种控制结构来管理代码执行流程。
基础控制结构
// 顺序执行
$step1 = loadData();
$step2 = processData($step1);
$step3 = saveData($step2);
// 条件分支
if ($conditionA) {
// 执行路径 A
} elseif ($conditionB) {
// 执行路径 B
} else {
// 默认路径
}
// 循环
foreach ($items as $item) {
if ($item->isValid()) {
continue; // 跳过当前
}
if ($item->shouldStop()) {
break; // 中断循环
}
process($item);
}
状态机模式(推荐)
class OrderStateMachine
{
private $state;
private $allowedTransitions = [
'pending' => ['approved', 'rejected'],
'approved' => ['shipped', 'cancelled'],
'shipped' => ['delivered'],
'delivered' => [],
'cancelled' => [],
'rejected' => [],
];
public function __construct($initialState = 'pending')
{
$this->state = $initialState;
}
public function canTransition($nextState): bool
{
return in_array(
$nextState,
$this->allowedTransitions[$this->state] ?? []
);
}
public function transition($nextState): self
{
if (!$this->canTransition($nextState)) {
throw new \RuntimeException(
"Cannot transition from {$this->state} to {$nextState}"
);
}
$this->state = $nextState;
return $this;
}
public function getState(): string
{
return $this->state;
}
}
// 使用示例
$order = new OrderStateMachine('pending');
$order->transition('approved'); // ✓ 合法
$order->transition('delivered'); // ✗ 抛异常
业务层面的工作流引擎
适用于需要管理复杂审批、多级流转、并行任务的场景。
轻量级方案:自定义工作流类
class WorkflowEngine
{
private $tasks = [];
private $currentTask = 0;
public function addTask(callable $task, string $name = ''): self
{
$this->tasks[] = [
'name' => $name,
'callback' => $task,
];
return $this;
}
public function run()
{
$context = new WorkflowContext();
foreach ($this->tasks as $index => $task) {
$this->currentTask = $index;
echo "执行任务: {$task['name']}\n";
$result = call_user_func($task['callback'], $context);
// 支持任务间数据传递
$context->setResult($task['name'], $result);
// 支持条件性跳过
if ($result === false) {
echo "任务 {$task['name']} 中断流程\n";
break;
}
}
return $context;
}
}
class WorkflowContext
{
private $data = [];
public function set(string $key, $value): void
{
$this->data[$key] = $value;
}
public function get(string $key, $default = null)
{
return $this->data[$key] ?? $default;
}
}
// 使用示例
$engine = new WorkflowEngine();
$engine
->addTask(function ($ctx) {
echo "第一步:数据验证\n";
$ctx->set('validated', true);
return true;
}, '验证')
->addTask(function ($ctx) {
if (!$ctx->get('validated')) {
return false;
}
echo "第二步:数据处理\n";
$ctx->set('processed', ['data' => 'value']);
return true;
}, '处理')
->run();
完整解决方案:Symfony Workflow 组件
composer require symfony/workflow
use Symfony\Component\Workflow\Definition;
use Symfony\Component\Workflow\MarkingStore\MethodMarkingStore;
use Symfony\Component\Workflow\Transition;
use Symfony\Component\Workflow\Workflow;
use Symfony\Component\Workflow\MarkingStore\MarkingStoreInterface;
// 定义状态和转移
$places = ['draft', 'review', 'approved', 'rejected', 'published'];
$transitions = [
new Transition('submit', 'draft', 'review'),
new Transition('approve', 'review', 'approved'),
new Transition('reject', 'review', 'rejected'),
new Transition('publish', 'approved', 'published'),
];
$definition = new Definition($places, $transitions);
// 状态存储方式
$markingStore = new MethodMarkingStore(true, 'currentPlace');
$workflow = new Workflow($definition, $markingStore);
class Document
{
private $status = 'draft';
public function getStatus() { return $this->status; }
public function setStatus($status) { $this->status = $status; }
}
$doc = new Document();
if ($workflow->can($doc, 'approve')) {
$workflow->apply($doc, 'approve');
}
消息队列流程(异步处理)
use RabbitMQ\Connection;
use RabbitMQ\Message;
class AsyncWorkflow
{
private $connection;
public function dispatchStep1($data)
{
$this->publish('workflow.step1', $data);
}
public function handleStep1($data)
{
// 处理步骤1
$result = $this->processStep1($data);
// 发送到下一步
$this->publish('workflow.step2', $result);
}
public function handleStep2($data)
{
// 处理步骤2
$this->processStep2($data);
}
}
// 消费者模式
class WorkflowConsumer
{
public function configure($channel)
{
$channel->basic_qos(null, 1, null);
// 步骤1消费者
$channel->basic_consume('workflow.step1', '', false, false, false, false, function ($msg) {
echo "处理步骤1\n";
$data = json_decode($msg->body, true);
$this->handleStep1($data);
});
// 步骤2消费者
$channel->basic_consume('workflow.step2', '', false, false, false, false, function ($msg) {
echo "处理步骤2\n";
$data = json_decode($msg->body, true);
$this->handleStep2($data);
});
while (count($channel->callbacks) > 0) {
$channel->wait();
}
}
}
推荐方案对比
| 方案 | 适用场景 | 复杂度 | 性能 | 扩展性 |
|---|---|---|---|---|
| 基础控制结构 | 简单逻辑流程 | 极低 | 极高 | 差 |
| 状态机模式 | 状态流转明确 | 低 | 高 | 中 |
| 自定义工作流类 | 中小型业务流程 | 中 | 中 | 中 |
| Symfony Workflow | 企业级工作流 | 高 | 中 | 高 |
| 消息队列方案 | 分布式异步流程 | 高 | 高 | 极高 |
实际项目建议
对于大多数项目,建议:
- 简单流程 → 用状态机模式
- 中等复杂 → 自定义工作流引擎 + 数据库存储状态
- 大型复杂 → 选用商业/开源工作流引擎(如 Camunda、Flowable)并提供 PHP 客户端
// 伪代码示例:基于数据库的工作流
class WorkflowProcess
{
private $db;
public function execute($processId, $action)
{
// 1. 获取当前状态
$currentState = $this->db->getState($processId);
// 2. 验证动作是否合法
$transitions = $this->getTransitions($currentState);
// 3. 执行动作
$this->db->beginTransaction();
try {
// 执行业务逻辑
$this->performAction($action);
// 更新状态
$newState = $transitions[$action];
$this->db->updateState($processId, $newState);
// 记录日志
$this->db->insertLog($processId, $action, $currentState, $newState);
$this->db->commit();
} catch (\Exception $e) {
$this->db->rollback();
throw $e;
}
}
}
选择方案时,记住这个原则:
"先从最简单的方式开始,当遇到真实瓶颈时再升级方案。"
有任何具体场景需要细化方案,可以告诉我你的业务需求,我帮你做更合适的设计。