Local PHP SDK
The local PHP SDK connects your application’s session operations to an ExecKernel engine running in the same PHP process. Your application starts a session, submits a choice or asks for the current screen. The SDK’s local adapter loads the graph, retrieves the saved state when needed, calls the engine and confirms a save before returning a successful start or choice.
The client presents those results as PHP objects. This lets your application work with a session ID and typed payloads while the adapter coordinates the underlying engine and store. Your application still chooses the store, authorizes access to each session and decides how to present the response.
This guide assumes the local PHP integration is already available through your autoloader; see Installation and requirements for setup.
Configure the client, adapter and store
Section titled “Configure the client, adapter and store”The local integration has three separate responsibilities:
| Component | Responsibility |
|---|---|
ExecKernelLocalClient |
Offers session operations, converts returned arrays into SDK DTOs and exposes SDK exceptions. A DTO is a typed object carrying response data. |
ExecKernelLocalAdapter |
Implements the client’s LocalEngineInterface port using the real PHP engine, a graph loader and a session store. |
SessionStoreInterface |
Saves, loads and deletes core SessionState objects. These are the persisted engine states, not the SDK DTOs shown to your application. |
For graphs and sessions stored in directories, the bootstrap composes the standard adapter:
use ExecKernel\Bootstrap\ExecKernelLocalBootstrap;use ExecKernel\Client\ExecKernelLocalClient;
$adapter = ExecKernelLocalBootstrap::fromFilesystem( graphDirectory: __DIR__ . '/graphs', sessionDirectory: __DIR__ . '/var/sessions',);$client = new ExecKernelLocalClient($adapter);fromFilesystem() returns an ExecKernelLocalAdapter. Wrapping it in ExecKernelLocalClient gives you typed responses. The client constructor expects LocalEngineInterface; the core ExecKernel engine itself is not that port.
The bootstrap creates a factory-built engine, a LocalGraphLoader and a FilesystemSessionStore.
We will reuse the learning-choice graph introduced in Anatomy of a graph. At node 10, edge 101 selects a reading guide and reaches terminal 20. Edge 102 selects practice and reaches terminal 30, provided practiceEnabled is true. The complete graph definition contains English and Spanish text.
A graph code such as learning-path resolves to graphs/learning-path.json. Keep that code under application control: the underlying loader also accepts file paths. Its optional graphRepository argument supplies array definitions when no matching file is found.
The session directory must be writable and accessible to the PHP processes that will continue those sessions. Put it outside the web server’s public directory and retain it for as long as sessions should remain recoverable. A new client can use the same stored state; an empty or temporary directory changes that lifetime.
If your application already has a configured engine, loader and store, construct the adapter explicitly. Here, $engine is your configured core engine, $loader implements GraphLoaderInterface and $sessions implements the core SessionStoreInterface:
use ExecKernel\Client\ExecKernelLocalAdapter;
$client = new ExecKernelLocalClient( new ExecKernelLocalAdapter($engine, $loader, $sessions),);This is where you supply the application dependencies described in Embedding the engine · Factory and Facade. You do not need a facade between the adapter and the engine.
Start a session and retain its identity
Section titled “Start a session and retain its identity”A session records one person’s progress through a graph. Starting creates that state, saves it and returns the first response. The start() parameter named flowId receives the graph code in this example.
Your application decides whether practice is enabled and selects the presentation language:
$state = $client->start( 'learning-path', ['practiceEnabled' => false], 'en',);
$sessionId = $state->sessionId;The returned SessionStateDTO gives you:
| Property | Use in your application |
|---|---|
sessionId |
Retain this value to continue or recover the session. |
nodeId, isTerminal |
Identify the current position and whether the graph has reached a terminal. |
context, history |
Read the returned context and navigation history. These arrays describe the response; changing client data does not replace the store. |
payload |
Present the current choice or terminal result through NodePayloadDTO or TerminalPayloadDTO. The general DTO type also permits null. |
lang |
Know the language used to build this response. |
Associate sessionId with the authenticated person’s application session or record. The graph store does not decide which user may access an ID. Check that association before accepting choices, resuming or deleting a session.
The language belongs to the generated response. Navigation carries the current DTO’s lang, but core SessionState does not store it. Keep the person’s language preference in your application and pass it to resume() on later requests. With the standard adapter, omitting it selects the graph’s default language, with a fallback to the first allowed language when no default is declared.
Adapt the typed payload to your view
Section titled “Adapt the typed payload to your view”A node payload describes a screen with choices. Its title and description are object properties; its edges remain arrays with the engine’s field names.
use ExecKernel\DTO\NodePayloadDTO;use ExecKernel\DTO\TerminalPayloadDTO;
$payload = $state->payload;
if ($payload instanceof NodePayloadDTO) { $choices = []; foreach ($payload->edges as $edge) { $choices[] = [ 'edgeId' => $edge['id'], 'label' => $edge['labels'][0]['text'] ?? 'Continue', 'enabled' => $edge['enabled'], 'availability' => $edge['availability'], ]; }
$view = [ 'screen' => 'choice', 'title' => $payload->title, 'description' => $payload->description, 'choices' => $choices, ];}For the initial context above, your application displays “How would you like to learn?”, enables “Read the guide” and disables “Practise in the browser”. A button submits its edgeId; the controller does not submit a destination node.
Keep the availability information when adapting the response. available means the current observation allows the option, blocked disables it, and pending leaves evaluation for the choice operation. A pending edge can have enabled: true. The engine still evaluates the submitted choice; the displayed state is not a permanent authorization.
A terminal payload supplies outputs for your application to use. This fragment extracts the text and links from the guide result:
if ($payload instanceof TerminalPayloadDTO) { $paragraphs = []; $links = [];
foreach ($payload->outputs as $output) { if ($output['type'] === 'content') { $paragraphs[] = $output['content']; } elseif ($output['type'] === 'url') { $links[] = [ 'url' => $output['url'], 'label' => $output['label'], ]; } }
$view = [ 'screen' => 'result', 'title' => $payload->title, 'paragraphs' => $paragraphs, 'links' => $links, ];}After selecting the guide, the title is “Guide selected”, the paragraph is “Read the guide at your own pace.” and the link points to https://example.org/learning/guide. The complete service also handles the practice terminal’s redirect output by exposing its destination to the controller.
These examples build an application view model. Your templates render text with their normal escaping, and your controller decides whether an allowed redirect should become an HTTP response. Reading an output does not execute it. If your integration receives a DTO with payload === null, treat it as insufficient data for a screen; the complete service makes that case explicit.
Submit a choice and recover the current screen
Section titled “Submit a choice and recover the current screen”When your application still has the DTO returned by start, it can navigate directly:
$next = $client->navigate($state, 101);The adapter takes the session ID from that DTO and loads the authoritative state from the store. It evaluates edge 101 against that state, saves the new state and returns a fresh DTO. The original $state object remains the previous response; use $next to present the result.
In another request, your application usually retains only the session ID and the person’s language. Recover the current response first:
$current = $client->resume($sessionId, 'en');$next = $client->navigate($current, 101);Here, resume() loads the stored state and regenerates its payload. The standard adapter does not save during this operation, and no edge is selected. Runtime checks can still reject the resume, for example when the session is no longer valid for the loaded graph.
The SDK client has no separate get() or getPayload() operation. Use resume() when your screen needs a session and its payload; use status() when a small position summary is enough.
A choice can also include context updates:
$next = $client->navigate( $current, 102, ['practiceEnabled' => true],);Only send that update after your application has established that practice should now be enabled. The adapter passes the updates to the engine, which evaluates the choice with the candidate context and saves the accepted result. Passing arbitrary form fields as this array would let request data decide facts your application should control. Editing $current->context or importing a client snapshot is not the mechanism for updating persisted context.
The default local adapter constructs the core Context with its standard policy. Use string keys and scalar values such as booleans, integers, finite floats and text. Arrays and null are rejected by that runtime policy even when an SDK helper or DTO can represent them. A builder producing data successfully does not establish that the engine accepts it; Builders, payloads and session snapshots develops that boundary.
Recover after a known rejection
Section titled “Recover after a known rejection”A stale screen can submit practice even though the saved context says it is disabled. The engine rejects that choice with EK-SEC-NAV-002. The standard local adapter does not save a new state for this rejected calculation.
Catch the SDK’s exception base class and branch on the code. In the complete service, $this->present() is the response adaptation described above:
use ExecKernel\Exceptions\ExecKernelException;
try { $next = $this->client->navigate($state, $edgeId, $trustedContext);} catch (ExecKernelException $error) { if ($error->code() !== 'EK-SEC-NAV-002') { throw $error; }
$view = $this->present($this->client->resume($sessionId, $lang)); $view['notice'] = 'This option is unavailable. Choose another option.'; return $view;}For this graph’s blocked practice choice, recovery returns node 10 with the guide still available. Your application shows the notice beside the refreshed choices. It does not silently select the guide or turn the rejected context into saved state.
The base class is ExecKernel\Exceptions\ExecKernelException, with plural Exceptions. It differs from the core’s ExecKernel\Exception\ExecKernelException. The local SDK mapper can use ExecKernelRemoteErrorException for this security rejection; that class name does not mean an HTTP request occurred. Read code(), context() and hint() to decide what happened, and keep diagnostic details separate from the message shown to the person.
Input rejection is a different case. For example, sending ['practiceEnabled' => null] during navigation produces EK-SESSION-002 under the standard runtime policy and leaves the saved state unchanged. Correct the application data before trying again.
A failed save is different again. The adapter requires the store to confirm the same state and maps an unconfirmed save to EK-SYS-002. A store might have committed before losing its acknowledgement, so that error does not prove that the old state is still stored. Recover the stored session before deciding what to do next, and do not automatically repeat the choice. See Client errors, transport and diagnostics for those decisions.
Use the operation that answers your question
Section titled “Use the operation that answers your question”| Operation | Required data | Returned value and purpose |
|---|---|---|
start($flowId, $context, $lang) |
Graph code; optional context and language. | SessionStateDTO for a new saved session. |
navigate($state, $edgeId, $context) |
A session DTO, the chosen edge ID and optional context updates. | A new SessionStateDTO after the accepted choice has been saved. |
resume($sessionId, $lang) |
Session ID and optional language. | SessionStateDTO with the current payload rebuilt from storage. |
status($sessionId) |
Session ID. | SessionStatusDTO: currentNode, nodeStatus and logsTail. The standard local adapter reports active or terminal and a null logs tail. |
inspect($flowId) |
Graph code. | GraphInspectionDTO with node, edge and label arrays; it does not start a session. |
destroy($sessionId) |
Session ID. | true when deletion is confirmed. With the standard store, deleting an already absent session also succeeds. |
Here, active and terminal classify the current node. status() does not perform the full resume checks or rebuild a screen.
After deletion, resume() cannot recover that session and reports EK-SESSION-001. There is no payload in the status summary; it cannot replace the response your screen needs.
Complete application service and persistence choice
Section titled “Complete application service and persistence choice”Download local-learning-service.php and the learning-path graph. The complete service composes the client, adapts both payload types, handles the known rejection and exposes start, choose, resume, status and destroy operations.
Place the PHP file beside your application’s vendor/autoload.php and the graph at graphs/learning-path.json. Your application can include and use the service:
require __DIR__ . '/local-learning-service.php';
$service = LocalLearningService::fromDirectories( __DIR__ . '/graphs', __DIR__ . '/var/sessions',);$view = $service->start(practiceEnabled: false, lang: 'en');On a later request, call choose($sessionId, $edgeId, $lang). The optional fourth argument supplies context updates already validated by your application. Use resume($sessionId, $lang) to reopen the screen without choosing.
The adapter coordinates saving and deferred runtime events: successful start and choice events are published after the store confirms the requested state. When a store supports conditional writes through ConditionalSessionStoreInterface, the adapter uses that capability. The filesystem store used here does not provide it, so this example assumes sequential requests per session. A filesystem write alone does not prevent two requests from calculating from the same earlier state.
For sessions used concurrently, choose the persistence and coordination strategy described in Session stores and persistence modes and Concurrency and session revisions. Your application also remains responsible for coordinating business effects outside the runtime event batch.
To exercise the complete service, the file has an optional demonstration:
php local-learning-service.php ./graphs ./var/sessions enIt prints the initial choices, a rejected-practice notice, the selected guide, recovery through a new client, the terminal status and the confirmed deletion. Pass es to receive the graph’s Spanish text. The sequence shows how the application responds at each step; the reusable service can be included without running that demonstration.