Skip to content

Embedding the engine · Factory and Facade

Embedding ExecKernel means running a graph decision inside your application’s PHP process. Your service supplies the graph and the session data; the engine returns the next state and a payload, the data your application uses to present the current step or result.

Two classes simplify that integration. ExecKernelFactory builds an engine with compatible runtime components. ExecKernelFacade combines that engine with a graph loader, so your service can start or continue a graph by its code. Your application still decides where session state is saved and how the result becomes a response.

This guide assumes ExecKernel is already available through your application’s autoloader; see Installation and requirements for setup.

Decide which responsibilities your service will own

Section titled “Decide which responsibilities your service will own”

Factory and Facade operate at different moments. You use the factory when composing your application’s services. You call the facade when handling a start, choice or return to an existing session.

Component What it does What your application provides
ExecKernelFactory Connects the evaluator, navigator, payload builder and shared event dispatcher; returns an ExecKernel engine. Optional dependencies such as custom rules, a clock, event bridge, logging or session policies.
ExecKernelFacade Loads a graph, resolves its default language and calls the engine; returns an EngineResult. The configured engine, a GraphLoaderInterface and, when continuing, the existing SessionState.
Your application service Associates state with a session ID, saves and reloads it, and prepares a view or another application response. A store, session ownership checks and the response logic appropriate to your application.

Your application calls Facade, receives state and payload, and separately saves or loads session state. Facade uses a graph loader and the engine created by Factory. There is no store inside Facade.

This arrangement is useful when your application already has a place to coordinate state and responses. If you want an adapter to manage session IDs, saving and SDK response types, use the local PHP SDK.

You can also call the engine returned by the factory directly. Choose that level when an operation needs an explicit presentation language, context updates during a choice, a session ID for runtime correlation, or deferred runtime events. The facade’s smaller signatures do not expose those options.

An engine is independent of where graph definitions are kept. A loader turns an identifier into the Graph the engine needs. Here, LocalGraphLoader looks for definitions in a directory controlled by your application:

use ExecKernel\Application\ExecKernelFacade;
use ExecKernel\Infrastructure\Engine\ExecKernelFactory;
use ExecKernel\Infrastructure\Loader\LocalGraphLoader;
use ExecKernel\SessionStore\FilesystemSessionStore;
$engine = (new ExecKernelFactory())->build();
$loader = new LocalGraphLoader(basePath: __DIR__ . '/graphs');
$facade = new ExecKernelFacade($engine, $loader);
$sessions = new FilesystemSessionStore(__DIR__ . '/var/sessions');

We will reuse the learning-choice example introduced in Anatomy of a graph. It starts at node 10: edge 101 selects a reading guide and reaches terminal 20; edge 102 selects practice and reaches terminal 30. Practice requires practiceEnabled: true. The complete definition includes English and Spanish presentation data.

The graph declares default_lang: en, so the facade examples below return English presentation text.

With this loader, learning-path resolves to graphs/learning-path.json; the definition’s graph_code must match that code. Keep the graph identifier under your application’s control: the same loader can also accept a direct file path. A graphRepository constructor argument can supply definitions as arrays; files take precedence when a matching file is found.

The store is a separate dependency of your service. It receives the state returned by the engine; it is not passed to the facade. Use a persistent directory outside the web server’s public directory if another request must recover the session.

Factory’s optional named arguments configure runtime responsibilities. For example, an eventBridge connects event handling, customRules registers rule classes and timeProvider supplies the clock. Those collaborators need their own application configuration. Creating a factory does not discover a graph directory, create a store or connect your business services automatically.

A start operation creates progress through a graph from its declared root. Initial context contains the facts your application wants the engine to use when evaluating choices.

The downloadable service below accepts a boolean that your application has already derived from its own data. Its start method performs three distinct actions:

public function start(bool $practiceEnabled): array
{
$result = $this->facade->start('learning-path', [
'practiceEnabled' => $practiceEnabled,
]);
$sessionId = bin2hex(random_bytes(16));
$this->save($sessionId, $result);
return $this->present($sessionId, $result);
}

First, start() loads the graph and evaluates the initial screen. The returned EngineResult contains state, a core SessionState with the current node, context and history, and payload, an array describing the screen. The state is what must survive; the payload is what your application presents now.

Next, the service creates an application session ID and saves the state under that ID. A core SessionState does not contain this storage key. Your application retains the association between the authenticated person and the ID so a later request can retrieve the correct session.

Finally, present() turns the result into your application’s view model. Keeping that transformation in the service lets a controller return JSON, render a template or select another response without exposing the entire persisted state.

The private save() helper checks that the store confirms the requested state:

$saved = $this->sessions->save($sessionId, $result->state);
if (!$saved->persisted || $saved->state->toArray() !== $result->state->toArray()) {
throw new RuntimeException('The session store did not confirm the requested state.');
}

Only after that check does this service return a successful screen. The distinction between a calculated result and a confirmed save is developed in Session stores and persistence modes.

A node payload contains presentation text and outgoing edges. The edge ID is the value your application submits when the person makes a choice; its label is the text you display.

This extract from present() prepares the choices for a template or JSON response:

$payload = $result->payload;
$choices = [];
foreach ($payload['edges'] as $edge) {
$choices[] = [
'edgeId' => $edge['id'],
'label' => $edge['labels'][0]['text'] ?? 'Continue',
'enabled' => $edge['enabled'],
'availability' => $edge['availability'],
];
}

With practiceEnabled: false, the title is “How would you like to learn?” and the application can render these controls:

Label Submitted edge ID Presentation
Read the guide 101 Enabled; availability is available.
Practise in the browser 102 Disabled; availability is blocked.

Availability describes the engine’s observation for this payload. Some graphs can return pending with enabled: true, meaning evaluation is deferred. Even an available option is checked again when chosen. Forward the edge ID to the engine instead of deciding the next node in your controller.

A terminal payload changes what the application presents. It contains outputs rather than edges. In this graph, selecting the guide returns a content output, “Read the guide at your own pace.”, and a URL output for https://example.org/learning/guide. Selecting practice returns a redirect destination.

The complete service adapts these output types to paragraphs, links and redirect fields. These are application view fields, not additional ExecKernel fields. A content output supplies text for your template; a URL output supplies a link; a redirect output supplies a destination your controller may use. ExecKernel does not send an HTTP redirect or open a browser. Your presentation code escapes text and applies your application’s policy for destinations.

A later request needs the session ID and the selected edge ID. Before calling the service, your application checks that the session belongs to the person making that request. The service loads its saved state, then gives that state to the facade:

public function choose(string $sessionId, int $edgeId): array
{
$state = $this->load($sessionId);
try {
$result = $this->facade->next($state->graphCode, $state, $edgeId);
} catch (ForbiddenEdgeException) {
$view = $this->resume($sessionId);
$view['notice'] = 'This option is unavailable. Choose another option.';
return $view;
}
$this->save($sessionId, $result);
return $this->present($sessionId, $result);
}

In the complete file, load() calls the store and throws SessionNotFoundException when the ID has no saved state. ForbiddenEdgeException is the core exception imported from ExecKernel\Exception.

For an accepted guide choice, next() returns a new state at node 20 with edge 101 in its history. The service saves that state before presenting the guide. It does not construct the next state from form fields.

If a stale interface submits practice while practiceEnabled is false, the engine throws ForbiddenEdgeException. No new state reaches this service’s save(). The handler reloads the existing session, rebuilds its screen and adds an application message. Other failures propagate so your application can handle them according to their cause; a storage failure is not treated as an unavailable choice.

To redisplay a session without submitting a choice, the service uses:

$state = $this->load($sessionId);
$result = $this->facade->resume($state->graphCode, $state);

resume() receives an existing state and returns an EngineResult for it; it does not fetch from the store or choose another edge. It still checks runtime requirements such as graph compatibility and session validity. When calling the engine directly, getPayload($graph, $state, $lang) produces just the presentation array. That method also needs a graph and state already available to your application.

The facade uses the graph’s default_lang for start, next and resume. Setting a context key called lang does not select the presentation language. For this definition, facade responses are in English. Use an explicit language with the engine, or the local SDK’s language arguments, when each person should receive a different language.

Coordinate persistence and effects deliberately

Section titled “Coordinate persistence and effects deliberately”

The example installs no listeners that perform external work and assumes requests for one session are handled sequentially. Those assumptions make its save-and-present sequence useful without suggesting a transaction that the facade does not provide.

Facade calls use the engine’s normal event delivery: runtime events are published before the call returns. Saving $result->state afterwards cannot undo a listener that has already sent a message or changed another system.

When successful runtime events must wait for a confirmed save, call the engine directly with deferEvents: true. Confirm the store result, then publish $result->eventBatch; discard the batch if saving fails. The local SDK adapter already coordinates that ordering. Deferred events do not turn rule execution and storage into one transaction, or make external effects happen exactly once. Connect such effects to your application’s idempotency or durable delivery mechanism. Events and listeners explains the event side of this relationship.

Persistence also does not by itself serialize concurrent requests. FilesystemSessionStore writes state files, but it does not compare the state read by two concurrent requests before saving. For simultaneous choices, select the store and coordination strategy described in Concurrency and session revisions. In particular, adding a runtime lock cannot make the facade’s later application save part of that lock.

Download direct-learning-service.php and the learning-path graph. The PHP file contains the complete composition, state loading and saving, choice recovery and view adaptation shown above.

Place the service alongside your application’s vendor/autoload.php, and keep the graph as graphs/learning-path.json. Your application can include the file and construct the service with its own directories:

require __DIR__ . '/direct-learning-service.php';
$service = DirectLearningService::fromDirectories(
__DIR__ . '/graphs',
__DIR__ . '/var/sessions',
);
$view = $service->start(practiceEnabled: false);

Call choose($sessionId, $edgeId) for a submitted choice and resume($sessionId) to reopen the screen. The service returns a view model; your controller owns the actual response and the association between a session and its user.

The file also has an optional executable demonstration:

Terminal window
php direct-learning-service.php ./graphs ./var/sessions

It prints the initial choice screen, the same screen with a rejected-practice notice, the selected guide, and the guide recovered through a new service instance. The stored session remains available after the program exits. Reading those operations in the service is sufficient to understand the integration; running them is a way to exercise the same application behavior.