Skip to content

Building graphs programmatically in PHP

A PHP application can create a graph directly from objects. This is useful when your code assembles a definition from configuration or a catalog of steps. Your application builds the nodes, connections and associated data; ExecKernel uses that definition to evaluate the choices available during a run.

This tutorial recreates the learning-path graph introduced in Anatomy of a graph. Its root, node 10, offers two choices: edge 101 leads to the guide at terminal 20, and edge 102 leads to practice at terminal 30. The practice choice requires the application to provide practiceEnabled: true in the session context. We will construct the same definition in PHP, check it and select a choice.

The code assumes an existing project with ExecKernel and the Composer autoloader available. See Installation and requirements if you need that setup. The complete program is available at the end; the fragments below explain its parts.

The learning-path graph: root 10 offers the guide through edge 101 and practice through edge 102; practice requires practiceEnabled to be true.

Node identifies a point in the process. Its isTerminal flag marks a point where navigation ends. Edge identifies a directed connection and names its origin and destination.

use ExecKernel\Domain\Graph\Edge;
use ExecKernel\Domain\Graph\Node;
$nodes = [
10 => new Node(id: 10),
20 => new Node(id: 20, isTerminal: true),
30 => new Node(id: 30, isTerminal: true),
];
$edges = [
10 => [
new Edge(id: 101, fromNode: 10, toNode: 20),
new Edge(id: 102, fromNode: 10, toNode: 30),
],
];

The keys in $nodes let us identify each node. The key 10 in $edges has a different purpose: it groups the connections that leave node 10. Inside that group, 101 and 102 identify the choices themselves. Your application will submit an edge ID when it asks the engine to select a choice.

The terminal nodes have no outgoing connections. We have created their structure, but have not yet supplied the titles, choice text or final results that an application can present.

Give the application titles and choice text

Section titled “Give the application titles and choice text”

Node presentation belongs in Metadata; the text of a choice belongs in EdgeLabel. Both records name the item they describe and the language of their text. The engine can then return the appropriate presentation when your application requests a payload in that language.

Here is the root’s English metadata record from the complete definition:

use ExecKernel\Domain\Graph\Metadata;
$rootEnglish = new Metadata(
id: 1,
nodeId: 10,
lang: 'en',
title: 'How would you like to learn?',
description: 'Choose a guide to read or an exercise to try.',
extras: ['screen' => 'learning-choice'],
);

nodeId attaches this title to node 10. id identifies the metadata record itself; the PHP constructor requires it. JSON import can allocate these internal record IDs when they are omitted. The extras array carries application data: here, your application could use screen to choose a view. ExecKernel carries that value with the presentation; your application decides what it means.

Group the records by node and then by language. The root’s English record belongs at $metadata[10]['en']; the remaining records supply the Spanish root and both terminal titles:

$metadata = [
10 => [
'en' => $rootEnglish,
'es' => new Metadata(
id: 2, nodeId: 10, lang: 'es',
title: '¿Cómo quieres aprender?',
description: 'Elige una guía para leer o un ejercicio para practicar.',
extras: ['screen' => 'learning-choice'],
),
],
20 => [
'en' => new Metadata(
id: 3, nodeId: 20, lang: 'en',
title: 'Guide selected', extras: ['mode' => 'guide'],
),
'es' => new Metadata(
id: 4, nodeId: 20, lang: 'es',
title: 'Guía seleccionada', extras: ['mode' => 'guide'],
),
],
30 => [
'en' => new Metadata(
id: 5, nodeId: 30, lang: 'en',
title: 'Practice selected', extras: ['mode' => 'practice'],
),
'es' => new Metadata(
id: 6, nodeId: 30, lang: 'es',
title: 'Práctica seleccionada', extras: ['mode' => 'practice'],
),
],
];

Choice labels use the same pattern, starting with the edge ID:

use ExecKernel\Domain\Graph\EdgeLabel;
$labels = [
101 => [
'en' => new EdgeLabel(101, 'en', 'Read the guide'),
'es' => new EdgeLabel(101, 'es', 'Leer la guía'),
],
102 => [
'en' => new EdgeLabel(102, 'en', 'Practise in the browser'),
'es' => new EdgeLabel(102, 'es', 'Practicar en el navegador'),
],
];

The three constructor arguments are the edge ID, language and visible text. Translating that text leaves the edge IDs unchanged, so the application can submit 101 for the guide in either language. Labels, metadata and languages develops presentation and language selection in more detail.

A Condition names a rule and provides the parameters that the rule will evaluate. For this graph, the built-in context_value rule compares a value supplied by the application with the value declared in the condition.

use ExecKernel\Domain\Graph\Condition;
$conditions = [
102 => [
new Condition(
rule: 'context_value',
params: [
'key' => 'practiceEnabled',
'operator' => '==',
'value' => true,
],
),
],
];

The outer key attaches the condition to edge 102. key names the context entry to read, operator selects the comparison and value supplies the expected boolean. The rule’s == comparison requires matching values and types: the string 'true' does not match the boolean true.

Creating this object does not set practiceEnabled or evaluate the condition. Your application supplies that value when it starts or advances the run; the engine evaluates the condition against that context. This keeps the definition reusable for runs in which practice is available and runs in which it is unavailable.

TerminalOutput describes a result that your application can present or act on when navigation reaches a terminal. The guide terminal has localized content followed by a link. The practice terminal has a redirect destination shared by both languages.

This fragment shows the English guide outputs and the shared practice output. The complete program also contains the Spanish guide outputs.

use ExecKernel\Domain\Graph\TerminalOutput;
$outputs = [
20 => [
new TerminalOutput(
nodeId: 20,
type: 'content',
lang: 'en',
content: 'Read the guide at your own pace.',
),
new TerminalOutput(
nodeId: 20,
type: 'url',
lang: 'en',
url: 'https://example.org/learning/guide',
label: 'Open the guide',
),
],
30 => [
new TerminalOutput(
nodeId: 30,
type: 'redirect',
url: 'https://example.org/learning/practice',
),
],
];

The outer keys and nodeId values associate these outputs with their terminals. type determines which result is being described; the remaining fields provide its text or destination. The example URLs are placeholders for destinations in your application.

The engine returns these declarations in the terminal payload. Your application displays the content, creates the link or performs the navigation. The terminal outputs guide explains those options and their ordering.

Graph brings together the objects we have created. In the complete program, $metadata and $outputs contain all the English and Spanish records described above.

use ExecKernel\Domain\Graph\Graph;
$graph = new Graph(
graphCode: 'learning-path',
nodesById: $nodes,
rootNodeId: 10,
edgesFrom: $edges,
labelsByEdge: $labels,
metadataByNode: $metadata,
outputsByNode: $outputs,
conditionsByEdge: $conditions,
defaultLang: 'en',
allowedLangs: ['en', 'es'],
);

graphCode identifies this definition; rootNodeId selects the starting node. The collection parameters state how each kind of data is indexed. For example, edgesFrom groups connections by their origin, whereas conditionsByEdge associates conditions with the choice they govern. defaultLang and allowedLangs establish the graph’s presentation languages.

The constructor checks the structure as it assembles it: the root must exist, connections must reference existing nodes, and every node must be reachable from the root and have a structural path to a terminal. It also checks that indexed records agree with their node, edge and language keys. An inconsistent definition raises an exception instead of producing a Graph.

Before using the definition, we also apply the importer’s strict validation. This checks aspects such as required default-language titles and labels, known condition types and their parameters.

use ExecKernel\Infrastructure\Exporter\GraphSchemaExporter;
use ExecKernel\Infrastructure\Importer\SchemaImporter;
$definition = (new GraphSchemaExporter())->toPayload($graph);
$importer = new SchemaImporter(strict: true);
$graph = $importer->importJson($definition);

toPayload() converts the graph objects into the array representation accepted by the importer; it does not write a file. Despite its name, importJson() receives that PHP array, validates it and returns a Graph. If validation fails, it throws an exception. This gives a programmatically constructed definition the same validation path as imported data. See Graph validation and diagnostics for interpreting failures.

We can now check what the graph means for an application. ExecKernelFactory builds an engine with its standard components. Context holds the application values used by conditions.

use ExecKernel\Domain\Session\Context;
use ExecKernel\Infrastructure\Engine\ExecKernelFactory;
$lang = 'en';
$engine = (new ExecKernelFactory())->build();
$start = $engine->start(
$graph,
$lang,
new Context(['practiceEnabled' => true]),
);

start() returns an EngineResult. Its state represents the run at node 10; its payload contains the root’s title and evaluated choices. With this context, both edges have enabled: true. If the application supplies practiceEnabled: false, the payload still contains edge 102, with enabled: false and availability: 'blocked'. The guide remains available.

To take the guide, pass edge 101 and the state returned by start():

$finish = $engine->choose($graph, $start->state, 101, $lang);
echo $finish->payload['title'], PHP_EOL;
echo $finish->payload['outputs'][0]['content'], PHP_EOL;

The new result describes terminal 20 and contains the message “Read the guide at your own pace.” The payload also includes the guide’s URL output. We selected an edge and inspected its result; a full application would decide how to display those values and where to retain the run’s state.

Download learning-path.php. It contains the complete graph, both languages, all terminal outputs, the validation step and the short execution above. Save it at the root of your Composer project, beside vendor/, and run:

Terminal window
php learning-path.php en

The program prints the initial choices, selects the guide and prints its result:

How would you like to learn?
101: Read the guide
102: Practise in the browser
Guide selected
Read the guide at your own pace.

Use es as the argument to request the Spanish presentation. The node and edge IDs remain the same.

For definitions maintained as data files, continue with JSON and YAML graph definitions. The public PHP types reference provides the broader API, and Embedding the engine covers application integration.