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.
Installation:
composer require hyperf/collection
The package is a direct port of Laravel's Illuminate\Support\Collection, so no additional configuration is required.
First Usage:
use Hyperf\Collection\Collection;
$collection = new Collection([1, 2, 3]);
$filtered = $collection->filter(fn($item) => $item > 1); // Returns [2, 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).
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',
]);
Chaining Methods: Collections support fluent method chaining for readability:
$result = collect($data)
->filter(fn($item) => $item['active'])
->sortBy('priority')
->values()
->all();
Grouping and Aggregation:
$grouped = collect($orders)
->groupBy('customer_id')
->mapToGroups(fn($order) => [$order['customer_id'] => $order['total']])
->sum();
Integration with Hyperf Components:
collect() on Eloquent or Hyperf DB query results:
$users = collect(UserModel::query()->get());
$validated = collect($request->input())->only(['name', 'email']);
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,
]);
});
lazy() for large datasets to avoid loading everything into memory:
$lazy = collect($hugeArray)->lazy()->filter(...);
collect($items)->chunk(100)->each(function ($chunk) {
// Process chunk
});
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]
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
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 () { ... });
}
dump() or toArray() to debug:
collect($data)->dump(); // Dumps the collection
memory_get_usage() when processing large collections.Custom Collectors:
Extend the base Collection class for domain-specific logic:
class UserCollection extends Collection {
public function activeOnly() {
return $this->where('active', true);
}
}
Integration with Hyperf Pipes: Use collections in Hyperf's pipeable middleware or filters:
$request->collect()->pipe([new ValidatePipe(), new TransformPipe()]);
Serialization:
Override jsonSerialize() for custom serialization:
$collection->map(fn($item) => (object) $item)->jsonSerialize();
Hyperf\AsyncQueue or Swoole\Coroutine.Collection facade in config/autoload.php if needed:
'aliases' => [
'Collection' => Hyperf\Collection\Collection::class,
],
How can I help you explore Laravel packages today?