daggerhartlab/collections

各种集合类。

v2.0.0 2022-07-11 22:02 UTC

This package is auto-updated.

Last update: 2024-09-12 19:06:01 UTC


README

一组简单的集合类。

集合示例

所有集合共享相同的方法。

基本 Collection

集合是无关单个项目名称的一维项目列表。

<?php

$collection = new \DaggerhartLab\Collections\Collection(['one', 'two', 'three']);
$collection->add('four');

foreach ($collection as $item) {
  echo $item;
}

TypedCollection

只允许列表中包含一种数据类型的集合。

<?php

$type = '\\Big\\Long\\Fqn\\ExampleInterface';
$items = [
  new \Big\Long\Fqn\ExampleModel(),
  new \Big\Long\Fqn\ExampleAdvancedModel(),
  new DateTime(),
];
$collection = new \DaggerhartLab\Collections\TypedCollection($type, $items);

// We don't expect the DateTime() to get registered.
assertEquals(2, $collection->count());
foreach ($collection as $item) {
  assertInstanceOf($type, $item);
}

注册表示例

所有注册表都包含与集合相同的功能,并提供了处理项目键的额外方法。

基本 Registry

注册表是包含项目的一个集合,其中注册表中的每个项目都有一个独特的名称。

<?php

$registry = new \DaggerhartLab\Collections\Map\Map([
  'one' => 1,
  'two' => 'buckle my shoe',
  'three' => 3,
]);
$registry->set('four', 'close the door');

echo $registry->get('two');
echo $registry['four'];

TypedRegistry

只允许集合中包含一种数据类型的注册表。

<?php

$type = '\\Big\\Long\\Fqn\\ExampleInterface';
$items = [
  'example' => new \Big\Long\Fqn\ExampleModel(),
  'advanced' => new \Big\Long\Fqn\ExampleAdvancedModel(),
  'another' => new DateTime(),
];
$registry = new \DaggerhartLab\Collections\Map\TypedMap($type, $items);

$example = $registry->get('example');
echo $example->getTitle();

ClassRegistry

期望项目值为完全命名空间类名的注册表。它可以反射和实例化注册的类。

<?php

$registry = new \DaggerhartLab\Collections\Map\ClassMap([
  'example' => \Big\Long\Fqn\ExampleModel::class,
  'advanced' => '\\Big\\Long\\Fqn\\ExampleAdvancedModel',
]);

/**
 * @var \Big\Long\Fqn\ExampleModel $example
 * @var \Big\Long\Fqn\ExampleAdvancedModel $advanced
 */
$example = $registry->createInstance('example');
assertInstanceOf('\\Big\\Long\\Fqn\\ExampleModel', $example);

$advanced = $registry->createInstance('advanced', ['param1', 'param2', null, 'param3' => ['is_an_array' => true]]);
assertInstanceOf('\\Big\\Long\\Fqn\\ExampleAdvancedModel', $advanced);

TraversableRegistry

一个多维注册表,可以通过点表示法访问深层嵌套的值。

使用点表示法在多维注册表中获取和设置值。

<?php

// Get values deeply nested.
$registry = new \DaggerhartLab\Collections\Map\TraversableMap([
  'one' => [
    'two' => [
      'three' => 'four',
    ],
  ],
]);
echo $registry->get('one.two.three');

// Set values deeply nested.
$registry = new \DaggerhartLab\Collections\Map\TraversableMap();
$registry->set('one.two.three', 'four');
var_export($registry->all());