PHPackages                             alcaeus/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. alcaeus/graph

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

alcaeus/graph
=============

A graph data structure implementation in PHP

02PHPCI passing

Since Oct 5Pushed 7mo agoCompare

[ Source](https://github.com/alcaeus/graph)[ Packagist](https://packagist.org/packages/alcaeus/graph)[ RSS](/packages/alcaeus-graph/feed)WikiDiscussions main Synced 1mo ago

READMEChangelogDependenciesVersions (1)Used By (0)

Graph Data Structure Library
============================

[](#graph-data-structure-library)

[![Tests](https://github.com/alcaeus/graph/workflows/Tests/badge.svg)](https://github.com/alcaeus/graph/actions)[![PHPStan](https://github.com/alcaeus/graph/workflows/PHPStan/badge.svg)](https://github.com/alcaeus/graph/actions)[![PHP CS](https://github.com/alcaeus/graph/workflows/PHP%20CS/badge.svg)](https://github.com/alcaeus/graph/actions)

> **⚠️ EXPERIMENTAL LIBRARY**
> This library is currently experimental and not yet ready for production use. The API may change significantly between versions. Use at your own risk.

A sophisticated graph data structure implementation in PHP with advanced pathfinding algorithms and intelligent caching.

Features
--------

[](#features)

- **Generic Graph Structure**: Nodes and edges can store arbitrary data
- **Optimized Pathfinding**: Advanced DFS algorithm with comprehensive segment caching
- **Algorithm Architecture**: Clean separation between graph structure and algorithms
- **Type Safety**: Full PHPStan level max compliance with strict type checking
- **PHP 8.4+ Ready**: Leverages modern PHP features including property hooks

Requirements
------------

[](#requirements)

- PHP 8.4 or higher

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

[](#installation)

```
composer require alcaeus/graph
```

Basic Usage
-----------

[](#basic-usage)

### Creating a Graph

[](#creating-a-graph)

```
use Alcaeus\Graph\Graph;

// Create a new graph
$graph = new Graph();

// Add nodes with optional data
$nodeA = $graph->addNode('A', 'Node A data');
$nodeB = $graph->addNode('B', 'Node B data');
$nodeC = $graph->addNode('C');

// Connect nodes with edges (also with optional data)
$edgeAB = $graph->connect($nodeA, $nodeB, 'Connection A to B');
$edgeBC = $graph->connect('B', 'C', 'Connection B to C'); // Can use node IDs
$edgeAC = $graph->connect($nodeA, $nodeC); // No edge data
```

### Exploring Connections

[](#exploring-connections)

```
// Get incoming and outgoing edges for a node
$incomingEdges = $graph->getIncomingEdges($nodeB);
$outgoingEdges = $graph->getOutgoingEdges($nodeA);

// Access node and edge data
echo $nodeA->data; // "Node A data"
echo $edgeAB->data; // "Connection A to B"

// Navigate the graph
foreach ($outgoingEdges as $edge) {
    echo "From: {$edge->from->id} -> To: {$edge->to->id}\\n";
}
```

### Advanced Pathfinding

[](#advanced-pathfinding)

The library includes an optimized pathfinding algorithm with intelligent caching:

```
// Find all paths between two nodes
$paths = $graph->getPaths($nodeA, $nodeC);

foreach ($paths as $path) {
    echo "Path: {$path}\\n"; // "A -> B -> C" or "A -> C"

    // Access path details
    echo "Start: {$path->start->id}\\n";
    echo "End: {$path->end->id}\\n";
    echo "Length: " . count($path->edges) . " edges\\n";

    // Iterate through edges in the path
    foreach ($path->edges as $edge) {
        echo "  {$edge->from->id} -> {$edge->to->id}\\n";
    }
}
```

### Complex Graph Example

[](#complex-graph-example)

```
// Create a more complex graph
$graph = new Graph();

// Add nodes representing cities
$paris = $graph->addNode('PAR', ['name' => 'Paris', 'country' => 'France']);
$london = $graph->addNode('LON', ['name' => 'London', 'country' => 'UK']);
$berlin = $graph->addNode('BER', ['name' => 'Berlin', 'country' => 'Germany']);
$rome = $graph->addNode('ROM', ['name' => 'Rome', 'country' => 'Italy']);

// Add connections with travel data
$graph->connect($paris, $london, ['distance' => 344, 'mode' => 'flight']);
$graph->connect($paris, $berlin, ['distance' => 878, 'mode' => 'train']);
$graph->connect($london, $berlin, ['distance' => 933, 'mode' => 'flight']);
$graph->connect($berlin, $rome, ['distance' => 1181, 'mode' => 'flight']);
$graph->connect($paris, $rome, ['distance' => 1105, 'mode' => 'flight']);

// Find all possible routes from Paris to Rome
$routes = $graph->getPaths($paris, $rome);

echo "Found " . count($routes) . " routes from Paris to Rome:\\n";
foreach ($routes as $i => $route) {
    echo ($i + 1) . ". {$route}\\n";

    $totalDistance = 0;
    foreach ($route->edges as $edge) {
        $totalDistance += $edge->data['distance'];
    }
    echo "   Total distance: {$totalDistance} km\\n";
}
```

### Using with Typed Data

[](#using-with-typed-data)

The library supports PHP generics for type-safe operations:

```
/**
 * @var Graph $typedGraph
 */
$typedGraph = new Graph();

// Node data must be string, edge data must be array with distance and mode
$nodeA = $typedGraph->addNode('A', 'City A');
$nodeB = $typedGraph->addNode('B', 'City B');
$edge = $typedGraph->connect($nodeA, $nodeB, ['distance' => 100, 'mode' => 'car']);
```

Performance Features
--------------------

[](#performance-features)

The library includes several performance optimizations:

- **Segment Caching**: Path segments are cached during traversal for maximum reuse
- **Algorithm Separation**: Algorithms are instantiated per graph instance and cache independently
- **Lazy Evaluation**: Algorithm instances are created only when needed
- **Cache Invalidation**: Caches are automatically cleared when graph structure changes

Development
-----------

[](#development)

### Running Tests

[](#running-tests)

```
vendor/bin/phpunit
```

### Code Quality

[](#code-quality)

```
# Run PHPStan static analysis
vendor/bin/phpstan analyse

# Check code style
vendor/bin/phpcs

# Fix code style
vendor/bin/phpcbf
```

Architecture
------------

[](#architecture)

The library follows clean architecture principles:

- **Graph**: Core graph structure management
- **Node/Edge**: Basic graph elements with data storage
- **Path**: Value object representing a path through the graph
- **Algorithms**: Separated algorithms (PathFinder) with independent caching

License
-------

[](#license)

This project is licensed under the MIT License - see the [LICENSE](LICENSE) file for details.

Contributing
------------

[](#contributing)

This is an experimental library. Contributions are welcome, but please note that the API may change significantly between versions.

###  Health Score

16

—

LowBetter than 5% of packages

Maintenance44

Moderate activity, may be stable

Popularity2

Limited adoption so far

Community6

Small or concentrated contributor base

Maturity13

Early-stage or recently created project

 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.

### Community

Maintainers

![](https://avatars.githubusercontent.com/u/383198?v=4)[Andreas Braun](/maintainers/alcaeus)[@alcaeus](https://github.com/alcaeus)

---

Top Contributors

[![alcaeus](https://avatars.githubusercontent.com/u/383198?v=4)](https://github.com/alcaeus "alcaeus (9 commits)")

### Embed Badge

![Health badge](/badges/alcaeus-graph/health.svg)

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

PHPackages © 2026

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