Symfony Workflow: state machine and transitions

Symfony's Workflow component describes an object's life cycle, its places and its transitions, once and for all, and refuses any move that wasn't planned.

// The argument name picks the "reservation" workflow (a state_machine).
public function transition(Reservation $reservation, string $transition, WorkflowInterface $reservationStateMachine): Response
{
    if (!$reservationStateMachine->can($reservation, $transition)) {
        // unknown transition, not allowed from this place, or blocked by a guard
    }
    $reservationStateMachine->apply($reservation, $transition);
}

#[AsEnteredListener(workflow: 'reservation', place: 'confirmee')]
public function confirmee(EnteredEvent $event): void { /* send the confirmation */ }

A status handled with if ($statut === …) everywhere ends up letting a booking be honoured without ever being confirmed. A state machine (state_machine) declares the possible places and the allowed transitions; the service knows where the object stands (getMarking()), what can be done (can()) and moves it forward (apply()). On every transition, it emits events, guard, leave, entered and others, to which you hook guards and side effects. The trap is listening to the wrong one: leave fires for every transition that leaves a place, cancellation included, whereas entered only targets arriving at the place you mean.

The exercises have you describe the life of a tavern booking, from the request to the meal, then fix a ledger where the transitions, the guards and the scrolls sent no longer say the same thing.

3 exercises work on this concept, by writing code in the browser.

In the tracks

In Practice

Related concepts

GuardsDebuggingWorkflow eventsMailer