Weave Code
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

Graph Laravel Package

graphp/graph

Graphp/graph is a PHP graph data structure library for building and traversing graphs of vertices and edges. Create directed or undirected graphs, attach attributes, and run common algorithms like shortest paths, cycles, and connectivity for analysis and visualization.

View on GitHub
Deep Wiki
Context7
## Getting Started

### **Minimal Setup**
1. **Installation**
   ```bash
   composer require graphp/graph
  • PHP 8.1 Support: This release officially supports PHP 8.1. Ensure your project meets this requirement.
  1. First Use Case: Creating a Graph

    use Graphp\Graph\Graph;
    
    $graph = new Graph();
    $graph->addVertex('A'); // String IDs work reliably (fixed in v0.9.3)
    $graph->addVertex('B');
    $graph->addEdge('A', 'B', ['weight' => 5]);
    
    • Key Classes (unchanged):
      • Graph (base graph structure)
      • Vertex (nodes)
      • Edge (connections)
      • Graph\Directed / Graph\Undirected (specialized graphs)
  2. Where to Look First

    • Updated Documentation (check for PHP 8.1-specific notes).
    • src/Graph/ for core classes (no structural changes).
    • tests/ for usage examples (now CI-verified via GitHub Actions).

Implementation Patterns

Common Workflows

  1. Building a Graph (PHP 8.1 Optimized)

    $graph = new Graph\Directed();
    $graph->addVertex('Node1', ['data' => 'custom']); // String IDs now auto-generate correctly
    $graph->addEdge('Node1', 'Node2', ['weight' => 3]);
    
    • Tip: Leverage PHP 8.1’s named arguments for clarity:
      $graph->addEdge('A', 'B', weight: 5, label: 'fast');
      
  2. Traversal Algorithms (Unchanged)

    $bfs = new Graph\Traversal\BreadthFirstSearch($graph, 'A');
    $bfs->run();
    $path = $bfs->getPathTo('B');
    
    • PHP 8.1 Note: Use match expressions for traversal state handling:
      match ($vertex->getId()) {
          'A' => $this->processStart(),
          default => $this->processNode($vertex),
      };
      
  3. Graph Analysis (Unchanged)

    $components = (new Graph\Analysis\ConnectedComponents($graph))->run();
    
  4. Serialization (Unchanged)

    $serializer = new Graph\IO\Graph6($graph);
    $serialized = $serializer->serialize(); // Now PHP 8.1-optimized
    
  5. Laravel Integration (Updated for PHP 8.1)

    // config/app.php (PHP 8.1 syntax)
    'graph' => Graph\Directed::class,
    
    // Controller (constructor property promotion)
    public function __construct(
        private Graph $graph
    ) {}
    

Gotchas and Tips

Pitfalls

  1. Vertex ID Generation (Fixed in v0.9.3)

    • Issue: String IDs (e.g., 'A') now auto-generate correctly. Avoid numeric-only IDs if using strings.
    • Fix: Test with mixed ID types:
      $graph->addVertex('string_id');
      $graph->addVertex(123); // Works, but strings are now preferred for clarity.
      
  2. PHP 8.1 Breaking Changes

    • Issue: null comparisons may behave differently with PHP 8.1’s strict typing.
    • Fix: Explicitly type-check:
      if ($vertex->getData() === null) { /* ... */ }
      
  3. Edge Cases in Traversal (Unchanged)

    • Validate weights before traversal (e.g., Dijkstra):
      foreach ($graph->edges() as $edge) {
          assert(is_numeric($edge['weight']), 'Weight must be numeric');
      }
      
  4. Performance (Unchanged)

    • For large graphs (>10K nodes), use Graph\Traversal\IterativeDFS and PHP 8.1’s JIT:
      $dfs = new IterativeDFS($graph, 'A');
      $dfs->run(); // Faster with PHP 8.1 JIT enabled
      

Debugging Tips

  1. Inspect Graph Structure (PHP 8.1)

    dump(
        vertices: $graph->vertices(),
        edges: $graph->edges()
    );
    
  2. Visualization (Unchanged)

    • Use GraphML with PHP 8.1’s Stringable interface:
      $serializer = new Graph\IO\GraphML($graph);
      file_put_contents('graph.graphml', $serializer->serialize()->__toString());
      
  3. Logging (PHP 8.1)

    $dfs->setCallback(fn (Vertex $vertex) => logger()->info("Visited: {$vertex->getId()}"));
    

Extension Points

  1. Custom Traversals (PHP 8.1)

    class MyTraversal extends AbstractTraversal {
        public function __construct(Graph $graph, string $startVertex) {
            parent::__construct($graph, $startVertex);
        }
        // Use PHP 8.1’s constructor property promotion
    }
    
  2. Graph Serializers (Unchanged)

    • Implement SerializerInterface with PHP 8.1’s Stringable:
      class JSONSerializer implements SerializerInterface, Stringable {
          public function __toString(): string { /* ... */ }
      }
      
  3. Laravel Integration (PHP 8.1)

    • Eloquent as Vertices:
      $graph = new Graph();
      foreach (User::all() as $user) {
          $graph->addVertex($user->id, ['user' => $user]); // PHP 8.1’s union types work here
      }
      
    • Database-Backed Graphs:
      • Use Laravel’s query builder with PHP 8.1’s whereIn:
        $vertices = Vertex::whereIn('id', $graph->vertices())->get();
        
  4. PHP 8.1-Specific Features

    • Attributes for Metadata:
      #[Attribute]
      class VertexWeight {
          public function __construct(public int $weight) {}
      }
      
      // Usage in custom Vertex class
      #[VertexWeight(5)]
      class WeightedVertex extends Vertex {}
      
    • Readonly Properties:
      class ImmutableVertex extends Vertex {
          public function __construct(
              public readonly string $id,
              array $data = []
          ) {
              parent::__construct($id, $data);
          }
      }
      

NO_UPDATE_NEEDED would **not** apply here—this release introduces meaningful changes (PHP 8.1 support, fixed vertex ID generation) that warrant updates to the **Getting Started**, **Implementation Patterns**, and **Gotchas** sections. The above reflects the revised assessment.
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.
andydefer/laravel-cluster
testo/fiber
mintobit/jobqueue
a4sex/maintenance-bundle
a4sex/entity-date-update
a4sex/client-identifier
a4sex/base-utilites
a4sex/key-value-storage
a4sex/micro-status
chilldev/dependency-injection-extra
datinglibre/datinglibre-app-api
biberltd/corebundle
bricre/symfony-bundle-test
biberltd/logbundle
dominium/http-adapter-bundle
dominium/google-analytics
a4sex/auto-clean-entity
christhompsontldr/laravel-inky
spatie/mailcoach-vapor
spatie/laravel-javascript-views