philiprehberger/php-state-machine
Composer 安装命令:
composer require philiprehberger/php-state-machine
包简介
Declarative state machine with guards, hooks, and transition history
README 文档
README
Declarative state machine with guards, hooks, and transition history.
Requirements
- PHP 8.2+
Installation
composer require philiprehberger/php-state-machine
Usage
Define a state machine
use PhilipRehberger\StateMachine\StateMachine; $sm = StateMachine::define() ->states(['pending', 'processing', 'shipped', 'delivered', 'cancelled']) ->initial('pending') ->stateProperty('state') ->transition('process', 'pending', 'processing') ->transition('ship', 'processing', 'shipped') ->transition('deliver', 'shipped', 'delivered') ->transition('cancel', ['pending', 'processing'], 'cancelled') ->build();
Apply transitions
$order = new Order(); // $order->state === 'pending' $result = $sm->apply($order, 'process'); // $order->state === 'processing' // $result->from === 'pending' // $result->to === 'processing'
Pass a payload to transitions
$sm = StateMachine::define() ->states(['pending', 'approved', 'rejected']) ->initial('pending') ->transition('approve', 'pending', 'approved') ->guard(fn (object $order, array $payload) => ($payload['role'] ?? '') === 'manager') ->before(fn (object $order, array $payload) => $order->log[] = 'Approved by '.$payload['user']) ->transition('reject', 'pending', 'rejected') ->build(); $sm->apply($order, 'approve', ['role' => 'manager', 'user' => 'Alice']);
The $payload array is passed through to all guards, before hooks, and after hooks. It defaults to [] when omitted, so existing guards and hooks that accept only one parameter continue to work.
Check if a transition is allowed
$sm->can($order, 'ship'); // true $sm->can($order, 'deliver'); // false
Get available transitions
$sm->allowedTransitions($order); // ['ship', 'cancel'] $sm->availableTransitions($order); // ['ship', 'cancel'] (alias) // Payload is forwarded to guards when checking availability: $sm->availableTransitions($order, ['role' => 'manager']);
Guards
Guards are callables that must return true for the transition to proceed:
$sm = StateMachine::define() ->states(['pending', 'processing', 'shipped']) ->initial('pending') ->transition('process', 'pending', 'processing') ->guard(fn (object $order, array $payload) => $order->isPaid) ->transition('ship', 'processing', 'shipped') ->build();
Before and after hooks
$sm = StateMachine::define() ->states(['pending', 'processing']) ->initial('pending') ->transition('process', 'pending', 'processing') ->before(fn (object $order, array $payload) => $order->log[] = 'Processing started') ->after(fn (object $order, array $payload) => $order->log[] = 'Processing complete') ->build();
State entry/exit hooks
$sm = StateMachine::define() ->states(['draft', 'review', 'published']) ->initial('draft') ->onEnter('review', fn (object $entity, string $transition) => $entity->log[] = "Entered review via $transition") ->onExit('draft', fn (object $entity, string $transition) => $entity->log[] = "Left draft via $transition") ->transition('submit', 'draft', 'review') ->transition('approve', 'review', 'published') ->build();
Rollback the last transition
$sm->apply($order, 'process'); $sm->rollback($order); // $order->state === 'pending'
Mermaid diagram export
echo $sm->toMermaid(); // stateDiagram-v2 // [*] --> pending // pending --> processing : process // processing --> shipped : ship // shipped --> delivered : deliver // pending --> cancelled : cancel // processing --> cancelled : cancel
Transition history
$sm->apply($order, 'process'); $sm->apply($order, 'ship'); $history = $sm->history(); $history->all(); // [TransitionResult, TransitionResult] $history->last(); // TransitionResult { transition: 'ship', from: 'processing', to: 'shipped' }
API
| Method | Description |
|---|---|
StateMachine::define() |
Create a new StateMachineBuilder |
$sm->apply(object $entity, string $transition, array $payload = []) |
Apply a transition, returns TransitionResult |
$sm->can(object $entity, string $transition, array $payload = []) |
Check if a transition is allowed |
$sm->allowedTransitions(object $entity, array $payload = []) |
Get names of all allowed transitions |
$sm->availableTransitions(object $entity, array $payload = []) |
Alias for allowedTransitions() |
$sm->currentState(object $entity) |
Get the entity's current state |
$sm->rollback(object $entity) |
Revert the most recent transition |
$sm->toMermaid() |
Generate a Mermaid state diagram string |
$sm->history() |
Get the TransitionHistory instance |
$sm->initialState() |
Get the defined initial state |
$sm->states() |
Get all defined states |
StateMachineBuilder
| Method | Description |
|---|---|
->states(array $states) |
Define valid states |
->initial(string $state) |
Set the initial state |
->stateProperty(string $property) |
Set the entity property name (default: 'state') |
->onEnter(string $state, callable $hook) |
Register a hook that fires when entering a state |
->onExit(string $state, callable $hook) |
Register a hook that fires when leaving a state |
->transition(string $name, string|array $from, string $to) |
Define a transition |
->build() |
Build the StateMachine |
TransitionBuilder
| Method | Description |
|---|---|
->guard(callable $guard) |
Add a guard (object $entity, array $payload): bool |
->before(callable $hook) |
Add a before-transition hook (object $entity, array $payload): void |
->after(callable $hook) |
Add an after-transition hook (object $entity, array $payload): void |
Development
composer install vendor/bin/phpunit vendor/bin/pint --test
Support
If you find this project useful:
License
philiprehberger/php-state-machine 适用场景与选型建议
philiprehberger/php-state-machine 是一款 基于 PHP 开发的 Composer 扩展包,目前已累计 48 次下载、GitHub Stars 达 1, 最近一次更新时间为 2026 年 03 月 15 日, 在 PHP 生态内属于活跃度较高的组件。
它主要适用于以下技术方向: 「workflow」 「fsm」 「hooks」 「state-machine」 「guards」 「transitions」 等业务场景。在实际项目中,围绕这些方向常见需要落地的问题包括:接口对接、性能调优、并发安全、与既有框架(Laravel / ThinkPHP / Yii / Webman 等)的兼容适配,以及生产环境的日志埋点与稳定性保障。
我们在过去多个企业项目中使用过 philiprehberger/php-state-machine 或与其功能相近的方案,如果你在选型或落地过程中遇到问题,例如 版本兼容、二次改造、私有化封装、与内部系统对接、生产 BUG 排查,欢迎联系我们协助评估。
基于 philiprehberger/php-state-machine 在你已有业务上做功能扩展、字段裁剪、UI 适配、与内部账号 / 权限 / 日志系统的深度对接。
线上偶发问题、内存泄漏、慢查询、并发异常等排查修复;针对高流量场景做缓存、队列、索引层面的调优。
承接完整的项目从需求 → 设计 → 开发 → 上线 → 长期运维;也可按月提供技术保姆服务。
与 philiprehberger/php-state-machine 相关的其它包
同方向 / 同关键字的高下载量 PHP Composer 包推荐,方便对比选型:
Workflow for NetCommons Plugin
Finite state machine for php.
Workflow logger
A state Machine library for business processes
A lightweight WordPress hook helper library. Register hooks before WordPress loads, run callbacks only once, and more.
Hooks integrated in Voyager
统计信息
- 总下载量: 48
- 月度下载量: 0
- 日度下载量: 0
- 收藏数: 1
- 点击次数: 34
- 依赖项目数: 0
- 推荐数: 0
其他信息
- 授权协议: MIT
- 更新时间: 2026-03-15