tailflow/enum

1.1 2020-11-05 13:45 UTC

This package is auto-updated.

Last update: 2024-09-24 21:52:45 UTC


README

Latest Version on Packagist Build Status

介绍

该包为PHP提供强类型枚举。在此包中,枚举始终是对象,而不是单独的常量值。这允许在IDE中进行适当的静态分析和重构。

安装

您可以通过composer安装此包

composer require tailflow/enum

用法

以下是如何定义枚举

use Tailflow\Enum\Enum;

class Status extends Enum
{
    public const Inactive = 0;
    public const Active = 1;
    public const OnHold = 3;
}

以下是它们的用法

$class->setStatus(Status::Inactive);

自定义枚举标签

默认情况下,枚举标签是从常量名称派生的。要获取枚举标签,您可以使用枚举类上的 ::getLabel 方法

// $label will be equal to "OnHold" - the name of the constant
$label = Status::getLabel(Status::OnHold); 

可选地,您可以为任何给定的枚举值提供不同的标签

use Tailflow\Enum\Enum;

class Status extends Enum
{
    public const Inactive = 0;
    public const Active = 1;
    public const OnHold = 3;

    public static function labels(): array
    {
        return [
            self::OnHold => 'waiting'
        ];
    }
}

// $label will be equal to "waiting" - the custom label defined in "labels" method
$label = Status::getLabel(Status::OnHold); 

列出所有枚举标签

要获取枚举的所有标签列表,您可以使用 ::getLabels 方法

// $labels will contain the array - ['Inactive', 'Active', 'waiting']
$labels = Status::getLabels(); 

列出所有枚举值

要获取枚举的所有值列表,您可以使用 ::getValues 方法

// $labels will contain the array - [0, 1, 3]
$labels = Status::getValues(); 

许可证

Laravel Orion 是开源软件,受 MIT 许可证 许可。