Payload output hooks
An output hook is a PHP component that ExecKernel calls after preparing a payload. It receives that array and returns the presentation data your application will receive. You can use a hook to add a summary, a contextual hint or a view-specific calculation without adding those calculations to the graph definition.
The payload still describes the session’s current position. Returning a different presentation does not select an edge or update the session’s context and history. Your application remains responsible for turning the returned data into a screen.
We will return to the learning-path graph from Anatomy of a graph. At node 10, edge 101 offers a guide and edge 102 offers browser practice when practiceEnabled is true. Here we add a help message that tells the person how many options are available.
For fixed instructions, node metadata can already carry text and extras. A hook is useful in this example because the message depends on the availability calculated for the current payload.
See what the hook adds
Section titled “See what the hook adds”With practiceEnabled: false, the guide is available and practice is blocked. Before the hook, these selected fields describe the node:
{ "type": "node", "node_id": 10, "extras": { "screen": "learning-choice" }, "edges": [ { "id": 101, "enabled": true }, { "id": 102, "enabled": false } ]}The hook counts the enabled choices and adds one property inside extras. The same fields after the hook are:
{ "type": "node", "node_id": 10, "extras": { "screen": "learning-choice", "learningHelp": { "availableChoices": 1, "text": "1 option is available. Choose it to continue." } }, "edges": [ { "id": 101, "enabled": true }, { "id": 102, "enabled": false } ]}Only extras.learningHelp is new. The existing screen value, node ID and edge availability are preserved. When the current payload has two enabled choices, the message becomes “2 options are available. Choose one to continue.” The hook reads the engine’s result; it does not evaluate the conditions again.
Implement the transformation
Section titled “Implement the transformation”Implement PayloadOutputHookInterface and return the complete payload from apply(). Its arguments give the hook the context needed to produce the view:
| Argument | Available information |
|---|---|
$graph |
The loaded graph, including its identity and presentation definitions. |
$state |
The session snapshot used for this presentation: current node, context and history. |
$lang |
The requested language. The hook supplies its own translated text. |
$payload |
The payload prepared by the engine, or the result returned by an earlier hook. |
This hook limits its work to decision nodes in learning-path. It counts only entries whose enabled value is exactly true, chooses an English or Spanish message, and adds that message without replacing the other extra data:
use ExecKernel\Domain\Engine\PayloadOutputHookInterface;use ExecKernel\Domain\Graph\Graph;use ExecKernel\Domain\Session\SessionState;
final class HelpOutputHook implements PayloadOutputHookInterface{ public function apply(Graph $graph, SessionState $state, string $lang, array $payload): array { if ($graph->graphCode !== 'learning-path' || ($payload['type'] ?? null) !== 'node') { return $payload; }
$count = count(array_filter( $payload['edges'], static fn (array $edge): bool => ($edge['enabled'] ?? false) === true, )); $message = $lang === 'es' ? match ($count) { 0 => 'No hay opciones disponibles en este momento.', 1 => 'Hay 1 opción disponible. Elígela para continuar.', default => "Hay {$count} opciones disponibles. Elige una para continuar.", } : match ($count) { 0 => 'No options are currently available.', 1 => '1 option is available. Choose it to continue.', default => "{$count} options are available. Choose one to continue.", };
$payload['extras'] ??= []; if (!is_array($payload['extras']) || array_key_exists('learningHelp', $payload['extras'])) { throw new \RuntimeException('The learningHelp presentation key is already in use.'); } $payload['extras']['learningHelp'] = [ 'availableChoices' => $count, 'text' => $message, ];
return $payload; }}The graph and payload checks make the hook return unrelated results unchanged, including this graph’s terminals. This matters when an engine instance presents more than one graph.
The learningHelp property belongs to this extension. If another part of the application already uses it, the hook raises an error instead of silently overwriting that data. Use a similarly distinct property for your own extension.
$state is part of the interface even though this particular calculation needs only the supplied payload. Other hooks may read the context to prepare a summary. Keep that work about presentation: the return value is a payload array, not a replacement session state.
Register the hook before using the engine
Section titled “Register the hook before using the engine”A plugin connects the hook class to the registry. In the following code, register() adds the class and provides.outputs declares the same class in the manifest. The registry constructs HelpOutputHook when the engine consumes the registered hooks; this class needs no constructor arguments.
use ExecKernel\Domain\Engine\PluginInterface;use ExecKernel\Domain\Engine\PluginRegistry;use ExecKernel\Domain\Versioning\CompatibilityMode;
final class HelpOutputPlugin implements PluginInterface{ public function register(PluginRegistry $registry): void { $registry->addOutputHook(HelpOutputHook::class); }
public function boot(): void {}}
$plugins = new PluginRegistry( engineVersion: '0.2.0', compatibilityMode: CompatibilityMode::STRICT,);$plugins->registerPlugin(new HelpOutputPlugin(), [ 'name' => 'learning-help', 'version' => '1.0.0', 'requires' => ['execkernel' => '0.2.0'], 'provides' => ['outputs' => [HelpOutputHook::class]],]);Here engineVersion: '0.2.0' is the compatibility value supplied by your application, and the manifest requires that exact value. STRICT makes a mismatch fail registration. Complete registration before constructing the engine or loading a graph through the registry: consuming its extensions seals it. Plugin architecture and lifecycle explains that lifecycle and registration with dependencies.
To compare the result, use the same session with an ordinary engine and an engine that has the plugin. In this fragment, $graph is the loaded learning-path graph:
use ExecKernel\Domain\Session\Context;use ExecKernel\Infrastructure\Engine\ExecKernelFactory;
$plainEngine = (new ExecKernelFactory())->build();$engine = (new ExecKernelFactory())->build(pluginRegistry: $plugins);
$started = $plainEngine->start($graph, 'en', new Context(['practiceEnabled' => false]));$before = $started->payload;$after = $engine->getPayload($graph, $started->state, 'en');$after contains the added help shown above. getPayload() presents the existing session; it leaves the state at node 10 with the same context and history. If the person later chooses an available edge, your application makes its normal choose() call.
Display the help in your application
Section titled “Display the help in your application”Your existing view can keep rendering the title and choices. Add a place for the help text:
<p id="learning-help" aria-live="polite" hidden></p>The following function reads the new property, displays it as text and clears an earlier message when the next payload has no help. Call it when your view receives a fresh payload:
export function renderLearningHelp(payload, element) { const help = payload.extras?.learningHelp; const text = typeof help?.text === "string" ? help.text : ""; element.textContent = text; element.hidden = text === "";}renderLearningHelp(payload, document.getElementById("learning-help"));The illustration shows one possible view before and after the application uses the extra data. The disabled practice option stays disabled in both views.
Keep the payload consistent with execution
Section titled “Keep the payload consistent with execution”ExecKernel calls registered hooks in order after building the normal payload and before adding debug information and checking the final payload size. A later hook receives the array returned by the previous one, so give each extension a clear responsibility and avoid competing for the same property.
The engine checks that the returned type and node_id still describe the current node. It rejects invented edges or changed edge endpoints, and it restores each returned edge’s availability from the engine’s own calculation. A terminal payload cannot contain outgoing edges; terminal outputs must satisfy their registered type’s validator. Returned data must also remain representable as plain declarative values and fit the payload budget.
These checks preserve the execution contract, but the application still owns the meaning and rendering of its extra fields. Keep this hook focused on useful text. A help message is not authorization, and hiding a choice in a view does not change the graph’s conditions.
Complete example and a larger presentation hook
Section titled “Complete example and a larger presentation hook”The complete PHP example includes the hook, plugin, manifest, graph loading and before/after payloads. It uses your project’s Composer autoloader and expects the learning-path.json beside it; its optional arguments select en or es and an alternative graph path. The small view function can be included in your application’s JavaScript module. The result above can be understood without executing these files.
For a richer example, open Chart Lab. Its ChartPayloadHook calculates series and statistics in extras.chart; the application’s chart component renders those data. The demo’s Source code viewer shows the hook and plugin registration. The chart appears because the application implements that view.
To give a terminal result its own type and interpretation, continue with Custom terminal output types.