首頁  >  文章  >  後端開發  >  如何統一管理的 PHP Enum?

如何統一管理的 PHP Enum?

Guanhui
Guanhui轉載
2020-06-19 18:04:342312瀏覽

如何統一管理的 PHP Enum?

安裝

#
composer require fangx/php-enum

建立

使用./vendor/bin/enum 指令建立一個列舉類別.

./vendor/bin/enum FooEnum --enum="1=foo" --enum="b=bar" --path=Enums

這個指令預設在目前目錄的Enums 目錄下建立一個FooEnum.php文件. 文件內容如下:

<?phpnamespace Enums;use Fangx\Enum\AbstractEnum;class FooEnum extends AbstractEnum{
    const FOO = "f", __FOO = "foo";
    const BAR = "b", __BAR = "bar";}

使用

#枚舉類別預設繼承\Fangx\Enum\AbstractEnum#.可以靜態呼叫以下方法:

  • toArray(Format $format = null, Filter $filter = null)
  • toJson(Format $format = null, Filter $filter = null)
  • desc($key, $default = 'Undefined')

取得所有的枚舉值

<?phpclass FooEnum extends \Fangx\Enum\AbstractEnum{
    const FOO = &#39;f&#39;, __FOO = &#39;foo&#39;;
    const BAR = &#39;b&#39;, __BAR = &#39;bar&#39;;}/**
 * [&#39;f&#39; => 'foo', 'b' => 'bar']
 */FooEnum::toArray();

取得枚舉值的描述資訊

<?phpclass FooEnum extends \Fangx\Enum\AbstractEnum{
    const FOO = &#39;f&#39;, __FOO = &#39;foo&#39;;
    const BAR = &#39;b&#39;, __BAR = &#39;bar&#39;;}/**
 * "foo"
 */FooEnum::desc(&#39;f&#39;);/**
 * "bar"
 */FooEnum::desc(FooEnum::BAR);

使用格式來約束傳回值

<?phpclass FooFormat implements \Fangx\Enum\Contracts\Format{
    public function parse(\Fangx\Enum\Contracts\Definition $definition): array
    {
        return [[&#39;key&#39; => $definition->getKey() , 'value' => $definition->getValue()]];
    }}class FooEnum extends \Fangx\Enum\AbstractEnum{
    const FOO = 'f', __FOO = 'foo';
    const BAR = 'b', __BAR = 'bar';}/**
 * [['key' => 'f', 'value' => 'foo'], ['key' => 'b', 'value' => 'bar'],]
 */$format = new FooFormat();FooEnum::toArray($format);

透過規則來過來過濾枚舉值.

class FooFilter implements \Fangx\Enum\Contracts\Filter{
    public function __invoke(\Fangx\Enum\Contracts\Definition $definition)
    {
        return $definition->getKey() === 'f';
    }}/**
 * ['f' => 'foo']
 */$filter = new FooFilter();FooEnum::toArray(null, $filter);

使用自訂的集合來作為所有的枚舉類型, 其他使用方法與FooEnum 一致.

<?phpclass BarEnum extends \Fangx\Enum\AbstractEnum{
    public function all()
    {
        return [
            new \Fangx\Enum\Definition('f', 'foo'),
            new \Fangx\Enum\Definition('b', 'bar'),
        ];
    }}

                       

推薦教程:《PHP

以上是如何統一管理的 PHP Enum?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文轉載於:learnku.com。如有侵權,請聯絡admin@php.cn刪除