定制 originphp/collection 二次开发

按需修改功能、优化性能、对接业务系统,提供一站式技术支持

邮箱:yvsm@zunyunkeji.com | QQ:316430983 | 微信:yvsm316

originphp/collection

Composer 安装命令:

composer require originphp/collection

包简介

OriginPHP Collection

README 文档

README

license build coverage

You can create a Collection using arrays or an object which is an instance of Traversable.

Installation

To install this package

$ composer require originphp/collection

Creating a Collection

To create a collection:

use Origin\Collection\Collection;
$collection = new Collection($array);

There is also a helper function which you can use.

$collection = collection($array);

Collections

After you have finished manipulating the data you can use toArray or toList to convert the collection. Some methods return a boolean (e.g. every) or number (e.g median, average etc.), however most will return a new collection, which then can be chained through other methods.

Iteration Methods

Extract

Extracts a single column from a collection to create a list. You can use dot notation.

    $collection = collection($books);
    $authors = $collection->extract('authors.name');
    $list = $authors->toList();

You can also use a callback function :

    $collection = collection($books);
    $books = $collection->extract(function ($book) {
      return $book->name . ' written by ' . $book->author->name;
    });
    $list = $books->toList();

Each

Go through each item of the collection. You should note that each does not modify data. If you want to modify data then use map.

    $collection = new Collection($books);
    $collection->each(function ($value, $key) {
        echo "{$key} - {$value}";
    });

Map

This will iterate through each item in the collection and pass value through a callback which can modify the data and return it, creating a new collection in the process.

    $collection = new Collection([
        'a'=>1,'b'=>2,'c'=>3
        ]);

    // using a callable must return a value
    $plusOneCollection = $collection->map(function ($value, $key) {
        return $value + 1;
    });

Combine

Creates a new collection using keys and values.

    $collection = new Collection($results);
    $combined = $collection->combine('id', 'name'); 
    $array = $combined->toArray(); //[1=>'Tom','2'=>'James']

Results from combine can also be grouped by a third key.

    $collection = new Collection($results);
    $result => $collection->combine('id', 'name','profile'); 
    $array = $result->toArray(); // ['admin' => [1=>'tom',2=>'tim']]

Chunk

Chunks a collection into multiple parts

  $collection = new Collection([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]);
  $chunks = $collection->chunk(5);
  $array = $chunks->toArray();  // [[1,2,3,4,5],[6,7,8,9,10],[11,12]];

Filter Methods

Filter

Filters results using a callback function

    $collection = new Collection($books);
    $inStock = $collection->filter(function ($book) {
        return $book->in_stock ===  true;
    });

Reject

This is the inverse of filter.

    $collection = new Collection($books);
    $notInStock = $collection->reject(function ($book) {
        return $book->in_stock ===  true;
    });

Every

Run truth tests on every item in the collection.

    $collection = new Collection($books);
    $allBooksInStock = $collection->every(function ($book) {
        return $book->in_stock > 0;
    });
    if($allBooksInStock){
        ...
    }

Some

Check to see if at least one item matches the filter

    $collection = new Collection($books);
    $anyThingInStock = $collection->some(function ($book) {
        return $book->in_stock > 0;
    });
    if($anyThingInStock){
        ...
    }

Sorting

SortBy

Sorts a collection by a field or callback. To sort by a field, and you can use dot notation.

    $collection = new Collection($books);
    $sortedCollection = $collection->sortBy('authors.name');

To sort by a callback.

    $collection = new Collection($books);
    $sortedCollection = $collection->sortBy(function ($book) {
        return $book->author->name . '-' . $book->name;
    });

The sortBy method accepts 3 arguments, with the first argument being the path or a callback.

The second argument is the direction,which can be either SORT_DESC or SORT_ASC.

The third argument depends upon the data and the same flags used by PHP Sort, which include:

  • SORT_NUMERIC - for numbers
  • SORT_STRING - for strings
  • SORT_NATURAL - for natural ordering

Aggregation

Min

Gets the first item with the smallest value.

    $collection = new Collection($authors);
    $author = $collection->min('rating');

To sort by a callback.

    $collection = new Collection($books);
    $author = $collection->min(function ($book) {
        return $book->author->score;
    });

Max

Gets the first item with the smallest value.

    $collection = new Collection($books);
    $author = $collection->max('authors.rating');

To sort by a callback.

    $collection = new Collection($books);
    $author = $collection->max(function ($book) {
        return $book->author->score;
    });

Counting

SumOf

Gets the sum from a field or callback.

    $collection = new Collection($books);
    $inStock = $collection->sumOf('in_stock');

To get the sum using a callback

    $collection = new Collection($books);
    $points = $collection->sumOf(function ($book) {
        return $book->author->rating;
    });

Avg

Gets the average value from a field or callback.

    $collection = new Collection($books);
    $avgRating = $collection->avg('authors.rating');

To get the average value using a callback

    $collection = new Collection($books);
    $avgRating = $collection->avg(function ($book) {
        return $book->author->rating;
    });

Median

Gets the median value from a field or callback.

    $collection = new Collection($books);
    $median = $collection->median('authors.rating');

To get the median value using a callback

    $collection = new Collection($books);
    $median = $collection->median(function ($book) {
        return $book->author->rating;
    });

Count

This a function to count items in the collection, it is useful when working with other collection methods such as take or chunk.

    $collection = new Collection($books);
    $count = $collection->count();

CountBy

Counts by a field and value, and results are grouped.

    $collection = new Collection($books);
    $counts = $collection->countBy('authors.type'); // ['famous'=>10,'new'=>20]

You can also use a callback.

    // ['odd'=>2,'even'=>3]
    $collection = new Collection($books);
    $counts = $collection->countBy(function ($book) {
        return $book->id % 2 == 0 ? 'even' : 'odd';
    }); 

Grouping

GroupBy

Groups results by a field or callback.

    $collection = new Collection($books);
    $grouped = $collection->groupBy('authors.type');
    $array = $grouped->toArray();

You can also use a callback.

    $collection = new Collection($books);
    $grouped = $collection->groupBy(function ($book) {
        return $book->id % 2 == 0 ? 'even' : 'odd';
    });
    $array = $grouped->toArray();

Inserting Data

Insert

Inserts a value into a path for each item in the collection.

    $collection = new Collection($books);
    $newCollection = $collection->insert('authors.registered',true);
    $books = $newCollection->toArray();

Taking the same example, I will chain it using the helper function. This can be done with any method that returns a new collection.

    $books = collection($books)->insert('authors.registered',true)->toArray();

Other

Take

Take a number of items from a collection.

    $collection = new Collection($books);
    $firstLot = $collection->take(10);
    $secondLot = $collection->take(10,11);

originphp/collection 适用场景与选型建议

originphp/collection 是一款 基于 PHP 开发的 Composer 扩展包,目前已累计 580 次下载、GitHub Stars 达 1, 最近一次更新时间为 2019 年 10 月 11 日, 在 PHP 生态内属于活跃度较高的组件。

它主要适用于以下技术方向: 「collections」 「arrays」 「iterators」 「originPHP」 等业务场景。在实际项目中,围绕这些方向常见需要落地的问题包括:接口对接、性能调优、并发安全、与既有框架(Laravel / ThinkPHP / Yii / Webman 等)的兼容适配,以及生产环境的日志埋点与稳定性保障。

我们在过去多个企业项目中使用过 originphp/collection 或与其功能相近的方案,如果你在选型或落地过程中遇到问题,例如 版本兼容、二次改造、私有化封装、与内部系统对接、生产 BUG 排查,欢迎联系我们协助评估。

围绕 originphp/collection 我们能提供哪些服务?
定制开发 / 二次开发

基于 originphp/collection 在你已有业务上做功能扩展、字段裁剪、UI 适配、与内部账号 / 权限 / 日志系统的深度对接。

BUG 修复 & 性能优化

线上偶发问题、内存泄漏、慢查询、并发异常等排查修复;针对高流量场景做缓存、队列、索引层面的调优。

项目外包 & 长期维护

承接完整的项目从需求 → 设计 → 开发 → 上线 → 长期运维;也可按月提供技术保姆服务。

yvsm@zunyunkeji.com QQ:316430983 微信:yvsm316 西安尊云信息科技 · 专注 PHP / Go / 分布式系统研发

统计信息

  • 总下载量: 580
  • 月度下载量: 0
  • 日度下载量: 0
  • 收藏数: 1
  • 点击次数: 7
  • 依赖项目数: 1
  • 推荐数: 0

GitHub 信息

  • Stars: 1
  • Watchers: 1
  • Forks: 0
  • 开发语言: PHP

其他信息

  • 授权协议: MIT
  • 更新时间: 2019-10-11