abhi1693/yii2-enum

可枚举助手

安装次数: 11,161

依赖项: 0

建议者: 0

安全: 0

星级: 3

关注者: 4

分支: 2

开放性问题: 0

类型:yii2-extension

v1.0.0 2015-01-29 07:28 UTC

This package is not auto-updated.

Last update: 2024-09-14 16:51:08 UTC


README

Dependency Status Code Climate Latest Stable Version Total Downloads Latest Unstable Version License

文档

安装

安装此扩展的首选方式是通过 composer

运行以下命令之一:

php composer.phar require --prefer-dist abhi1693/yii2-enum "1.0.0"

或者将以下内容添加到您的 composer.json 文件中的 require 部分:

"abhi1693/yii2-enum": "1.0.0"

to require section of your composer.json file.

使用方法

BaseEnum 类为枚举类型提供支持。该类还提供了在创建和验证枚举过程中可能有用的功能。要使用它,您只需创建一个继承自 BaseEnum 的自己的类

use abhimanyu\enum\helpers;

class Month extends BaseEnum
{
    const January = 1;
    const February = 2;
    const March = 3;
    const April = 4;
    const May = 5;
    const June = 6;
    const July = 7;
    const August = 8;
    const September = 9;
    const October = 10;
    const November = 11;
    const December = 12;
}

创建枚举类型的新值有多种方式

// static call
$month = Month::May();

// direct instantiation
$month = new Month(Month::May);

// by value
$month = Month::createByValue(5);

// by name
$month = Month::createByName('May');

可以检索枚举类型的实例的名称和值

$name = $month->getName();
$value = $month->getValue();

注意:如果您定义了多个具有相同值的类常量,则将返回一个名称数组而不是一个字符串。您将需要自己决定使用哪个。

该类还提供了验证名称和值的方法

if (Month::isValidName('May')) {
    // it is valid
}

if (Month::isValidValue($value)) {
    // it is valid
}

如果您需要检索可能的枚举值的完整列表,您可以通过名称或值获取它们

$constantsByName = Month::getConstantsByName();

echo $constantsByName['May']; // 5

$constantsByValue = Month::getConstantsByValue();

echo $constantsByValue[5]; // "May"

如何贡献?

贡献说明位于 CONTRIBUTING.md 文件中。

许可证

Yii2-Enum 在 MIT 许可证下发布。有关详细信息,请参阅附带 LICENSE 文件。