shrikeh/collections

不可变集合中的可重用特性

v1.0.4 2017-01-03 13:58 UTC

This package is auto-updated.

Last update: 2024-09-06 03:31:34 UTC


README

build_status_img code_quality_img latest_stable_version_img latest_unstable_version_img license_img twitter_img

基于特性的辅助库,用于处理PHP中不可变集合的繁重工作。

概述

这个低级库只是创建不可变集合的特性,可以节省时间。由于PHP 7可以使用返回类型提示,我决定,如果有可能从方法返回0-n个对象,我总是返回一个Collection,然后可以将返回值类型提示为Collection,无论是否为空。PHP不支持原生的不可变迭代器,所以当我使用领域驱动设计并且需要一组可迭代的值对象时,我必须做同样的样板重工作。

这种模式对我很成功,因为我也可以为Collections本身进行强类型检查,因此它们只能包含给定类型的对象。我还通常使它们不可变,所以如果你尝试设置或取消设置值,它们将抛出DomainException的子类。

因此,随着我更频繁地使用这些,我将它们拆分成特质以供代码跨项目重用。请随意使用,它们很小,只需为我处理样板工作。

安装

推荐使用无处不在且具有开创性的composer进行安装

composer require --prefer-dist shrikeh/collections

使用

该库包含约十多个特性,有助于匹配核心PHP和SPL接口,如ArrayAccessOuterIterator。通常我有一个内部的“存储”,并确保直接访问此存储被删除,包括可变方法,如offsetSet()offsetUnset()。这确保了只能迭代构造函数中添加的值。

例如,要创建只能包含SomeObject对象的Collection

<?php

namespace Shrikeh\Collection\Examples;

use IteratorIterator;
use Shrikeh\Collection\Examples\SomeObject;

/**
 * An immutable iterator that can only contain SomeObject objects.
 */
final class ImmutableSomeObjectCollection extends IteratorIterator
{
    use \Shrikeh\Collection\NamedConstructorsTrait;   # Give it named constructors
    use \Shrikeh\Collection\ImmutableCollectionTrait; # Give it read-only array access
    use \Shrikeh\Collection\ClosedOuterIteratorTrait; # Close off access to the inner iterator
    use \Shrikeh\Collection\OuterIteratorTrait;       # Give it all the standard read access methods
    use \Shrikeh\Collection\ObjectStorageTrait;       # Set inner storage to SplObjectStorage

    # Append method is called by ObjectStorageTrait during construction, so we
    # type hint the relevant class/interface we need...
    protected function append(SomeObject $object, $key)
    {
        $this->getStorage()->attach($object);
    }
}

请查看示例规范以获取更多使用方法。

特性

ArrayAccessTrait

用于轻松满足ArrayAccess接口的要求。代理到存储的底层offsetX方法。

ClosedOuterIteratorTrait

OuterIterator接口指定了一个类必须实现getInnerIterator方法,并且该方法的可视性不能从public更改。这违背了不可变集合的目的。因此,当应用此特性时,该类将为此方法抛出ClosedOuterIterator异常。

FixedArrayStorageTrait

这提供了一个与SPL类族中的IteratorIterator家族一致的公共__construct()方法,为该类提供了一种SplFixedArray存储(遗憾的是,SplFixedArray在实例化后可以改变大小)。

ImmutableArrayAccessTrait

这个特性“关闭”了由ArrayAccess接口要求的offsetSet()offsetUnset()方法。尝试使用任一方法将导致抛出ImmutableCollection异常。

ImmutableCollectionTrait

这个特性是包含ArrayAccessTrait并使用ImmutableArrayAccessTrait覆盖设置器的一个简写。

NamedConstructorsTrait

为集合提供命名构造函数fromTraversable()fromArray()

ObjectStorageTrait

这提供了一个与SPL类族中的IteratorIterator家族一致的公共__construct()方法,为该类提供了一个SplObjectStorage内部存储。

OuterIteratorTrait

如果您不想扩展任何IteratorIterator家族,但想实现OuterIterator,这个特性提供了代理到内部存储的必要方法。

RequiresOuterIteratorTrait

FixedArrayStorageTraitObjectStorageTrait使用的“安全捕获”特性,以确保使用该特性的类实现了OuterIterator。如果没有实现,将抛出IncorrectInterface异常。