wp-starter/collections
Laravel-friendly collection utilities for WordPress projects. Adds helpful helpers and abstractions around arrays and iterable data to make transforming, filtering, and mapping data easier in WP-driven apps, plugins, and themes with a modern PHP approach.
Installation
composer require wp-starter/collections
Ensure autoload is dumped:
composer dump-autoload
Basic Usage Import the core class:
use WpStarter\Collections\Collection;
Initialize with an array:
$collection = new Collection([1, 2, 3]);
First Use Case: Filtering Posts
$posts = new Collection($wpdb->get_results("SELECT * FROM posts"));
$published = $posts->where('post_status', 'publish');
Chaining Methods
$filtered = $collection
->where('status', 'active')
->sortBy('created_at')
->take(10);
Integration with Eloquent
$users = User::all()->toBase()->pipe(function ($users) {
return new Collection($users);
});
Custom Collections
class PostCollection extends Collection {
public function published() {
return $this->where('post_status', 'publish');
}
}
Service Provider Binding
$this->app->bind(Collection::class, function () {
return new Collection();
});
Macro Extensions
Collection::macro('activeOnly', function () {
return $this->where('is_active', true);
});
API Response Formatting
return response()->json($collection->map(fn ($item) => $item->toArray()));
Immutable Operations
Methods like where(), sortBy(), etc., return new instances. Use -> chaining or reassign:
$filtered = $collection->where(...); // Correct
$collection->where(...); // Silent failure (original unchanged)
Array vs. Object Handling
Collections assume array-like access. For objects, ensure get()/set() methods exist or use ->toArray() first.
Performance with Large Datasets
Avoid eager-loading entire tables into a Collection. Use database cursors or chunking:
$collection = new Collection();
$wpdb->get_results("SELECT * FROM large_table", ARRAY_A, $collection);
Inspect Internals
$collection->dump(); // Dumps the underlying array
Check for Mutations
Use tap() to debug intermediate steps:
$collection->tap(fn ($c) => Log::debug($c->all()));
Custom Comparators
Collection::macro('customSort', function () {
return $this->sortBy(function ($item) {
return $item->customProperty;
});
});
Override Default Behavior
Extend the class and modify get(), set(), or offsetGet() methods.
Leverage Laravel’s Collection Synergy
Use merge(), concat(), or crossJoin() for advanced operations:
$merged = $collection->merge($anotherCollection);
No Built-in Config
The package is lightweight; no config/collections.php exists. All logic is method-based.
Type Safety
No native type hints (e.g., array|object). Validate inputs manually if needed:
if (!is_array($data)) {
throw new \InvalidArgumentException('Expected array');
}
How can I help you explore Laravel packages today?