PHPackages                             somnambulist/collection - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. [Utility &amp; Helpers](/categories/utility)
4. /
5. somnambulist/collection

ActiveLibrary[Utility &amp; Helpers](/categories/utility)

somnambulist/collection
=======================

Collection implementation with no dependencies.

5.5.1(1y ago)1153.8k↓15.2%29MITPHPPHP &gt;=8.1

Since Jan 22Pushed 1y ago4 watchersCompare

[ Source](https://github.com/somnambulist-tech/collection)[ Packagist](https://packagist.org/packages/somnambulist/collection)[ RSS](/packages/somnambulist-collection/feed)WikiDiscussions master Synced 1mo ago

READMEChangelog (7)Dependencies (4)Versions (42)Used By (9)

Somnambulist Collection Library
===============================

[](#somnambulist-collection-library)

[![GitHub Actions Build Status](https://camo.githubusercontent.com/050ee2a9771775daec98ff6a03988cbb72b8ebb04265387c64ebf3fd9202949c/68747470733a2f2f696d672e736869656c64732e696f2f6769746875622f616374696f6e732f776f726b666c6f772f7374617475732f736f6d6e616d62756c6973742d746563682f636f6c6c656374696f6e2f74657374732e796d6c3f6c6f676f3d676974687562266272616e63683d6d6173746572)](https://github.com/somnambulist-tech/collection/actions?query=workflow%3Atests)[![Issues](https://camo.githubusercontent.com/06add08d10da861321feb1d2ee0cdd3a6d3d58a8dbc9c7b9a1abb8afd08a4843/68747470733a2f2f696d672e736869656c64732e696f2f6769746875622f6973737565732f736f6d6e616d62756c6973742d746563682f636f6c6c656374696f6e3f6c6f676f3d676974687562)](https://github.com/somnambulist-tech/collection/issues)[![License](https://camo.githubusercontent.com/002e484eb3da33071eeb99d4fce482902256456acbaa2eb05ad8d1c7eba2f139/68747470733a2f2f696d672e736869656c64732e696f2f6769746875622f6c6963656e73652f736f6d6e616d62756c6973742d746563682f636f6c6c656374696f6e3f6c6f676f3d676974687562)](https://github.com/somnambulist-tech/collection/blob/master/LICENSE)[![PHP Version](https://camo.githubusercontent.com/526b32b551b6bad4a88f81da4244a776abafee9626c94f1d95097f33809b9ca6/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f7068702d762f736f6d6e616d62756c6973742f636f6c6c656374696f6e3f6c6f676f3d706870266c6f676f436f6c6f723d7768697465)](https://packagist.org/packages/somnambulist/collection)[![Current Version](https://camo.githubusercontent.com/bd7569153e8a859f3bf5077e4c7f15ee37ad5275cf6eff7fcf8365946ab50f01/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f762f736f6d6e616d62756c6973742f636f6c6c656374696f6e3f6c6f676f3d7061636b6167697374266c6f676f436f6c6f723d7768697465)](https://packagist.org/packages/somnambulist/collection)

Somnambulist Collection provides a framework for making collections and pseudo sets of your own. It has been completely re-worked from the previous versions into a set of behaviours (traits) and some common interfaces grouped around function.

The basic "Collection" is an interface that extends ArrayAccess, IteratorAggregate and Countable; and adds Arrayable and Jsonable as common requirements. Then the basic methods are:

```
public function all(): array;
public function contains($value): bool;
public function doesNotContain($value): bool;
public function each(callable $callback);
public function filter($criteria = null);
public function first();
public function get($key, $default = null);
public function has(...$key): bool;
public function keys($search = null);
public function last();
public function map(callable $callable);
public function value($key, $default = null);
public function values();
```

From this, additional functionality is added by interface and traits - or implement your own. The goal is to allow for a set of small, re-usable, well tested functions that can be combined to provide the functionality you need, instead of a single monolithic collection class that does everything and more.

Of course out of the box, several standard implementations are included.

This is heavily inspired by Doctrine ArrayCollection and of course Laravel Collection along with ideas from Lithium framework, ez Components, CakePHP and more.

If you see something missing or have suggestions for other methods, submit a PR or ticket! Adding functions is easy with the trait system and if you think that the groupings need work, suggest a better name!

### Change History

[](#change-history)

- [V3 Deprecations, API changes](CHANGELOG_V3.md)
- [V4 Deprecations, API changes](CHANGELOG_V4.md)
- [V5 Deprecations, API changes](CHANGELOG_V5.md)

Requirements
------------

[](#requirements)

- PHP 8.0+
- ext-json for JSON export

Installation
------------

[](#installation)

Install using composer, or checkout / pull the files from github.com.

- composer require somnambulist/collection

Contributing
------------

[](#contributing)

Contributions are more than welcome! Whether doc improvements, new methods or bug fixes. In all cases, fork the repository, make a branch then submit a PR - the usual GitHub flow.

Please consider the following:

- the minimum version of PHP is 8.0
- traits should not specify a return type but must include a docblock return type
- return types for the Collection must be `static` to allow runtime resolution
- all trait methods must have docblocks - these are converted to docs
- if a trait uses code from elsewhere, it should be attributed whenever possible
- consider the type of operation and if it will work in a Set or a Frozen collection
- tests should be included

Remember that the Collection could be a Set or Frozen, so often it is necessary to operate on the values and then create a new collection after processing. See the current implementations for examples.

Built-in Collections
--------------------

[](#built-in-collections)

There are several types of collection that all implement the Collection interface with varying levels of functionality:

- SimpleCollection - a very basic, Doctrine ArrayCollection like style collection
- MutableCollection - more like Laravel Collection, supports dot notation accessing
- FrozenCollection - more like a Symfony Frozen ParameterBag, but more, with dot notation
- MutableSet - a pseudo set that does not allow duplicate values, but does allow string keys.

There's no frozen set, but if you freeze a MutableSet; you have yourself a FrozenSet.

Usage
-----

[](#usage)

Instantiate with an array or other collection of items:

```
$collection = MutableCollection::collect($items);
$collection->map()->filter()...
```

Freeze changes to a collection:

```
$locked = $collection->freeze();

// raises exception
$locked->shift();
```

Use a custom Immutable collection class:

```
MutableCollection::setFreezeableClass();
$locked = $collection->freeze();

// raises exception
$locked->shift();
```

### Dot Access

[](#dot-access)

Dot access is available on:

- has\*
- get
- extract
- aggregate functions

For example: `users.*.name` would fetch the name from all elements in the users key space. Dot access can call into:

- arrays
- Collections
- public object properties
- object return methods e.g.: `name` would be translated to `name()`
- object `get` methods e.g: `name` would be translated to `getName()`

If the key name uses snake casing e.g.: user\_address, this will be converted to UserAddress for method access checks.

A default can be supplied with `get()` that if the specified key does not exist, it will be used instead. The default can be a closure. Note: that this will be called for all elements e.g: `users.*.age` with a default that returned `0`, would return 0 for all matching users without an age present.

Key walking is implemented in a standalone class allowing it to be re-used in other classes. This functionality is based on Laravel's `data_get()` and `Arr::pluck()`, modified to support getter methods and default handling when extracting from objects.

Proxy Helpers
-------------

[](#proxy-helpers)

New in v4 is an expansion of the run/map proxies used to make operations across the set. Now additional proxies can be bound to virtual properties that can be accessed at runtime. This allows for additional custom behaviour or the creation of mini Domain Specific Languages within the collection.

It is recommended when adding additional proxy options, that this is done in a child class of the collection so that the options can be documented using `@property-read` declarations in the class docblock. By default `run` and `map` are pre-bound in the built-in collections, however these can be overridden if necessary.

Proxies are lazy instantiated when accessed so should have a minimal impact on performance. For most cases the proxy is mapped by the full qualified class name to an alias, but for more complex construction a closure can be used.

The proxy can be called by:

- `$collection->proxy()->someMethod()`
- `$collection->->someMethod()`

For example: to run the method `setDateTo()` on a collection of objects that have this method:

- `$collection->run->setDateTo(new DateTime())` or
- `$collection->proxy('run')->setDateTo(new DateTime())`

Method Index
------------

[](#method-index)

The collection behaviour docs are generated from the source code and are available in the `docs` folder.

### Factory Methods

[](#factory-methods)

#### On the collection class

[](#on-the-collection-class)

- `collect()` create a new Collection statically
- `create()` create a new Collection statically

#### As helpers in the FactoryUtils

[](#as-helpers-in-the-factoryutils)

- `createFromIniString()` create a Collection from an ini style string
- `createFromString()` split an encoded string into a Collection
- `createFromUrl()` given a URL returns a Collection after using `parse_url()`
- `createFromUrlQuery()` converts a URL query string to a Collection using `parse_str()`
- `createWithNestedArrayFromKey` converts a key like `user.addresses.home` to a nested collection
- `explode()` explode a string into a Collection

### Methods by Group

[](#methods-by-group)

[Aggregates](docs/aggregates.md)[Assertable](docs/assertable.md)[Comparable](docs/comparable.md)[Exportable](docs/exportable.md)[Filterable](docs/queryable.md)[Mappable](docs/mappable.md)averageassertdiffjsonSerializefiltercollapsemaxdiffUsingtoArraymatchingflatMapmediandiffAssoctoJsonnotMatchingflattenmindiffAssocUsingtoQueryStringrejectmapmodaldiffKeystoStringexceptmapIntosumdiffKeysUsingserializehasreducecountByintersectunserializehasAllOfintersectByKeyshasAnyOfhasNoneOfkeyskeysMatchingonlywithwithoutmatchingRule[Mutable](docs/mutateable.md)[Partitionable](docs/partitionable.md)[Queryable](docs/queryable.md)[Runnable](docs/runnable.md)[String Helpers](docs/string_helpers.md)addgroupByalleachcapitalizeappendpartitioncontainspipelowerconcatslicedoesNotContainpipelinetrimcombinespliceextractrunupperclearfindcombinefindLastfillfirstfillKeysWithgetfliplastmergehaspadrandompopremoveEmptyprependremoveNullspushsortremapKeyssortByremovevaluereplacevaluesreplaceRecursivelyreversesetshiftshuffleunionunsetwhen### Magic Methods &amp; PHP Interface Methods

[](#magic-methods--php-interface-methods)

- getIterator
- offsetGet
- offsetExists
- offsetSet
- offsetUnset
- \_\_get
- \_\_isset
- \_\_set
- \_\_set\_state
- \_\_unset

###  Health Score

49

—

FairBetter than 95% of packages

Maintenance38

Infrequent updates — may be unmaintained

Popularity37

Limited adoption so far

Community22

Small or concentrated contributor base

Maturity84

Battle-tested with a long release history

 Bus Factor1

Top contributor holds 95.5% of commits — single point of failure

How is this calculated?**Maintenance (25%)** — Last commit recency, latest release date, and issue-to-star ratio. Uses a 2-year decay window.

**Popularity (30%)** — Total and monthly downloads, GitHub stars, and forks. Logarithmic scaling prevents top-heavy scores.

**Community (15%)** — Contributors, dependents, forks, watchers, and maintainers. Measures real ecosystem engagement.

**Maturity (30%)** — Project age, version count, PHP version support, and release stability.

###  Release Activity

Cadence

Every ~71 days

Recently: every ~269 days

Total

41

Last Release

537d ago

Major Versions

1.3.0 → 2.0.02017-06-23

2.2.0 → 3.0.02019-07-11

3.3.2 → 4.0.02020-08-26

4.x-dev → 5.0.02021-01-20

PHP version history (6 changes)1.0.0PHP &gt;=5.6.0

2.0.0PHP &gt;=7

3.0.0PHP &gt;=7.2

4.0.0PHP &gt;=7.4

5.0.0PHP &gt;=8.0

5.4.0PHP &gt;=8.1

### Community

Maintainers

![](https://www.gravatar.com/avatar/c0e439bf91b68c2e81e0250c752d3a552e78752c91acdf00c72a1f93aeb1ceca?d=identicon)[dredfern](/maintainers/dredfern)

---

Top Contributors

[![dave-redfern](https://avatars.githubusercontent.com/u/1477147?v=4)](https://github.com/dave-redfern "dave-redfern (42 commits)")[![Garethp](https://avatars.githubusercontent.com/u/709912?v=4)](https://github.com/Garethp "Garethp (1 commits)")[![paulmaclean](https://avatars.githubusercontent.com/u/3999001?v=4)](https://github.com/paulmaclean "paulmaclean (1 commits)")

---

Tags

collectioncomposerphpsetcollectiondomain

###  Code Quality

TestsPHPUnit

### Embed Badge

![Health badge](/badges/somnambulist-collection/health.svg)

```
[![Health](https://phpackages.com/badges/somnambulist-collection/health.svg)](https://phpackages.com/packages/somnambulist-collection)
```

###  Alternatives

[phpcollection/phpcollection

General-Purpose Collection Library for PHP

1.0k64.0M34](/packages/phpcollection-phpcollection)[marc-mabe/php-enum

Simple and fast implementation of enumerations with native PHP

49644.8M97](/packages/marc-mabe-php-enum)[chdemko/sorted-collections

Sorted Collections for PHP &gt;= 8.2

222.5M3](/packages/chdemko-sorted-collections)

PHPackages © 2026

[Directory](/)[Categories](/categories)[Trending](/trending)[Changelog](/changelog)[Analyze](/analyze)
