Skip to content

Building a guided multi-step process

A guided process keeps track of a path while a person supplies data and makes decisions. ExecKernel checks which transition can be taken and returns the data for the next screen. Your application collects forms, prepares context, builds the interface and records the outcome that matters to its business.

In this tutorial you will build a small web wizard for requesting an equipment loan. The person enters their name and the duration, chooses a laptop or projector, reviews the request, then submits or cancels it. The projector allows loans of up to three days; the laptop allows one to fourteen. These are this example’s policies. “Request submitted” means that your application has recorded it; physical availability and handover would need their own processes.

You need a PHP project that already loads the core and local SDK through vendor/autoload.php. If you do not have one yet, prepare that prerequisite with Installation and requirements. We will reuse the composition explained in Local PHP SDK: the client presents typed responses, and the adapter connects the engine to a graph loader and a persistent store.

Download guided-loan.zip and extract it in that project’s root, beside vendor/. The archive creates the guided-loan/ directory. From the project root, run:

Terminal window
php -S 127.0.0.1:8080 -t guided-loan/public

Open the wizard in English. PHP must be able to create and write guided-loan/var/. Serving only public/ keeps graph definitions and state files outside the web directory. This server lets you follow the tutorial on your own machine.

The example is complete: you can explore it before reading the code. First try a five-day request; Laptop is available and Projector is disabled. Choose Laptop, reload the review screen, then submit. The reference stays the same when you reload the result. Next, use “New request” to try two days and choose Projector, or to cancel on review.

File What it provides
equipment-loan.json Path, condition, EN/ES text and terminal content.
bootstrap.php Connection between the local SDK, graph and persistent sessions.
LoanApplication.php Validation, start, choice, recovery and business request recording.
index.php Web controller, forms, notices and payload rendering.
style.css Wizard presentation.
README.md Running the complete example and its boundaries.

The initial form belongs to the application. Once the name and duration are valid, the application starts the graph at node 10. The person chooses equipment there. The branches reach two review nodes: 20 for the laptop and 30 for the projector. Both allow submission or cancellation.

Equipment-loan graph: from node 10, choose Laptop through edge 101 or Projector through edge 102, which requires projector_allowed to be true. Review nodes 20 and 30 allow submission to terminal 90 or cancellation to terminal 91.

Position Choice Next position
10, equipment 101, laptop 20, laptop review
10, equipment 102, projector, when permitted 30, projector review
20, review 201, submit; 202, cancel 90, submitted; 91, cancelled
30, review 301, submit; 302, cancel 90, submitted; 91, cancelled

To let the graph check the projector choice, we declare a condition on edge 102:

{
"edge_id": 102,
"rule": "context_value",
"params": {
"key": "projector_allowed",
"operator": "==",
"value": true
}
}

The condition reads a value prepared by PHP. The engine does not know the form and does not calculate a loan policy by itself. Your application validates the duration and derives projector_allowed; the engine checks that value when evaluating the edge. This is the relationship between data and decisions developed in Context, state and history: context supplies facts to an execution, and conditions determine whether a transition can be taken.

Keep four sets of data separate:

Data Contents in this example Where it lives
Received form Name and duration that have not yet been validated. HTTP request.
Engine context days, projector_allowed and, after a choice, equipment. ExecKernel session state.
Application request Reference, name, days, equipment, business status and sessionId. A JSON file in var/requests/.
Browser session Current request reference, language and form token. PHP session in var/http/.

Engine state, stored in var/engine/, also contains the position and path. The request reference and engine session ID identify different things: the record connects them through sessionId. The name is needed to display the request, but it does not participate in rules and is not sent to context.

bootstrap.php loads Composer and constructs the client:

use ExecKernel\Bootstrap\ExecKernelLocalBootstrap;
use ExecKernel\Client\ExecKernelLocalClient;
$client = new ExecKernelLocalClient(
ExecKernelLocalBootstrap::fromFilesystem(
__DIR__ . '/graphs',
__DIR__ . '/var/engine',
),
);

fromFilesystem() composes the engine, the loader that will find equipment-loan.json, and a FilesystemSessionStore. That last directory must remain available between requests: the client object is created again on each PHP request, but sessions remain on disk.

The client is passed to LoanApplication, our application service. Its methods match operations the wizard needs: create(), current() and choose(). The web controller reads the request and produces HTML; the service coordinates the business request record with the SDK.

LoanApplication::create() receives the name and duration as strings. First it converts the duration to an integer from one to fourteen and checks the name length:

$requester = trim($requester);
$days = filter_var($daysInput, FILTER_VALIDATE_INT, [
'options' => ['min_range' => 1, 'max_range' => 14],
]);
if (preg_match('/^.{1,80}$/us', $requester) !== 1 || $days === false) {
throw new InvalidArgumentException('invalid_form');
}

The HTML also constrains input, but this check runs on the server. If it fails, the controller returns a notice and keeps the entered form values. No engine session has started yet.

With valid data, the service prepares the facts the graph will use:

$state = $this->client->start('equipment-loan', [
'days' => $days,
'projector_allowed' => $days <= 3,
], $lang);

The first argument identifies the graph file; the second contains scalar data prepared by your application; $lang selects English or Spanish text. $_POST is not passed as context. A submitted field named projector_allowed therefore cannot change the policy defined in PHP.

The SDK returns a SessionStateDTO at node 10. Its sessionId lets the application recover this execution. The application then creates its record:

$record = [
'id' => bin2hex(random_bytes(6)),
'requester' => $requester,
'days' => $days,
'sessionId' => $state->sessionId,
'equipment' => null,
'status' => 'draft',
];
$this->save($record);

The record already exists even though no equipment has been selected. The controller stores only its reference in $_SESSION['requestId'] and redirects to the current screen. Later requests obtain the engine ID from this server-side record.

To display a request, current() reads the record and calls resume() with its sessionId. The response contains a NodePayloadDTO while choices remain. The template uses its title and edges:

<?php foreach ($payload->edges as $edge): ?>
<button name="edge"
value="<?= h($edge['id']) ?>"
<?= $edge['enabled'] ? '' : 'disabled' ?>>
<?= h($edge['labels'][0]['text']) ?>
</button>
<?php endforeach; ?>

The button submits the edge ID, not the destination node. enabled determines whether it can be pressed, and the label resolved for the language supplies its text. This graph declares an EN/ES label for every edge. The example’s h() function applies htmlspecialchars() before inserting data into HTML.

These buttons sit inside a form with action=choose and a token checked by the controller to protect against requests from outside the form. The browser does not submit an engine session ID or context object. The side summary comes from the application record; the engine supplies the question and choices.

Actual wizard screenshot for a five-day loan: Laptop is available and Projector is disabled with the three-day limit. The summary shows a request still in draft.

For five days, the condition on 102 is not satisfied. The template adds a concrete explanation beside the disabled button. That sentence belongs to this application and its loan policy.

Apply the choice and use the accepted response

Section titled “Apply the choice and use the accepted response”

choose() first recovers the current request. At node 10, it translates the received edge into an equipment code defined by the server:

$context = $current->nodeId === 10
? match ($edgeId) {
101 => ['equipment' => 'laptop'],
102 => ['equipment' => 'projector'],
default => [],
}
: [];
$next = $this->client->navigate($current, $edgeId, $context);
$this->synchronize($record, $next);

This reuses candidate context: equipment is proposed for this choice and becomes part of saved state if the transition is accepted. The client does not modify $current; it returns $next. The local adapter loads the reference state from the store, checks the choice and confirms persistence before returning it.

If 101 is accepted, the session reaches 20 and context contains equipment: laptop. Your application copies this confirmed value to its record through synchronize(). It does not record “laptop selected” before knowing whether the engine has accepted the edge.

Actual review screenshot: Laptop and five days appear in the summary beside Submit request and Cancel request. The reference is retained from the preceding screen.

At this step, submission selects 201 and cancellation selects 202. Projector review uses 301 and 302. The template does not need to hard-code those branches: it renders the edges from the returned payload again.

Disabling a button helps the person, but the engine still checks the choice. If edge=102 is deliberately submitted for the five-day request, navigate() throws an SDK exception with code EK-SEC-NAV-002. For this rejection, the adapter does not save candidate context or a new path.

The controller recognizes the code and prepares a notice:

catch (ExecKernelException $error) {
$key = match ($error->code()) {
'EK-SEC-NAV-002' => 'unavailable',
'EK-SEC-NAV-001', 'EK-SELECT-001' => 'stale',
default => null,
};
if ($key !== null) {
$_SESSION['notice'] = $text[$key];
redirectToScreen();
}
// The full controller logs other errors and responds with 503.
}

The imported class is ExecKernel\Exceptions\ExecKernelException, from the SDK. After the redirect, current() loads the session again and reconstructs the screen. The person sees “That option is unavailable. Your request remains at the same step”, with Laptop still available. The record remains a draft with no equipment selected.

An old tab can also submit an edge that no longer leaves the current node. The stale notice explains that the request has changed and displays its current choices. Other errors are not turned into business rejections. The controller asks the person to reload to recover saved state and logs the diagnostic; it does not automatically repeat a navigation whose outcome it does not know. Client errors, transport and diagnostics develops that distinction.

Record the outcome and recover it on return

Section titled “Record the outcome and recover it on return”

Terminal 90 means “submit the request” within this graph; 91 means “cancel”. Your application assigns its business status from the accepted response:

$updated = $record;
$updated['equipment'] = $state->context['equipment'] ?? null;
$updated['status'] = match ($state->nodeId) {
90 => 'submitted',
91 => 'cancelled',
default => 'draft',
};
if ($updated !== $record) {
$this->save($updated);
}

This is the central part of synchronize(). The engine determines the position and returns its result. Your application interprets those terminals and updates its JSON file. At a terminal, the payload is a TerminalPayloadDTO: the template displays the graph’s content outputs instead of new navigation buttons.

Actual result screenshot: Request submitted, the same reference and Submitted status in the record. The message explains that the request has been recorded and equipment has not yet been reserved.

Reloading does not start another path. The controller keeps the reference in the PHP session, and the service follows this sequence:

$record = $this->read($requestId);
$state = $this->client->resume($record['sessionId'], $lang);
$record = $this->synchronize($record, $state);
return ['record' => $record, 'state' => $state];

resume() recovers the saved position and regenerates the payload without choosing an edge. You can therefore reload both review and result screens. Repeating “Submit” after reaching the terminal also just displays the existing outcome.

The business record and engine session are stored separately. If writing the record fails after an accepted transition, the next recovery applies synchronize() again from engine state. This repairs the example’s simple projection; a payment, reservation or email would need its own coordination. The two writes do not form a transaction. A failure during initial creation can also leave an engine session without an associated record.

Recovery requires the browser’s PHP session and valid engine state to remain available. It does not include access from another device or account-based identification. The PHP session lock serializes requests from this browser; the engine’s filesystem store does not add conditional writes. To extend those boundaries, continue with Session stores and persistence modes and Concurrency and session revisions.

You now have a complete path: validate data, start or recover a session, display its payload, request an edge and turn the accepted result into application data.

To add another item, add its branch and text to the graph and update the edge-to-equipment mapping in choose(). When a policy changes, decide which facts your application should calculate and which condition the graph will check. When an outcome should trigger a business action, define how your application will execute and record it; reaching a terminal does not perform that action by itself.

The Product Configurator provides a broader selection case with candidate context and budget. Returns Center follows another local PHP application that connects engine decisions to its own case record.