Workflows as State Machines

Version: 4.0
Edit this page

Warning: You are browsing the documentation for Symfony 4.0, which is no longer maintained.

Read the updated version of this page for Symfony 5.3 (the current stable version).

Workflows as State Machines

The workflow component is modelled after a Workflow net which is a subclass of a Petri net. By adding further restrictions you can get a state machine. The most important one being that a state machine cannot be in more than one place simultaneously. It is also worth noting that a workflow does not commonly have cyclic path in the definition graph, but it is common for a state machine.

Example of a State Machine

A pull request starts in an initial "start" state, a state for e.g. running tests on Travis. When this is finished, the pull request is in the "review" state, where contributors can require changes, reject or accept the pull request. At any time, you can also "update" the pull request, which will result in another Travis run.

Below is the configuration for the pull request state machine.

  • YAML
  • XML
  • PHP
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
# config/packages/workflow.yaml
framework:
    workflows:
        pull_request:
            type: 'state_machine'
            supports:
                - App\Entity\PullRequest
            initial_place: start
            places:
                - start
                - coding
                - travis
                - review
                - merged
                - closed
            transitions:
                submit:
                    from: start
                    to: travis
                update:
                    from: [coding, travis, review]
                    to: travis
                wait_for_review:
                    from: travis
                    to: review
                request_change:
                    from: review
                    to: coding
                accept:
                    from: review
                    to: merged
                reject:
                    from: review
                    to: closed
                reopen:
                    from: closed
                    to: review

In a Symfony application using the default services.yaml configuration, you can get this state machine by injecting the Workflow registry service:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
// ...
use Symfony\Component\Workflow\Registry;

class SomeService
{
    private $workflows;

    public function __construct(Registry $workflows)
    {
        $this->workflows = $workflows;
    }

    public function someMethod($subject)
    {
        $stateMachine = $this->workflows->get($subject, 'pull_request');
        // ...
    }

    // ...
}
This work, including the code samples, is licensed under a Creative Commons BY-SA 3.0 license.