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

Collection Laravel Package

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.

View on GitHub
Deep Wiki
Context7

Getting Started

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]).

Implementation Patterns

  • Domain Layer Modeling: Declare typed collections as return types in entities and value objects (e.g., public function getTags(): StringCollection) to enforce domain constraints and improve API clarity.
  • DTO Validation: Embed Collection/Map in DTOs to ensure structured data integrity before processing (e.g., new StringCollection(['a', 'b', 'c']) avoids null or mixed-type surprises).
  • API Input/Output Handling: Parse request payloads into typed collections—especially useful for arrays of IDs, names, or nested objects—ensuring downstream code never handles untrusted raw arrays.
  • Custom Subclasses: Extend base classes (e.g., class ProductCollection extends Collection) to add domain-specific behavior like avgPrice() or filterByCategory(), creating intention-revealing APIs.
  • Interoperability: Collections implement \ArrayAccess, \IteratorAggregate, and \Countable, so they work seamlessly with foreach, count(), and json_encode()—ideal for APIs and templates.

Gotchas and Tips

  • Type Enforcement is Runtime-Only: PHP’s type safety is compile-time only in strict mode; 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.
  • Constructor vs fromArray(): Passing untyped arrays to new Collection(['a', 1]) causes immediate validation—use fromArray() for safe initialization only when you’ve pre-validated input.
  • Extensibility Quirk: When extending 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.
  • JSON Serialization: Collections serialize as arrays by default. To preserve type information (e.g., for API responses), manually cast to toArray() before encoding or implement custom JsonSerializable.
  • Performance Note: For large datasets (e.g., 10k+ items), prefer native arrays or generators if memory is critical—collections add object overhead. Benchmarks show ~10–20% slowdown vs raw arrays for frequent appends. Use collections where clarity and correctness outweigh raw speed.
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.
davejamesmiller/laravel-breadcrumbs
artisanry/parsedown
christhompsontldr/phpsdk
enqueue/dsn
bunny/bunny
enqueue/test
enqueue/null
enqueue/amqp-tools
bower-asset/punycode
bower-asset/inputmask
bower-asset/jquery
bower-asset/yii2-pjax
laravel/nova
spatie/laravel-mailcoach
spatie/laravel-superseeder
laravel/liferaft
nst/json-test-suite
danielmiessler/sec-lists
jackalope/jackalope-transport
twbs/bootstrap4