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

Yii2 Collection Laravel Package

hiqdev/yii2-collection

Yii2 extension that integrates hiqdev/php-collection, providing collection data structures and helpers for Yii2 apps. Install via Composer and use a consistent, reusable collection API within your Yii2 project.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation:

    composer require hiqdev/yii2-collection
    

    Add to your Yii2 application's config/web.php (or relevant environment config):

    'components' => [
        'collection' => [
            'class' => 'hiqdev\yii2\collection\Collection',
        ],
    ],
    
  2. First Use Case: Convert an array to a collection and perform basic operations:

    use hiqdev\yii2\collection\Collection;
    
    $items = [1, 2, 3, 4, 5];
    $collection = new Collection($items);
    
    // Filter even numbers
    $evens = $collection->filter(function ($item) {
        return $item % 2 === 0;
    });
    
    // Map to strings
    $strings = $collection->map(function ($item) {
        return "Item: $item";
    });
    
  3. Key Methods to Explore:

    • filter(), map(), reduce(), each()
    • first(), last(), find(), contains()
    • sort(), reverse(), unique()

Implementation Patterns

Common Workflows

1. Data Transformation

Use map() to transform collections:

$users = new Collection($userData);
$userNames = $users->map(function ($user) {
    return $user['name'];
});

2. Filtering and Aggregation

Combine filter() and reduce() for complex logic:

$total = $orders->filter(function ($order) {
    return $order['status'] === 'completed';
})->reduce(function ($carry, $order) {
    return $carry + $order['amount'];
}, 0);

3. Integration with ActiveRecord

Convert ActiveQuery results to collections:

$users = User::find()->all();
$collection = new Collection($users);

// Group by role
$grouped = $collection->groupBy('role');

4. Custom Collection Classes

Extend Collection for domain-specific logic:

class UserCollection extends Collection {
    public function getAdmins() {
        return $this->filter(function ($user) {
            return $user->role === 'admin';
        });
    }
}

5. Lazy Loading with each()

Process large datasets without loading everything into memory:

$collection->each(function ($item) {
    // Process item (e.g., send email, log, etc.)
});

Integration Tips

  • Form Requests: Validate and process form data as collections:

    $requestData = new Collection($this->request->post());
    $validated = $requestData->filter(function ($value, $key) {
        return in_array($key, ['name', 'email']);
    });
    
  • API Responses: Transform Eloquent models to API-friendly collections:

    $response = new Collection($posts)
        ->map(function ($post) {
            return [
                'id' => $post->id,
                'title' => $post->title,
                'url' => route('posts.show', $post),
            ];
        });
    
  • Dependency Injection: Bind the collection component in your DI container:

    $container->bind('collection', function () {
        return new Collection();
    });
    

Gotchas and Tips

Pitfalls

  1. Immutable Operations: Methods like filter(), map(), and sort() return new collections and do not modify the original. Always reassign the result:

    // Wrong (original remains unchanged)
    $collection->filter(...);
    
    // Correct
    $filtered = $collection->filter(...);
    
  2. Key-Value Assumptions: The package assumes associative arrays or objects with accessible properties. Passing non-indexed arrays may lead to unexpected behavior:

    // Avoid if keys are not meaningful
    $collection = new Collection([10, 20, 30]);
    
  3. Performance with Large Datasets: Avoid chaining methods on massive datasets (e.g., ->filter()->map()->sort()). Use intermediate variables or each() for side effects.

  4. Default Values in getItem(): The getItem() method returns null for missing keys by default. Use getItem($key, $default) to provide fallbacks:

    $collection->getItem('nonexistent', []);
    

Debugging Tips

  • Inspect Raw Data: Use rawItems() to debug the underlying array:

    $raw = $collection->rawItems();
    
  • Method Chaining: Break down complex chains to isolate issues:

    $filtered = $collection->filter(...);
    $mapped = $filtered->map(...);
    
  • Type Safety: Validate input data before passing to collections:

    if (!is_array($data)) {
        throw new InvalidArgumentException('Expected array');
    }
    

Extension Points

  1. Custom Traits: Extend functionality by adding traits to your collection class:

    use hiqdev\yii2\collection\ManagerTrait;
    
    class CustomCollection extends Collection {
        use ManagerTrait;
    
        public function customMethod() {
            // ...
        }
    }
    
  2. Override Default Behavior: Subclass Collection and override methods like filter() or map():

    class StrictCollection extends Collection {
        public function filter($callback) {
            if (!is_callable($callback)) {
                throw new InvalidArgumentException('Callback must be callable');
            }
            return parent::filter($callback);
        }
    }
    
  3. Integration with Yii2 Behaviors: Attach collection logic to models via behaviors:

    class CollectionBehavior extends ModelBehavior {
        public function events() {
            return [
                Model::EVENT_AFTER_FIND => 'afterFind',
            ];
        }
    
        public function afterFind($event) {
            $this->owner->collection = new Collection($event->sender->attributes);
        }
    }
    

Configuration Quirks

  • Namespace Conflicts: Ensure hiqdev\yii2\collection does not conflict with other Collection classes in your project. Use fully qualified names:

    use hiqdev\yii2\collection\Collection as HiQCollection;
    
  • Legacy Yii1 Compatibility: Avoid mixing with Yii1-style collections or CArrayDataProvider. Stick to Yii2 conventions.

  • Static vs. Instance Methods: Prefer instance methods (e.g., $collection->filter()) over static helpers for consistency with Laravel’s Collection pattern.

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.
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
spatie/mailcoach-vapor