ramsey/collection
ramsey/collection is a PHP library for representing and manipulating typed collections. Provides data structures and APIs inspired by the Java Collections Framework, helping you store, validate, and work with groups of objects and values consistently.
Start by installing the package via Composer: composer require ramsey/collection. The core abstraction is Collection, which enforces a single value type (e.g., StringCollection, IntegerCollection). For maps with typed keys/values, use Map (e.g., UserByIdMap). Sets (via Set) enforce uniqueness, and Queue provides FIFO behavior. Begin by replacing loose arrays in service layer logic—e.g., switch array|int[] $ids to IntegerCollection—to gain immediate type safety and prevent accidental insertion of invalid types. The fromArray() static method offers the easiest migration path from legacy code: IntegerCollection::fromArray([1, 2, 3]).
public function getTags(): StringCollection) to enforce domain constraints and improve API clarity.Collection/Map in DTOs to ensure structured data integrity before processing (e.g., new StringCollection(['a', 'b', 'c']) avoids null or mixed-type surprises).class ProductCollection extends Collection) to add domain-specific behavior like avgPrice() or filterByCategory(), creating intention-revealing APIs.\ArrayAccess, \IteratorAggregate, and \Countable, so they work seamlessly with foreach, count(), and json_encode()—ideal for APIs and templates.ramsey/collection catches value mismatches at runtime (e.g., inserting a string into IntegerCollection throws TypeConstraintViolationException). Ensure tests cover edge cases to avoid silent failures in production.fromArray(): Passing untyped arrays to new Collection(['a', 1]) causes immediate validation—use fromArray() for safe initialization only when you’ve pre-validated input.Collection, override getType() to return the FQCN of your expected type (e.g., 'App\ValueObject\Email')—failure to do so causes getType() to default to 'mixed', disabling validation.toArray() before encoding or implement custom JsonSerializable.How can I help you explore Laravel packages today?