lukaszmakuch/class-based-registry

允许将值与一个或多个类关联,然后通过传递实现了这些类的对象来获取这个值

v0.0.2 2016-01-16 17:52 UTC

This package is not auto-updated.

Last update: 2024-09-18 09:53:21 UTC


README

允许将值与一个或多个类关联,然后通过传递实现了这些类的对象来获取这个值。

用法

环境

假设我们有一些这样的类

class Animal {}
class Elephant extends Animal {}
class Plant {}

要获取注册表的实例,请创建它

$r = new \lukaszmakuch\ClassBasedRegistry\ClassBasedRegistry();

简单示例

将42与Animal类关联

$r->associateValueWithClasses(
    42,
    [Animal::class]
);

通过提供任何动物来获取它...

$r->fetchValueByObjects([new Animal()]); //42

...可能是一只大象!

$r->fetchValueByObjects([new Elephant()]); //42

多个类

可以将值与多个类关联

$r->associateValueWithClasses(
    1970,
    [Animal::class, Plant::class]
);

在获取对象时可以以任何顺序传递

$r->fetchValueByObjects([new Plant(), new Elephant()]); //1970

抛出异常

当无法获取任何值时,则抛出 \lukaszmakuch\ClassBasedRegistry\Exception\ValueNotFound 异常

try {
    $r->fetchValueByObjects([new Plant()]);
} catch (\lukaszmakuch\ClassBasedRegistry\Exception\ValueNotFound $e) {
  //it was not possible to fetch any value by a plant
}

安装

使用 composer 获取最新版本

$ composer require lukaszmakuch/class-based-registry