soluciones-ypunto / cake-enum

实现 CakePHP 中枚举的库

安装: 137

依赖者: 0

建议者: 0

安全: 0

星标: 0

关注者: 3

分支: 0

公开问题: 0

类型:cakephp-plugin

1.0.0 2019-01-22 20:22 UTC

This package is auto-updated.

Last update: 2024-09-23 08:46:57 UTC


README

安装

您可以使用 composer 将此插件安装到您的 CakePHP 应用程序中。

安装 composer 包的推荐方式是

composer require soluciones-ypunto/cake-enum

使用方法

按照以下方式定义您的枚举列表

// file Model/Enum/SomeList.php

namespace App\Model\Enum;

use Ypunto\EnumType\Enum\Enum;

class SomeList extends Enum
{
    const VALUE_1 = 1;
    const VALUE_2 = 2;
    const SOME_VALUE = 'any-val';

    /**
     * @return string[]
     */
    public static function getOptions()
    {
        return [
            self::VALUE_1 => __('First'),
            self::VALUE_2 => __('Second'),
            self::SOME_VALUE => __('Some Value'),
        ];
    }
}

然后在表单中使用它们,以显示值或进行比较,而无需使用纯字符串。

// in templates
// to create select controls
echo $this->Form->control('value', ['options' => \App\Model\Enum\SomeList::getOptions()]);

// to display
echo \App\Model\Enum\SomeList::getOption($entity->value);

// to compare
if ($entity->value === \App\Model\Enum\SomeList::VALUE_1) {
    // do something
}