webcodr/collection

PHP 的集合库

安装: 165

依赖: 1

建议者: 0

安全性: 0

星星: 7

关注者: 2

分支: 0

语言:JavaScript

2.1.4 2013-06-08 22:04 UTC

This package is not auto-updated.

Last update: 2024-09-14 14:52:57 UTC


README

Build Status

PHP version

一组用于 PHP 的数组替换类

需求

  • PHP 5.4
  • Composer

设置

将 Collection 添加到您的项目中

$ php composer.phar require webcodr/collection:2.*

基本信息

Collections 提供两个类:MutableMap 和 ArrayMap

ArrayMap 通过实现 SPL 接口 ArrayAccess 扩展了 MutableMap

MutableMap 实现了 SPL 接口 IteratorAggregate 和 Countable。

这两个类都支持流畅的接口和方法链。没有特定返回值的函数,如 get()has(),将返回对象本身。

用法

少一点代码,胜过千言万语,下面是示例

完整的文档可以在 doc 目录中找到。(由于使用了 traits,所以可能有点小问题)

<?php

use Collection\MutableMap;

$map = new MutableMap([
    'name' => 'William Adama',
    'rank' => 'Admiral'
]);

// getter and setter methods
echo $map->get('name'); // result = William Adama
var_dump($map->has('name')); // result = true

$map->set('commands', 'BSG 75');

// iterator method (you also use foreach() on the $map object)
$map->each(function($value, $attribute) {
    echo "{$attribute}: {$value}";
});

// update attributes with an array
$map->update([
    'name' => 'Lee Adama',
    'rank' => 'Commander',
    'commands' => 'BSG 62'
]);

echo $map->get('name'); // result = Lee Adama

// fast access with first() and last()
$battlestars = new MutableMap('Galactica', 'Pegasus', 'Atlantia');
echo $battlestars->first(); // result = Galactica
echo $battlestars->last(); // result = Atlantia

// method chaining
echo $battlestars->reverse()->last(); // result = Galactica