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

Php Collection Laravel Package

hiqdev/php-collection

Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation Add the package via Composer:

    composer require hiqdev/php-collection
    

    No additional configuration is required—it’s a drop-in library.

  2. First Use Case Replace Laravel’s native Collection with HiQDev\Collection\Collection for enhanced functionality:

    use HiQDev\Collection\Collection;
    
    $items = new Collection([1, 2, 3, 4, 5]);
    $evenSquares = $items->filter(fn($n) => $n % 2 === 0)
                        ->map(fn($n) => $n ** 2)
                        ->all();
    // Output: [4, 16]
    
  3. Where to Look First

    • Documentation: Check the GitHub README (if available) or inspect the source (vendor/hiqdev/php-collection/src/).
    • Key Classes: Focus on HiQDev\Collection\Collection and its methods (e.g., groupBy, diff, except).
    • Laravel Integration: Override Laravel’s Collection facade in config/app.php (if needed):
      'aliases' => [
          'Collection' => HiQDev\Collection\Collection::class,
      ],
      

Implementation Patterns

Core Workflows

  1. Data Transformation Use map, filter, and reduce for declarative operations:

    $users = new Collection([
        ['name' => 'Alice', 'age' => 30],
        ['name' => 'Bob', 'age' => 25],
    ]);
    $names = $users->pluck('name')->implode(', '); // "Alice, Bob"
    
  2. Grouping and Aggregation Leverage groupBy and countBy for analytics:

    $orders = new Collection([
        ['product' => 'Laptop', 'status' => 'shipped'],
        ['product' => 'Mouse', 'status' => 'pending'],
    ]);
    $grouped = $orders->groupBy('status');
    // ['shipped' => [...], 'pending' => [...]]
    
  3. Set Operations Use diff, intersect, or merge for array comparisons:

    $activeUsers = new Collection([1, 2, 3]);
    $inactiveUsers = new Collection([3, 4, 5]);
    $uniqueActive = $activeUsers->diff($inactiveUsers); // [1, 2]
    
  4. Lazy Evaluation Chain methods with lazy() for performance-critical pipelines:

    $largeData = new Collection(range(1, 1_000_000));
    $result = $largeData->lazy()
                        ->filter(fn($n) => $n % 7 === 0)
                        ->take(10)
                        ->toArray();
    

Laravel Integration Tips

  • Service Providers: Bind the collection class in a service provider for consistency:
    $this->app->bind(
        Illuminate\Support\Collection::class,
        HiQDev\Collection\Collection::class
    );
    
  • Custom Macros: Extend the collection with domain-specific methods:
    Collection::macro('snakeCaseKeys', function () {
        return $this->mapWithKeys(fn($item) => [
            Str::snake(key($item)) => $item,
        ]);
    });
    

Gotchas and Tips

Pitfalls

  1. Backward Compatibility

    • Some methods (e.g., pluck) may behave differently than Laravel’s Collection. Test edge cases:
      $collection = new Collection([['id' => 1], ['id' => 2]]);
      $collection->pluck('id'); // Returns [1, 2] (vs. Laravel's object-like access).
      
    • Fix: Use ->all() or ->toArray() if expecting arrays.
  2. Performance Overhead

    • The package adds abstraction layers. For micro-optimizations, use native PHP arrays:
      // Avoid:
      $collection->filter(...)->map(...)->count();
      // Prefer:
      array_filter($array, ...);
      
  3. Missing Laravel Features

    • No built-in support for Laravel’s when, tap, or unless methods. Reimplement or use native PHP:
      $collection->when($condition, fn($coll) => $coll->filter(...));
      

Debugging Tips

  • Method Introspection: Use getMethods() to list available methods:
    print_r(get_class_methods(HiQDev\Collection\Collection::class));
    
  • Lazy Evaluation Debugging: Add ->dump() or ->toArray() to inspect intermediate states:
    $result = $collection->lazy()->filter(...)->dump()->take(5);
    

Extension Points

  1. Custom Iterators Implement IteratorAggregate for bespoke traversal:

    class CustomCollection extends Collection implements IteratorAggregate {
        public function getIterator() {
            return new CustomIterator($this->items);
        }
    }
    
  2. Type-Safe Collections Use PHP 8’s array_object or generics (via mypy or phpstan) to enforce types:

    /** @var Collection<int, User> */
    $users = new Collection([], [], User::class);
    
  3. Serialization Override jsonSerialize() for custom output:

    Collection::macro('jsonSerialize', function () {
        return $this->map(fn($item) => (array) $item)->toArray();
    });
    

Configuration Quirks

  • No Config File: The package is self-contained; no config/hiqdev-collection.php exists.
  • Namespace Collisions: Avoid naming conflicts by aliasing:
    use Collection as HiQCollection;
    
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.
make-dev/orca
dmstr/symfony-system-resources-bundle
dmstr/symfony-job-queue-bundle
dmstr/openapi-json-schema-bundle
dmstr/keycloak-security-bundle
dmstr/doctrine-audit-log-bundle
dmstr/api-platform-utils-bundle
dmstr/api-configuration-bundle
chrisdev/ux-components
baks-dev/finances
emuniq/filament-browser-notifications
syriable/filament-translator
hungnm28/livewire-form
wenprise/eloquent
crudly/encrypted
fadion/bouncy
cuci/prototurk-sdk
gos/pubsub-router-bundle
cuci/prototurk-sdk-symfony
clementtalleu/easyadmin-markdown-bundle