PHPackages                             php-architecture-kit/graph - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. [Utility &amp; Helpers](/categories/utility)
4. /
5. php-architecture-kit/graph

ActiveLibrary[Utility &amp; Helpers](/categories/utility)

php-architecture-kit/graph
==========================

Graph data structure implementation to use as base for any (including Domain) Graphs.

1.0.1(1mo ago)191MITPHPPHP ^8.0

Since May 4Pushed 1mo agoCompare

[ Source](https://github.com/php-architecture-kit/graph)[ Packagist](https://packagist.org/packages/php-architecture-kit/graph)[ Docs](https://github.com/php-architecture-kit/graph)[ RSS](/packages/php-architecture-kit-graph/feed)WikiDiscussions main Synced today

READMEChangelogDependencies (1)Versions (3)Used By (1)

php-architecture-kit/graph
==========================

[](#php-architecture-kitgraph)

Framework-agnostic graph library for PHP applications. It provides a consistent API for building graphs with vertices and directed/undirected edges, traversing graph elements with visitors, and calculating shortest paths between vertices.

Features
--------

[](#features)

- **Directed and undirected edges** - Use `DirectedEdge` and `UndirectedEdge` in the same graph
- **Strongly typed identities** - `VertexId` and `EdgeId` value objects
- **Configurable validation** - Toggle self-loop, multi-edge, and cyclic-edge rules
- **Optional named edge weights** - Define defaults per edge class and override per edge
- **Traversal API (Visitor Pattern)** - Traverse vertices/edges with stop control
- **Navigation API** - Select entities as contexts and query neighbors/incident edges
- **Shortest path finder** - Bidirectional shortest path search with optional edge filtering
- **Automatic incidence index updates** - Built-in index synchronization through graph events

Installation
------------

[](#installation)

```
composer require php-architecture-kit/graph
```

Quick Start
-----------

[](#quick-start)

```
use PhpArchitecture\Graph\Graph;
use PhpArchitecture\Graph\GraphNavigator;
use PhpArchitecture\Graph\Edge\DirectedEdge;
use PhpArchitecture\Graph\Edge\UndirectedEdge;
use PhpArchitecture\Graph\Vertex\Vertex;

$graph = new Graph();

$a = new Vertex(metadata: ['name' => 'A']);
$b = new Vertex(metadata: ['name' => 'B']);
$c = new Vertex(metadata: ['name' => 'C']);

$graph->vertexStore->addVertex($a);
$graph->vertexStore->addVertex($b);
$graph->vertexStore->addVertex($c);

$ab = new DirectedEdge($a, $b);
$bc = new DirectedEdge($b, $c);
$ac = new UndirectedEdge($a, $c);

$graph->edgeStore->addEdge($ab);
$graph->edgeStore->addEdge($bc);
$graph->edgeStore->addEdge($ac);

$isAdjacent = $graph->edgeStore->areAdjacent($a->id(), $b->id()); // true
$degreeOfB = $graph->edgeStore->degree($b->id()); // 2

$navigator = new GraphNavigator($graph);
$path = $navigator->shortestPathTo($a->id(), $c->id()); // EdgeContext[]
```

Graph Configuration
-------------------

[](#graph-configuration)

Use `GraphConfig` to control validation behavior and edge weights.

```
use PhpArchitecture\Graph\Graph;
use PhpArchitecture\Graph\Config\GraphConfig;
use PhpArchitecture\Graph\Edge\DirectedEdge;
use PhpArchitecture\Graph\Edge\UndirectedEdge;
use PhpArchitecture\Graph\Edge\Weight\Config\WeightConfig;

$graph = new Graph(config: new GraphConfig(
    allowSelfLoop: false,
    allowMultiEdge: false,
    allowCyclicEdge: false,
    weightConfig: new WeightConfig([
        DirectedEdge::class => ['cost' => 1.0, 'latency' => 10.0],
        UndirectedEdge::class => ['cost' => 0.5],
    ]),
));
```

Navigation and Context API
--------------------------

[](#navigation-and-context-api)

`GraphNavigator` is the main read/query entry point.

### Selecting Vertices and Edges

[](#selecting-vertices-and-edges)

```
use PhpArchitecture\Graph\GraphNavigator;
use PhpArchitecture\Graph\Vertex\VertexInterface;

$navigator = new GraphNavigator($graph);

$vertexContext = $navigator->selectVertex($a->id());
$edgeContext = $navigator->selectEdge($ab->id());

$allVertexContexts = $navigator->selectVertices();
$apiVertices = $navigator->selectVertices(
    static fn(VertexInterface $vertex): bool => ($vertex->metadata['type'] ?? null) === 'api',
);
```

### Working with Context Objects

[](#working-with-context-objects)

```
// VertexContext
$neighborContexts = $vertexContext->neighbors();
$incidentEdges = $vertexContext->edges();

// EdgeContext
$isDirected = $edgeContext->isDirected();
$u = $edgeContext->u();
$v = $edgeContext->v();
```

Traversal (Visitor Pattern)
---------------------------

[](#traversal-visitor-pattern)

The traversal module supports multiple visitors and three control actions:

- `VisitAction::Continue`
- `VisitAction::StopAtCurrentEntity`
- `VisitAction::StopImmediately`

```
use PhpArchitecture\Graph\Tools\Navigation\Traversal\VertexVisitorInterface;
use PhpArchitecture\Graph\Tools\Navigation\Traversal\VisitAction;
use PhpArchitecture\Graph\Tools\Navigation\Traversal\VisitResult;
use PhpArchitecture\Graph\Vertex\VertexInterface;

final class CollectVertexIdsVisitor implements VertexVisitorInterface
{
    /** @var list */
    public array $visited = [];

    public function visit(VertexInterface $vertex): VisitResult
    {
        $this->visited[] = $vertex->id()->toString();

        return new VisitResult(VisitAction::Continue);
    }
}

$visitor = new CollectVertexIdsVisitor();
$result = $navigator->traverseVertices([$visitor]);

$visitedByVisitor = $result->getByVisitor(CollectVertexIdsVisitor::class);
```

Shortest Path
-------------

[](#shortest-path)

Shortest path search is available via `GraphNavigator::shortestPathTo(...)` and uses bidirectional search internally.

```
use PhpArchitecture\Graph\Edge\EdgeInterface;

$path = $navigator->shortestPathTo(
    sourceId: $a->id(),
    targetId: $c->id(),
    edgeFilter: static fn(EdgeInterface $edge): bool =>
        ($edge->metadata['blocked'] ?? false) === false,
);

$pathEdgeIds = array_map(
    static fn($context): string => $context->edge->id()->toString(),
    $path,
);
```

Returns:

- `EdgeContext[]` when a path exists
- `[]` when source equals target
- `[]` when no path matches the filter

Edge Weights
------------

[](#edge-weights)

If `weightConfig` is enabled, you can define and read named weights per edge.

```
use PhpArchitecture\Graph\Edge\DirectedEdge;
use PhpArchitecture\Graph\Edge\Weight\EdgeWeights;
use PhpArchitecture\Graph\Edge\Weight\Weight;

$edge = new DirectedEdge($a, $b);

$graph->edgeStore->addEdge(
    $edge,
    new EdgeWeights($edge->id(), [
        'cost' => new Weight('cost', 3.0),
        'latency' => new Weight('latency', 25.0),
    ]),
);

$cost = $navigator->selectEdge($edge->id())->weights()->value('cost');
```

API Reference
-------------

[](#api-reference)

### GraphNavigator

[](#graphnavigator)

MethodDescription`selectVertex(VertexId $id): VertexContext`Select one vertex as context`selectVertices(?callable $filter = null): VertexContext[]`Select many vertices with optional filter`selectEdge(EdgeId $id): EdgeContext`Select one edge as context`selectEdges(?callable $filter = null): EdgeContext[]`Select many edges with optional filter`traverseVertices(array $visitors, ?callable $filter = null): VertexTraversalResult`Traverse vertices with visitors`traverseEdges(array $visitors, ?callable $filter = null): EdgeTraversalResult`Traverse edges with visitors### VertexContext

[](#vertexcontext)

MethodDescription`edges(?callable $filter = null): EdgeContext[]`Get incident edges for this vertex`neighbors(?callable $edgeFilter = null, ?callable $filter = null): VertexContext[]`Get neighboring vertices### EdgeContext

[](#edgecontext)

MethodDescription`isDirected(): bool`Check if edge is directed`isUndirected(): bool`Check if edge is undirected`u(): VertexInterface`Resolve first endpoint`v(): VertexInterface`Resolve second endpoint`weights(): EdgeWeights`Resolve edge weights (when configured)### Traversal Interfaces

[](#traversal-interfaces)

InterfaceMethod`VertexVisitorInterface``visit(VertexInterface $vertex): VisitResult``EdgeVisitorInterface``visit(EdgeInterface $edge): VisitResult`License
-------

[](#license)

MIT

###  Health Score

37

—

LowBetter than 81% of packages

Maintenance88

Actively maintained with recent releases

Popularity7

Limited adoption so far

Community8

Small or concentrated contributor base

Maturity40

Maturing project, gaining track record

 Bus Factor1

Top contributor holds 100% of commits — single point of failure

How is this calculated?**Maintenance (25%)** — Last commit recency, latest release date, and issue-to-star ratio. Uses a 2-year decay window.

**Popularity (30%)** — Total and monthly downloads, GitHub stars, and forks. Logarithmic scaling prevents top-heavy scores.

**Community (15%)** — Contributors, dependents, forks, watchers, and maintainers. Measures real ecosystem engagement.

**Maturity (30%)** — Project age, version count, PHP version support, and release stability.

###  Release Activity

Cadence

Every ~1 days

Total

2

Last Release

58d ago

### Community

Maintainers

![](https://www.gravatar.com/avatar/145db325ca53baabce2d955faebe43d56bc4f3122b9ae463d41ee0e5da487cea?d=identicon)[patrykbaszak](/maintainers/patrykbaszak)

---

Top Contributors

[![patrykbaszak](https://avatars.githubusercontent.com/u/66377724?v=4)](https://github.com/patrykbaszak "patrykbaszak (14 commits)")

---

Tags

dddgraphframework agnosticdata structure

### Embed Badge

![Health badge](/badges/php-architecture-kit-graph/health.svg)

```
[![Health](https://phpackages.com/badges/php-architecture-kit-graph/health.svg)](https://phpackages.com/packages/php-architecture-kit-graph)
```

###  Alternatives

[novus/nvd3

A reusable charting library written in d3.js

7.2k214.4k3](/packages/novus-nvd3)[clue/graph

GraPHP is the mathematical graph/network library written in PHP.

7244.5M43](/packages/clue-graph)[prooph/service-bus

PHP Enterprise Service Bus Implementation supporting CQRS and DDD

4451.4M32](/packages/prooph-service-bus)[ecotone/ecotone

Enterprise architecture layer for Laravel and Symfony — CQRS, Event Sourcing, Durable Workflows (Sagas, Orchestrators), Projections, and Outbox messaging via PHP attributes.

564576.7k53](/packages/ecotone-ecotone)[graphp/graph

GraPHP is the mathematical graph/network library written in PHP.

714311.7k5](/packages/graphp-graph)[prooph/event-sourcing

PHP EventSourcing library

266824.6k18](/packages/prooph-event-sourcing)

PHPackages © 2026

[Directory](/)[Categories](/categories)[Trending](/trending)[Changelog](/changelog)[Analyze](/analyze)
