webdevcave/enum-index-accessor

动态索引访问变得简单

v1.0 2024-04-24 04:02 UTC

This package is auto-updated.

Last update: 2024-08-24 04:47:52 UTC


README

使用composer安装

composer install webdevcave/enum-index-accessor

为什么?

从php 8.1或更高版本开始,枚举器组织的可能性变得真实。它工作得很好,直到我们需要动态读取这些值。以下是一个示例

enum HexColors: string {
    case RED = '#FF0000';
    case GREEN = '#00FF00';
    case BLUE = '#0000FF';
    case WHITE = '#FFFFFF';
    case BLACK = '#000000';
    // and so on...
}

$index = 'BLUE'; // Imagine this is a dynamic value
$constant = HexColors::class."::$index"; // In a real-world application HexColors
                                         // will most probably be declared under a namespace
$color = null;

// Before we proceed, we have to ensure the specified index exists or our code will break
if (defined($constant)) {
    $color = constant($constant)->value; // Now we read its value
}

// You will probably want to assign a default value in case something went wrong
if (is_null($color)) {
    $color = HexColors::RED->value;
}

// Now we can finally proceed with our task...

这看起来太冗长和/或杂乱吗?现在想象一下,如果您的应用程序需要读取多个值,就像这样。

这就是我们创建这个包的原因!现在您可以用这种方式完成同样的任务

$color = HexColors::tryValue($index) ?? HexColors::value('RED');

如何?

use \WebdevCave\EnumIndexAccessor\BackedEnumIndexAccessor; // step 1: Import the trait

enum HexColors: string {
    case RED = '#FF0000';
    case GREEN = '#00FF00';
    case BLUE = '#0000FF';
    case WHITE = '#FFFFFF';
    case BLACK = '#000000';
    // and so on...
    
    use BackedEnumIndexAccessor; // step 2: use it
}

~ 哇!魔法 🪄!

其他用例...

我们遵循php团队的标准命名方法,以便于使用。以下是所有方法的列表

HexColors::hasIndex($index); // Checks if a case statement was set in the enumerator (boolean)
HexColors::index($index); // Read the object from given index (skips index check)
HexColors::tryIndex($index); // Read the object from given index (null on non-existent)
HexColors::value($index); // Read the value from given index (skips index check)
HexColors::tryValue($index); // Read the value from given index (null on non-existent)

对于纯枚举器(没有后置值的枚举器),请按如下方式使用纯枚举器特质

use \WebdevCave\EnumIndexAccessor\PureEnumIndexAccessor; // step 1: Import the trait

enum Fruits {
    case ORANGE;
    case PEAR;
    case APPLE;
    // and so on...
    
    use PureEnumIndexAccessor; // step 2: use it
}

重要提示: 方法 valuetryValue 对于纯枚举器不可用,因为纯枚举器不携带任何值