Remote PHP SDK
The remote PHP SDK connects your PHP application to an ExecKernel API. The API loads the graph, evaluates each choice and saves the session. Your application keeps the session identifier, sends input and turns the returned payload into a screen or another application action.
Use this client when the engine runs in a separate service. If your PHP application should load graphs and own the session store directly, use the local PHP SDK. Both approaches can return similar presentation data, but the remote client accesses the saved execution through HTTP.
Establish the service contract
Section titled “Establish the service contract”You need the PHP package in your application and a reachable API with a session store and the required graph in its catalogue. The Remote PHP Quick Start explains the initial connection; the HTTP API Quick Start covers preparing the service.
The connection has two settings:
| Setting | Meaning |
|---|---|
EXECKERNEL_BASE_URL |
The service root, such as https://api.example.org. The SDK appends its /execkernel/… paths. |
EXECKERNEL_API_TOKEN |
The deployment’s Bearer credential. Keep it in the server environment that runs this PHP code. |
The token authorizes calls to the service. A session identifier selects one execution within that service. Associate that identifier with the appropriate user or application record and check access in your own request handler.
To illustrate this separation, we reuse the learning-path graph introduced in Anatomy of a graph. It offers a guide or a browser exercise: node 10 presents the choices, edge 101 reaches the guide at node 20, and edge 102 reaches the exercise at node 30 only when practiceEnabled is true. This is an example of turning application facts into available choices.
The service must already serve learning-path. Its catalogue-ready JSON adds graph_id: 7006 to the graph from that chapter because the standalone API’s catalogue requires a positive numeric identity. The HTTP integration guide explains that catalogue entry. The remote PHP application sends the graph’s code; it does not need a local graph loader or upload the JSON.
Configure the client and its transport
Section titled “Configure the client and its transport”Config describes the connection. ExecKernelHttpClient uses it to send requests and convert successful responses into typed PHP objects:
use ExecKernel\Client\ExecKernelHttpClient;use ExecKernel\Config\Config;
$baseUrl = getenv('EXECKERNEL_BASE_URL');$token = getenv('EXECKERNEL_API_TOKEN');
if (!$baseUrl || !$token) { throw new RuntimeException('Set EXECKERNEL_BASE_URL and EXECKERNEL_API_TOKEN.');}
$config = new Config( baseUrl: $baseUrl, authToken: $token, timeoutSeconds: 5,);$client = new ExecKernelHttpClient($config);The default HttpTransport uses PHP streams and requires allow_url_fopen. It applies timeoutSeconds to the stream; the default is 10 seconds when you omit the setting. The client adds the Bearer header and JSON encoding for you. Retries are disabled by default.
You can supply GuzzleTransport when your application uses a PSR-18 HTTP client. Configure timeouts on that injected client: GuzzleTransport does not apply Config::timeoutSeconds() to it.
use ExecKernel\Client\GuzzleTransport;use GuzzleHttp\Client;use GuzzleHttp\Psr7\HttpFactory;
$http = new Client(['timeout' => 5.0, 'connect_timeout' => 2.0]);$factory = new HttpFactory();$transport = new GuzzleTransport($config, $http, $factory, $factory);$client = new ExecKernelHttpClient($config, $transport);This replaces the transport used by the earlier client. The session operations stay the same. For retry eligibility, timeout exceptions and uncertain delivery, see Client errors, transport and diagnostics; choosing a different transport can change how connection failures are classified.
Start an execution and build the choices
Section titled “Start an execution and build the choices”Your application supplies the facts the graph needs. Here, it has decided that practice is unavailable, so it starts a session with a false Boolean value:
$state = $client->start( 'learning-path', ['practiceEnabled' => false], 'en',);$sessionId = $state->sessionId;The API creates and stores the execution, then the client returns a SessionStateDTO. Its sessionId is the identifier to retain; nodeId, context and history describe the returned position. The payload contains the data to present there, while isTerminal tells your application whether the graph has reached an end.
With the standalone API, context values must be strings, finite numbers or Booleans under string keys. Nested arrays, objects and null values are rejected even if a PHP helper can represent them. Supply the individual facts the graph uses, such as practiceEnabled, instead of sending an entire application entity.
At node 10, the payload is a NodePayloadDTO. Its title becomes the heading, and each edge becomes a selectable control:
use ExecKernel\DTO\NodePayloadDTO;
$payload = $state->payload;if (!$payload instanceof NodePayloadDTO) { throw new LogicException('Expected the learning choices.');}
$view = [ 'title' => $payload->title, 'choices' => array_map(static fn (array $edge): array => [ 'edgeId' => $edge['id'], 'label' => $edge['labels'][0]['text'] ?? (string) $edge['id'], 'enabled' => $edge['enabled'], ], $payload->edges),];The resulting view contains:
{ "title": "How would you like to learn?", "choices": [ {"edgeId": 101, "label": "Read the guide", "enabled": true}, {"edgeId": 102, "label": "Practise in the browser", "enabled": false} ]}Your template can render one button per choice and disable the second button. Keep the integer edge identifier with each control so the submitted value expresses the selected transition. The API still checks that transition when it receives the choice.
Send a choice and use the new payload
Section titled “Send a choice and use the new payload”After validating the submitted choice in your request handler, pass its edge identifier to navigate(). Selecting the guide looks like this:
$state = $client->navigate($state, 101);The client sends the session identifier and edge 101. The API loads its saved state, evaluates the transition and stores the result at node 20. Assigning the returned DTO to $state gives your application the confirmed result. A previous DTO remains a local representation of an earlier response; editing client data does not replace the server’s saved session.
The new payload is a TerminalPayloadDTO. Its outputs describe what the application can present after the graph finishes:
use ExecKernel\DTO\TerminalPayloadDTO;
$payload = $state->payload;if (!$payload instanceof TerminalPayloadDTO) { throw new LogicException('Expected the selected learning resource.');}
$messages = [];foreach ($payload->outputs as $output) { if ($output['type'] === 'content' && is_string($output['content'] ?? null)) { $messages[] = $output['content']; }}Here, $messages contains “Read the guide at your own pace.” The same payload includes a url output for the guide. The complete example below prepares text, links and a possible redirect as view data. Your application renders or acts on that data; the SDK does not open a browser or navigate it. The example’s example.org URLs illustrate the output shapes and should be replaced with your application’s resource locations.
If application facts have changed, navigate() can also submit a context patch as its third argument. This reuses the candidate values introduced in Context updates and candidate values: facts proposed for this choice become part of the saved result only if the transition is accepted. For example, from the question node, $client->navigate($state, 102, ['practiceEnabled' => true]) proposes enabling practice for that choice. Your backend must establish that fact before sending it. The API evaluates the proposed values together with the saved context; a rejected choice does not confirm them.
Recover the execution in a later request
Section titled “Recover the execution in a later request”Save $sessionId with your application’s record. A subsequent PHP request can build another client with the same connection settings and obtain the current payload without retaining the earlier DTO:
$state = $client->resume($sessionId);$payload = $state->payload;After selecting the guide, nodeId is still 20 and the payload describes that result. resume() does not take another edge. Availability depends on the API’s session store and retention policy.
For a small position check, use $client->status($sessionId): it returns a SessionStatusDTO with currentNode and nodeStatus. Use resume() when you need the full presentation payload. Once your application no longer needs the saved execution, $client->destroy($sessionId) requests its deletion and returns a Boolean confirmation.
Handle a rejected or uncertain call
Section titled “Handle a rejected or uncertain call”SDK operations report failures through ExecKernelException subclasses. Use code() to choose application behavior and details() for available HTTP and trace information. The API maps a blocked edge to EK-RULE-403; your application can recover the question and explain that the option is unavailable.
If a connection fails after a choice was sent, the API may already have saved it. Keep the known session identifier and recover the session before deciding whether another transition is needed. A successful start() supplies a new server-generated identifier, so losing that response is a different case: this API does not provide a client-supplied start identifier or an idempotency key. The diagnostics guide develops these recovery decisions.
Complete PHP example
Section titled “Complete PHP example”The complete program combines the connection, view adapter and session operations. With your PHP package already installed, put it next to vendor/ and run it using the configured connection:
php remote-learning.phpEXECKERNEL_LANG=es php remote-learning.phpIt prints the choices, the guide result, the resumed view and a terminal status at node 20, then confirms deletion of its demonstration session. The guide choice is automatic in this program; in your application it comes from the submitted form. Retain the session for as long as your application needs it, and perform deletion as an explicit lifecycle decision.
Complete PHP program
<?php
declare(strict_types=1);
require __DIR__ . '/vendor/autoload.php';
use ExecKernel\Client\ExecKernelHttpClient;use ExecKernel\Config\Config;use ExecKernel\DTO\NodePayloadDTO;use ExecKernel\DTO\SessionStateDTO;use ExecKernel\DTO\TerminalPayloadDTO;use ExecKernel\Exceptions\ExecKernelException;
function learningView(SessionStateDTO $state): array{ $payload = $state->payload; $view = [ 'sessionId' => $state->sessionId, 'nodeId' => $state->nodeId, 'title' => $payload?->title, ];
if ($payload instanceof NodePayloadDTO) { return $view + [ 'kind' => 'choices', 'choices' => array_map(static fn (array $edge): array => [ 'edgeId' => $edge['id'], 'label' => $edge['labels'][0]['text'] ?? (string) $edge['id'], 'enabled' => $edge['enabled'], ], $payload->edges), ]; }
if ($payload instanceof TerminalPayloadDTO) { $messages = []; $links = []; $redirect = null;
foreach ($payload->outputs as $output) { if ($output['type'] === 'content' && is_string($output['content'] ?? null)) { $messages[] = $output['content']; } elseif ($output['type'] === 'url' && is_string($output['url'] ?? null)) { $links[] = [ 'url' => $output['url'], 'label' => $output['label'] ?? $output['url'], ]; } elseif ($output['type'] === 'redirect' && is_string($output['url'] ?? null)) { $redirect = $output['url']; } }
return $view + [ 'kind' => 'result', 'messages' => $messages, 'links' => $links, 'redirect' => $redirect, ]; }
throw new RuntimeException('The API did not return a displayable payload.');}
$baseUrl = getenv('EXECKERNEL_BASE_URL');$token = getenv('EXECKERNEL_API_TOKEN');$lang = getenv('EXECKERNEL_LANG') ?: 'en';
if (!$baseUrl || !$token) { throw new RuntimeException('Set EXECKERNEL_BASE_URL and EXECKERNEL_API_TOKEN.');}
$client = new ExecKernelHttpClient(new Config( baseUrl: $baseUrl, authToken: $token, timeoutSeconds: 5,));
$sessionId = null;
try { $state = $client->start('learning-path', ['practiceEnabled' => false], $lang); $sessionId = $state->sessionId; $choices = learningView($state);
// In a request handler, take the edge ID from the validated submitted choice. $state = $client->navigate($state, 101); $result = learningView($state);
// A later request needs the retained identifier, not the previous DTO. $resumed = $client->resume($sessionId); $status = $client->status($sessionId);
// This demonstration removes its session after reading the result. $deleted = $client->destroy($sessionId);
echo json_encode([ 'choices' => $choices, 'result' => $result, 'resumedView' => learningView($resumed), 'status' => [ 'currentNode' => $status->currentNode, 'nodeStatus' => $status->nodeStatus, ], 'deleted' => $deleted, ], JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE | JSON_THROW_ON_ERROR), PHP_EOL;} catch (ExecKernelException $error) { fwrite(STDERR, json_encode([ 'sessionId' => $sessionId, 'code' => $error->code(), 'message' => $error->getMessage(), 'http' => $error->details()['http'] ?? null, 'traceId' => $error->details()['trace_id'] ?? null, ], JSON_UNESCAPED_UNICODE | JSON_THROW_ON_ERROR) . PHP_EOL); exit(1);}