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.
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',
],
],
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";
});
Key Methods to Explore:
filter(), map(), reduce(), each()first(), last(), find(), contains()sort(), reverse(), unique()Use map() to transform collections:
$users = new Collection($userData);
$userNames = $users->map(function ($user) {
return $user['name'];
});
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);
Convert ActiveQuery results to collections:
$users = User::find()->all();
$collection = new Collection($users);
// Group by role
$grouped = $collection->groupBy('role');
Extend Collection for domain-specific logic:
class UserCollection extends Collection {
public function getAdmins() {
return $this->filter(function ($user) {
return $user->role === 'admin';
});
}
}
each()Process large datasets without loading everything into memory:
$collection->each(function ($item) {
// Process item (e.g., send email, log, etc.)
});
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();
});
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(...);
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]);
Performance with Large Datasets:
Avoid chaining methods on massive datasets (e.g., ->filter()->map()->sort()). Use intermediate variables or each() for side effects.
Default Values in getItem():
The getItem() method returns null for missing keys by default. Use getItem($key, $default) to provide fallbacks:
$collection->getItem('nonexistent', []);
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');
}
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() {
// ...
}
}
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);
}
}
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);
}
}
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.
How can I help you explore Laravel packages today?