morebec/orkestra-enum

提供枚举的 Orkestra 组件

v2.5.6 2021-07-05 16:42 UTC

This package is auto-updated.

Last update: 2024-09-30 01:16:32 UTC


README

此 Orkestra 组件为 PHP 提供了类型化的枚举。

安装

composer require morebec/orkestra-orkestra-enum

使用

创建枚举

要创建一个新的枚举,需要扩展 Enum 类。例如,假设我们想要创建一个 CardinalPoint 类。由于有严格的四个方向,这是一个很好的枚举候选

class CardinalPoint extends Enum
{
    const NORTH = 'NORTH';    
    const EAST = 'EAST';    
    const WEST = 'WEST';  
    const SOUTH = 'SOUTH';
}

简单地这样做,将允许我们以以下方式使用我们的类

// Instantiate a new CardinalPoint instance
$direction = new CardinalPoint(CardinalPoint::NORTH);

// Since Enums have builtin validation,
// the following line would throw an InvalidArgumentException:
$direction = new CardinalPoint('North');

// However the following would work:
$direction = new CardinalPoint('NORTH');

// Using in functions or class methods 
public function changeDirection(CardinalPoint $direction)
{
    // Testing equlity with string
    if(!$direction->isEqualTo(new CardinalPoint(CardinalPoint::EAST))) {
        echo 'Not going East!';
    }

    // Since the constants are strings, it is also possible to compare
    // using loose comparison
    if($direction == CardinalPoint::NORTH) {
        echo 'Definitely going North!';
    }    
}

为了更容易地进行 IDE 集成,我们甚至可以进一步添加 @method 注解到枚举类中

/**
* @method static self NORTH() 
* @method static self EAST() 
* @method static self WEST() 
* @method static self SOUTH() 
*/
class CardinalPoint extends Enum
{
   const NORTH = 'NORTH';    
   const EAST = 'EAST';    
   const WEST = 'WEST';  
   const SOUTH = 'SOUTH';
}

这将允许我们在代码中这样做

$direction = CardinalPoint::NORTH();

获取所有可能的值

为了以数组形式获取所有可能的值,您可以使用静态方法 getValues

CardinalPoint::getValues(); 
// Returns an array as: 
// [ 'NORTH', 'EAST', 'WEST', 'SOUTH' ]