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

Collection Laravel Package

php-standard-library/collection

Generic, object-oriented Vector, Map, and Set collections for PHP with both immutable and mutable variants. Part of PHP Standard Library; designed for a consistent, type-friendly API. Full docs at php-standard-library.dev.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Steps

  1. Installation:

    composer require php-standard-library/collection
    

    Add to composer.json under require:

    "php-standard-library/collection": "^6.0"
    
  2. First Use Case: Replace a simple array operation with a typed, immutable collection:

    use PHPStandardLibrary\Collection\Vector;
    
    // Before: Mutable array
    $numbers = [1, 2, 3];
    $doubled = array_map(fn($n) => $n * 2, $numbers);
    
    // After: Immutable Vector
    $immutableDoubled = Vector::of(1, 2, 3)->map(fn(int $n): int => $n * 2);
    
  3. Where to Look First:

    • Documentation for API reference.
    • src/Collection/ directory in the package for source code (e.g., Vector.php, Map.php).
    • Focus on Vector for lists, Map for key-value pairs, and Set for unique collections.

Implementation Patterns

Usage Patterns

  1. Immutable Workflows:

    // Safe for concurrent access (e.g., caching, jobs)
    $users = Vector::of(User::all())
        ->filter(fn(User $u) => $u->isActive())
        ->map(fn(User $u) => $u->name)
        ->freeze(); // Immutable!
    
  2. Mutable Performance Optimizations:

    // In-place updates for high-throughput operations
    $mutableVector = Vector::mutableOf(1, 2, 3);
    $mutableVector->push(4); // No new object created
    
  3. Type-Safe Collections:

    // Strong typing for domain models
    use PHPStandardLibrary\Collection\Map;
    
    /** @var Map<string, User> */
    $userMap = Map::of(['id1' => $user1, 'id2' => $user2]);
    $user = $userMap->get('id1'); // Returns User|null
    
  4. Laravel Integration:

    // Wrap Eloquent results
    $users = User::all()->mapInto(Vector::class);
    
    // Convert back to Laravel Collection
    $laravelCollection = $vector->toLaravelCollection();
    
  5. Functional Chaining:

    // Replace nested array functions
    $result = Vector::of($orders)
        ->filter(fn(Order $o) => $o->total > 100)
        ->map(fn(Order $o) => $o->customerId)
        ->unique()
        ->sort();
    

Workflows

  1. Data Transformation Pipeline:

    $processedData = Vector::of($rawData)
        ->map(fn($item) => (object) $item) // Normalize
        ->filter(fn(object $o) => $o->valid) // Validate
        ->groupBy(fn(object $o) => $o->category) // Group
        ->mapValues(fn(Vector $group) => $group->sum('value')); // Aggregate
    
  2. State Management in Jobs:

    // Thread-safe job state
    $jobState = Vector::of($initialState)->freeze();
    // ...
    $updatedState = $jobState->map(fn($item) => $item->process());
    
  3. Testing with Immutable Snapshots:

    // Reproducible test data
    $testData = Vector::of(1, 2, 3)->freeze();
    $this->assertEquals($testData, $testData->map(fn($n) => $n * 2));
    

Integration Tips

  1. Hybrid with Laravel Collections:

    // Convert Laravel Collection to Vector
    $vector = Laravel\Collection::make([1, 2, 3])->mapInto(Vector::class);
    
    // Convert back
    $laravelCollection = $vector->toLaravelCollection();
    
  2. Custom Value Objects:

    // Use with DTOs or value objects
    $orders = Vector::of(Order::class, $orderData);
    
  3. Performance-Critical Paths:

    • Use Vector::mutableOf() for bulk operations (e.g., batch processing).
    • Prefer Set for deduplication (e.g., Set::of($items)->toArray()).
  4. API Responses:

    // Type-safe API responses
    return response()->json(
        Vector::of($users)
            ->map(fn(User $u) => ['id' => $u->id, 'name' => $u->name])
            ->toArray()
    );
    

Gotchas and Tips

Pitfalls

  1. Immutable Overhead:

    • Every operation on an immutable collection creates a new object. Avoid in tight loops:
      // Bad: Creates N new objects
      $result = Vector::of([...]);
      for ($i = 0; $i < 1000; $i++) {
          $result = $result->map(...); // Expensive!
      }
      
    • Fix: Use mutable variants for iterative updates.
  2. Type Safety Strictness:

    • PHP 8.1+ generics are enforced. Mixed types may cause runtime errors:
      // Fails: Inconsistent types
      $mixed = Vector::of(1, 'two', 3.0); // Error if strict typing is enabled
      
    • Fix: Explicitly cast or use Vector::ofAny() (if available).
  3. Laravel Collection Incompatibilities:

    • Methods like pluck() or groupBy() may not exist. Use functional equivalents:
      // Laravel: $collection->pluck('name')
      // Standard Library: $vector->map(fn($item) => $item->name)
      
  4. Serialization Quirks:

    • Immutable collections may not serialize/deserialize cleanly with Laravel’s cache or queues:
      // May fail in Redis or database
      Cache::put('key', $immutableVector->freeze());
      
    • Fix: Convert to array first: $immutableVector->toArray().
  5. Circular References:

    • Deeply nested collections with circular references (e.g., User with orders containing User) may cause infinite loops:
      $user->orders->map(fn(Order $o) => $o->user); // Risk of recursion
      
    • Fix: Use ->toArray() for serialization or implement __serialize().

Debugging

  1. Unexpected Mutations:

    • If data changes unexpectedly, check for:
      • Accidental use of mutable methods (e.g., push() on an immutable Vector).
      • Laravel’s Collection macros overriding behavior.
  2. Type Errors:

    • Enable strict types in php.ini (strict_types=1) to catch issues early.
    • Use phpstan or psalm for static analysis:
      vendor/bin/phpstan analyse --level=max src/
      
  3. Performance Bottlenecks:

    • Profile with xdebug or blackfire.io to identify expensive operations (e.g., map on large immutable collections).

Config Quirks

  1. Autoloading:

    • Ensure composer dump-autoload is run after installation to avoid ClassNotFound errors.
  2. Laravel Service Provider:

    • If extending Laravel’s Collection, bind the package in AppServiceProvider:
      use PHPStandardLibrary\Collection\Vector;
      
      public function register()
      {
          Laravel\Collection::macro('toVector', function () {
              return Vector::of($this->all());
          });
      }
      

Extension Points

  1. Custom Collections:

    • Extend base classes for domain-specific logic:
      class UserVector extends Vector
      {
          public function activeOnly(): self
          {
              return $this->filter(fn(User $u) => $u->isActive());
          }
      }
      
  2. Laravel Macros:

    • Add package-specific macros to Laravel’s Collection:
      Laravel\Collection::macro('toImmutableVector', function () {
          return Vector::of($this->all())->freeze();
      });
      
  3. Interoperability:

    • Implement ArrayAccess or IteratorAggregate for seamless integration with Laravel’s utilities:
      $vector->getIterator(); // Works with Laravel's collection helpers
      
  4. Testing Helpers:

    • Create custom assertions for immutable collections:
      $this->assertVectorEquals(
          Vector::of(1, 2, 3),
          Vector::of(1, 2, 3)->map(fn($n) => $n)
      );
      

Pro Tips

  1. Immutable Defaults:
    • Prefer freeze() for function arguments to enforce immutability:
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.
terminal42/code-quality-tools
codifyo/ts-generator-bundle
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