somnambulist/collection
Composer 安装命令:
composer require somnambulist/collection
包简介
Collection implementation with no dependencies.
关键字:
README 文档
README
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
Requirements
- PHP 8.4+
- ext-json for JSON export
Installation
Install using composer, or checkout / pull the files from github.com.
- composer require somnambulist/collection
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.3
- traits should not specify a return type but must include a docblock return type
- return types for the Collection must be
staticto 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
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
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 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.:
namewould be translated toname() - object
getmethods e.g:namewould be translated togetName()
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
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(<alias>)->someMethod()$collection-><alias>->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
The collection behaviour docs are generated from the source code and are available in the docs folder.
Factory Methods
On the collection class
collect()create a new Collection staticallycreate()create a new Collection statically
As helpers in the FactoryUtils
createFromIniString()create a Collection from an ini style stringcreateFromString()split an encoded string into a CollectioncreateFromUrl()given a URL returns a Collection after usingparse_url()createFromUrlQuery()converts a URL query string to a Collection usingparse_str()createWithNestedArrayFromKeyconverts a key likeuser.addresses.hometo a nested collectionexplode()explode a string into a Collection
Methods by Group
| Aggregates | Assertable | Comparable | Exportable | Filterable | Mappable |
|---|---|---|---|---|---|
| average | assert | diff | jsonSerialize | filter | collapse |
| max | diffUsing | toArray | matching | flatMap | |
| median | diffAssoc | toJson | notMatching | flatten | |
| min | diffAssocUsing | toQueryString | reject | map | |
| modal | diffKeys | toString | except | mapInto | |
| sum | diffKeysUsing | serialize | has | reduce | |
| countBy | intersect | unserialize | hasAllOf | ||
| intersectByKeys | hasAnyOf | ||||
| hasNoneOf | |||||
| keys | |||||
| keysMatching | |||||
| only | |||||
| with | |||||
| without | |||||
| matchingRule |
| Mutable | Partitionable | Queryable | Runnable | String Helpers |
|---|---|---|---|---|
| add | groupBy | all | each | capitalize |
| append | partition | contains | pipe | lower |
| concat | slice | doesNotContain | pipeline | trim |
| combine | splice | extract | run | upper |
| clear | find | |||
| combine | findLast | |||
| fill | first | |||
| fillKeysWith | get | |||
| flip | last | |||
| merge | has | |||
| pad | random | |||
| pop | removeEmpty | |||
| prepend | removeNulls | |||
| push | sort | |||
| remapKeys | sortBy | |||
| remove | value | |||
| replace | values | |||
| replaceRecursively | ||||
| reverse | ||||
| set | ||||
| shift | ||||
| shuffle | ||||
| union | ||||
| unset | ||||
| when |
Magic Methods & PHP Interface Methods
- getIterator
- offsetGet
- offsetExists
- offsetSet
- offsetUnset
- __get
- __isset
- __set
- __set_state
- __unset
somnambulist/collection 适用场景与选型建议
somnambulist/collection 是一款 基于 PHP 开发的 Composer 扩展包,目前已累计 57.75k 次下载、GitHub Stars 达 11, 最近一次更新时间为 2017 年 01 月 22 日, 在 PHP 生态内属于活跃度较高的组件。
它主要适用于以下技术方向: 「set」 「domain」 「collection」 等业务场景。在实际项目中,围绕这些方向常见需要落地的问题包括:接口对接、性能调优、并发安全、与既有框架(Laravel / ThinkPHP / Yii / Webman 等)的兼容适配,以及生产环境的日志埋点与稳定性保障。
我们在过去多个企业项目中使用过 somnambulist/collection 或与其功能相近的方案,如果你在选型或落地过程中遇到问题,例如 版本兼容、二次改造、私有化封装、与内部系统对接、生产 BUG 排查,欢迎联系我们协助评估。
基于 somnambulist/collection 在你已有业务上做功能扩展、字段裁剪、UI 适配、与内部账号 / 权限 / 日志系统的深度对接。
线上偶发问题、内存泄漏、慢查询、并发异常等排查修复;针对高流量场景做缓存、队列、索引层面的调优。
承接完整的项目从需求 → 设计 → 开发 → 上线 → 长期运维;也可按月提供技术保姆服务。
与 somnambulist/collection 相关的其它包
同方向 / 同关键字的高下载量 PHP Composer 包推荐,方便对比选型:
Simple, immutable data structures
This package provides type-safe extension of the laravel collection, forcing a single type of object.
Baum is an implementation of the Nested Set pattern for Eloquent models.
Traits to build collections of specific objects
Build a domain-oriented application on Laravel Framework
Command bus implementation: Commands and domain events
统计信息
- 总下载量: 57.75k
- 月度下载量: 0
- 日度下载量: 0
- 收藏数: 11
- 点击次数: 15
- 依赖项目数: 9
- 推荐数: 0
其他信息
- 授权协议: MIT
- 更新时间: 2017-01-22