Weave Code
Weaver
Helps Laravel developers discover, compare, and choose open-source packages. See popularity, security, maintainers, and scores at a glance to make better decisions.
Feedback
Share your thoughts, report bugs, or suggest improvements.
Subject
Message

Algorithm Laravel Package

fisharebest/algorithm

A small PHP library of reusable algorithm implementations, including Dijkstra shortest-path and topological sorting, for graph traversal, dependency ordering, and routing tasks in Laravel or any Composer-based PHP project.

Deep Wiki
Context7

Getting Started

Install

composer require fisharebest/algorithm

That is the whole setup. The package is plain, dependency-free PHP with PSR-4 autoloading (Fisharebest\Algorithm\...). There is no service provider, no config file, no facade, and no Laravel version constraint to worry about — it runs unmodified on any modern Laravel app.

Where to look first

  • README.md — short; every class is demonstrated with a 5–20 line snippet.
  • src/ — only a handful of classes (Dijkstra, TopologicalSort, ConnectedComponent, BinarySearch, MyersDiff). You can read the entire package in an afternoon, which is the fastest way to learn its exact method signatures.
  • tests/ — the clearest specification of behavior, especially edge cases (cycles, empty graphs, unreachable nodes).

First use case: shortest path

use Fisharebest\Algorithm\Dijkstra;

$graph = new Dijkstra();
$graph->addEdge('home', 'shop', 4);
$graph->addEdge('home', 'park', 2);
$graph->addEdge('park', 'shop', 1);

$graph->shortestPath('home', 'shop'); // ['home', 'park', 'shop']

Instantiate, add edges, ask for the result. That pattern — build a graph, run an algorithm, get an array back — is the shape of every class in the package.

Implementation Patterns

Treat the classes as pure, throwaway value objects. They hold no framework state, so instantiate them inside the method that needs them (or inject them if you want to swap implementations in tests). There is nothing to app()->bind() unless you want a shared graph reused across a request.

Wrapping in a domain service. Because the API is minimal, the useful engineering work is your adapter layer:

final class RoutePlanner
{
    public function __construct(private Dijkstra $graph) {}

    public function cheapestPath(string $from, string $to): array
    {
        return $this->graph->shortestPath($from, $to);
    }
}

Bind RoutePlanner in a service provider and inject it into controllers, jobs, or commands. Keep the raw Fisharebest\Algorithm types out of your controllers so you can replace the library later.

Topological sort for dependency resolution. Very common in Laravel: ordering migrations, resolving job pipelines, sorting permission hierarchies, or ordering model relations for export.

use Fisharebest\Algorithm\TopologicalSort;

$sort = new TopologicalSort();
$sort->addEdge('migrate-users', 'migrate-orders'); // users must run first
$sort->addEdge('migrate-orders', 'migrate-invoices');

$order = $sort->sort(); // ['migrate-users', 'migrate-orders', 'migrate-invoices']

Connected components for grouping. Use it to merge duplicate records, cluster users by shared attributes, split a chat/user graph into threads, or find islands in a network graph.

use Fisharebest\Algorithm\ConnectedComponent;

$cc = new ConnectedComponent();
$cc->addEdge(1, 2);
$cc->addEdge(2, 3);
$cc->addEdge(4, 5);

$cc->findComponents(); // [[1, 2, 3], [4, 5]]

Binary search for boundaries. Instead of searching for an exact value, use the binary-search helper to find the transition point in a monotonic predicate (first record after a cutoff, insertion index, pagination boundary). This is the pattern that tends to show up in reporting and pagination code.

Myers diff for versioned content. Useful for audit logs, model version history, comparing config snapshots, or generating human-readable change summaries.

use Fisharebest\Algorithm\MyersDiff;

$diff = new MyersDiff();
$changes = $diff->calculate($oldBody, $newBody);

Integration tips

  • Build graphs from Eloquent relationships by iterating a cursor and calling addEdge() — never load a whole table into memory just to construct a graph.
  • Vertex names must be scalar and string-keyable; map Eloquent models to IDs before adding edges.
  • Cache expensive algorithm results (Cache::remember) keyed by the graph’s input signature.
  • Run long graph builds inside a queued job rather than a request cycle; the algorithms themselves are fast, but constructing large graphs isn’t.
  • Unit-test your adapter services with PHPUnit or Pest; the algorithms are deterministic, so snapshots work well.

Gotchas and Tips

GPL-3.0 license — read this before shipping. The package is GPL-3.0, a strong copyleft license. If you distribute a Laravel application that includes it, you are likely obligated to release your application under GPL-compatible terms. For internal-only tools this is usually fine; for a commercial SaaS or a distributed product, confirm with legal or vendor the algorithm yourself. This is the single biggest adoption risk for this package and the reason many teams fork the specific algorithm they need.

Vertex key coercion. PHP array keys turn numeric strings into integers. If you addEdge('1', '2', 1) and later call shortestPath('01', '2'), lookups will fail. Normalize IDs to a consistent type (int, or a hashed string) at the boundary.

Weights must be non-negative and numeric for Dijkstra. Zero-weight edges are generally tolerated, but negative weights break the algorithm silently — it will return a plausible-looking wrong path rather than throw. Validate inputs.

Cycles are your responsibility. Topological sort is only defined for a DAG. Check the class’s behavior for cyclic input in the installed version (some versions throw, others return a partial order) and add an explicit cycle check in your service if ordering correctness matters.

Unreachable nodes. shortestPath() returns only the path, not the distance, in most versions. If you need the total cost or need to distinguish “no path” from a one-node path, sum the weights yourself from your edge map, or check the return value carefully — an empty/one-element array is ambiguous.

Binary search requires a monotonic predicate. The predicate must be false for all indices below some point and true for all indices at or above it (or vice versa). If it isn’t monotonic, you’ll get a random-looking index with no error. Test the predicate in isolation.

Diff memory use. Myers diff is O(N·M) in the worst case for two long strings. Diffing two large HTML blobs will hurt. Tokenize or chunk first, and cap input size.

Version pinning. This is a small, low-velocity package (71 stars, single maintainer). Method names have changed between releases in the past, and the README is the de facto API contract. Pin an exact version in composer.json, skim the changelog before upgrading, and wrap the calls in your own service so an upstream rename is a one-line fix.

Extension points are limited. There are no interfaces or pluggable comparators to override. Customization means subclassing the concrete class or, more practically, preprocessing inputs and postprocessing outputs in your adapter.

Debugging. The algorithms return arrays with no internal trace. When a path or order looks wrong, dump your edge list (var_dump($graph)) and re-run on a 3–4 node graph — the inputs are almost always the bug, not the algorithm.

Forking is a legitimate option. Since the package is small and permissively structured (aside from the license), copying the one class you need into app/Support/ is often the pragmatic choice for a GPL-averse project.

Weaver

How can I help you explore Laravel packages today?

Conversation history is not saved when not logged in.
Prompt
Add packages to context
No packages found.
novasa/laravel-language-center
opencage/geocode
adolfoholzer/parameters
livenetworks/ln-starter
shitoudev/permissionmanager
johannesclimacus/laravel-tui
hocvt/seotools
vitalybaev/sypexgeo
amphibee/themosis-ignition
gito-me/fast-excel
frankyso/laravel-ipaymu
geolize-studio/laravel-chile
boomerangui/chat
jinas/dhivatar
store-doc/laravel-storage-driver
plus-it/laravel-translation-manager
diephp/perhaps
diephp/telegraph
osmaviation/spreadsheet
microsoft/fluentui-system-icons