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

hyperf/collection

A lightweight, fluent Collection implementation for Hyperf/PHP. Provides convenient methods for mapping, filtering, reducing, grouping, plucking, and more, with an API similar to Laravel Collections for handling arrays and iterables cleanly and safely.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation:

    composer require hyperf/collection
    

    The package is a direct port of Laravel's Illuminate\Support\Collection, so no additional configuration is required.

  2. First Usage:

    use Hyperf\Collection\Collection;
    
    $collection = new Collection([1, 2, 3]);
    $filtered = $collection->filter(fn($item) => $item > 1); // Returns [2, 3]
    
  3. Key Entry Point: The Collection facade (if published) or direct instantiation is the primary way to interact with the package. For Hyperf projects, you may also use the collect() helper (if included in your project's helpers).

First Use Case: Data Transformation

Transform an array of user data into a formatted response:

$users = collect([
    ['name' => 'John', 'age' => 30],
    ['name' => 'Jane', 'age' => 25],
]);

$formatted = $users->map(fn($user) => [
    'full_name' => $user['name'],
    'age_group' => $user['age'] >= 30 ? 'adult' : 'young',
]);

Implementation Patterns

Core Workflows

  1. Chaining Methods: Collections support fluent method chaining for readability:

    $result = collect($data)
        ->filter(fn($item) => $item['active'])
        ->sortBy('priority')
        ->values()
        ->all();
    
  2. Grouping and Aggregation:

    $grouped = collect($orders)
        ->groupBy('customer_id')
        ->mapToGroups(fn($order) => [$order['customer_id'] => $order['total']])
        ->sum();
    
  3. Integration with Hyperf Components:

    • Database Results: Use collect() on Eloquent or Hyperf DB query results:
      $users = collect(UserModel::query()->get());
      
    • HTTP Requests: Process incoming requests:
      $validated = collect($request->input())->only(['name', 'email']);
      
  4. Custom Macros: Extend functionality with macros (defined in a service provider):

    Collection::macro('snakeKeys', function () {
        return $this->mapWithKeys(fn($item) => [
            Str::snake(key($item)) => $item,
        ]);
    });
    

Performance Considerations

  • Lazy Evaluation: Use lazy() for large datasets to avoid loading everything into memory:
    $lazy = collect($hugeArray)->lazy()->filter(...);
    
  • Batch Processing: For CPU-intensive operations, chunk the collection:
    collect($items)->chunk(100)->each(function ($chunk) {
        // Process chunk
    });
    

Gotchas and Tips

Common Pitfalls

  1. Immutable Operations: Collection methods return new collections unless explicitly mutated (e.g., sort() vs. sorted()). Avoid assuming in-place changes:

    $col = collect([3, 1, 2]);
    $col->sort(); // Returns a new sorted collection; original remains [3, 1, 2]
    
  2. Type Safety: Hyperf Collections are loosely typed. For strict typing, cast to arrays or use PHP 8.1+ typed properties:

    $array = $collection->toArray(); // Explicit conversion
    
  3. Macro Conflicts: Ensure macros are registered after the Collection class is instantiated. Use a service provider's boot() method:

    public function boot(): void {
        Collection::macro('customMethod', function () { ... });
    }
    

Debugging Tips

  • Inspect Collections: Use dump() or toArray() to debug:
    collect($data)->dump(); // Dumps the collection
    
  • Memory Leaks: Monitor memory usage with memory_get_usage() when processing large collections.

Extension Points

  1. Custom Collectors: Extend the base Collection class for domain-specific logic:

    class UserCollection extends Collection {
        public function activeOnly() {
            return $this->where('active', true);
        }
    }
    
  2. Integration with Hyperf Pipes: Use collections in Hyperf's pipeable middleware or filters:

    $request->collect()->pipe([new ValidatePipe(), new TransformPipe()]);
    
  3. Serialization: Override jsonSerialize() for custom serialization:

    $collection->map(fn($item) => (object) $item)->jsonSerialize();
    

Hyperf-Specific Quirks

  • Coroutine Support: Collections are not natively coroutine-aware. For async operations, use Hyperf\AsyncQueue or Swoole\Coroutine.
  • Dependency Injection: Register the Collection facade in config/autoload.php if needed:
    'aliases' => [
        'Collection' => Hyperf\Collection\Collection::class,
    ],
    
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