Skip to content

Quick Start

This example uses attribute-based definitions.

1. Generate a Workflow Skeleton

bash
bin/cake workflow init order Orders

This creates a workflow directory in src/Workflow/Order/ with three files:

php
namespace App\Workflow\Order;

use Workflow\Attribute\StateMachine;
use Workflow\State\AbstractState;

#[StateMachine(name: 'order', table: 'Orders', field: 'state')]
abstract class BaseOrderState extends AbstractState
{
}
php
namespace App\Workflow\Order;

use Workflow\Attribute\InitialState;
use Workflow\Attribute\Transition;

#[InitialState]
#[Transition(to: CompletedState::class, name: 'complete', happy: true)]
class PendingState extends BaseOrderState
{
}
php
namespace App\Workflow\Order;

use Workflow\Attribute\FinalState;

#[FinalState]
class CompletedState extends BaseOrderState
{
}

If Bake is installed, you can add more states later:

bash
bin/cake bake workflow_state Order/Shipped --transition-to Delivered --transition-name deliver

See Attributes for adding guards, commands, and lifecycle callbacks.

2. Attach the Behavior

In your table class:

php
public function initialize(array $config): void
{
    parent::initialize($config);

    $this->addBehavior('Workflow.Workflow', [
        'workflow' => 'order',
    ]);
}

3. Apply Transitions

php
$order = $this->Orders->get($id);
$workflow = $this->workflowRegistry->get($order);

if ($workflow->can('complete')) {
    $result = $workflow->apply('complete', [
        'user_id' => $this->Authentication->getIdentity()->getIdentifier(),
        'reason' => 'Fulfillment finished',
    ]);

    if ($result->isSuccess()) {
        $this->Orders->saveOrFail($order);
    }
}

See Behavior Integration for the full API.

4. Inspect the Workflow

CLI:

bash
bin/cake workflow list
bin/cake workflow show order
bin/cake workflow validate

Admin UI:

  • /admin/workflow/workflows
  • /admin/workflow/workflows/view/order

Next Steps

Released under the MIT License.