Close search

Hack book de Hoa\Graph

Unfortunately, the documentation of this library has not been written yet. However, the file may contain enough information to help you. This document is an extract of the file.
Sorry for this inconvenience. Be ensured we are working hard to fix this.

Help on IRC Help on Gitter Documentation Board

This library allows to create and manipulate directed graphs, a common data structure. A directed graph is basically a set of vertices (aka nodes) and directed edges between vertices.

Learn more.

Quick usage

As a quick overview, we propose to see how to create a simple directed graph in memory and dump the result as a DOT script in order to visualize it in SVG. The graph implementation will use the adjacency list structure. Thus:

// Create the graph instance.
// By default, loops are not allowed and we would like loops for this example,
// so we enable them.
$graph = new Hoa\Graph\AdjacencyList(Hoa\Graph::ALLOW_LOOP);

// Create 4 vertices (aka nodes).
$n1 = new Hoa\Graph\SimpleNode('n1');
$n2 = new Hoa\Graph\SimpleNode('n2');
$n3 = new Hoa\Graph\SimpleNode('n3');
$n4 = new Hoa\Graph\SimpleNode('n4');

// Create edges (aka links) between them.
$graph->addNode($n2, [$n1]); // n2 has parent n1.
$graph->addNode($n3, [$n1, $n2, $n3]); // n3 has parents n1, n2 and n3.
$graph->addNode($n4, [$n3]); // n4 has parent n3.
$graph->addNode($n2, [$n4]); // Add parent n4 to n2.

The directed graph is created in memory. Now, let's dump into the DOT language:

echo $graph;

 * Will output:
 *     digraph {
 *         n1;
 *         n2;
 *         n3;
 *         n4;
 *         n1 -> n2;
 *         n1 -> n3;
 *         n2 -> n3;
 *         n3 -> n3;
 *         n3 -> n4;
 *         n4 -> n2;
 *     }

Then, to compile this DOT script into an SVG document, we will use dot(1):

$ dot -Tsvg -oresult.svg <( echo 'digraph { … }'; )

And the result should look like the following image:


We can see that n1 is the parent of n2 and n3. n2 is the parent of n3. n3 is parent of n4 and also or iself. And finally, n4 is the parent of n2.

Our directed graph is created. Depending of the node, we can add more information on it. The SimpleNode class has been used. It extends the Hoa\Graph\Node interface.

Une erreur ou une suggestion sur la documentation ? Les contributions sont ouvertes !