定制 n11t/abstract-collection 二次开发

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

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

n11t/abstract-collection

Composer 安装命令:

composer require n11t/abstract-collection

包简介

Abstract collection to handle object lists

README 文档

README

pipeline status coverage report

AbstractCollection

The AbstractCollection can be used to created typed lists.

Why?

With php7 the language improved a lot. But it's still not possible to use generics or typed arrays as parameter or return value. So we have to use a workaround.

With this abstract class you are able to build your own typed collection.

Usage

Extend from the AbstractCollection class and override the constructor.

class ProductCollection extends \N11t\AbstractCollection\AbstractCollection {

    public function __construct(Product ...$products)
    {
        $this->values = $products;
    }
}

Now you can type hint a collection of products everywhere in your code and be sure you get one.

Sampe Code

<?php
declare(strict_types=1);

require_once __DIR__ . '/vendor/autoload.php';

// Extend from AbstractCollection
class IntCollection extends \N11t\AbstractCollection\AbstractCollection {

    public function __construct(int ...$values)
    {
        $this->values = $values;
    }
}

// Type hint for collections instead of array
function write_ln(string $context, IntCollection $collection) {
    echo $context . PHP_EOL;

    // Iterate over
    foreach ($collection as $item) {
        echo $item . PHP_EOL;
    }
}

// Initialize typed collection.
$integer = [1,2,3,4,5];
$collection = new IntCollection(...$integer);

// Count collection
echo 'Collection count: ' . \count($collection) . PHP_EOL;

// Sort collection
write_ln('pre sort', $collection);
$collection->usort(function (int $a, int $b) {
    return $b <=> $a;
});
write_ln('post sort', $collection);

// Filter collection
$filteredCollection = $collection->filter(function(int $value, $key) {
   return $value % 2 === 0 || $key === 0;
}, \ARRAY_FILTER_USE_BOTH);

// Use toArray to get values
var_dump($collection->toArray());

Output

Collection count: 5
pre sort
1 2 3 4 5 
post sort
5 4 3 2 1 
array(3) {
  [0]=>
  int(5)
  [1]=>
  int(4)
  [3]=>
  int(2)
}

统计信息

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

GitHub 信息

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

其他信息

  • 授权协议: MIT
  • 更新时间: 2018-03-06

承接程序开发

PHP开发

VUE

Vue开发

前端开发

小程序开发

公众号开发

系统定制

数据库设计

云部署

网站建设

安全加固