後續將推出專門適配 laravel 的 enum 擴充套件.
歡迎 star / issue / pr. 3Q~~
安裝
composer require fangx/php-enum
建立
使用 ./vendor/bin/enum
命令建立一個列舉類.
./vendor/bin/enum FooEnum --enum="1=foo" --enum="b=bar" --path=Enums
該命令預設在 當前目錄的 Enums 目錄下建立一個 FooEnum.php 檔案. 檔案內容如下:
<?php
namespace 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')
獲取所有的列舉值
<?php
class FooEnum extends \Fangx\Enum\AbstractEnum
{
const FOO = 'f', __FOO = 'foo';
const BAR = 'b', __BAR = 'bar';
}
/**
* ['f' => 'foo', 'b' => 'bar']
*/
FooEnum::toArray();
獲取列舉值的描述資訊
<?php
class FooEnum extends \Fangx\Enum\AbstractEnum
{
const FOO = 'f', __FOO = 'foo';
const BAR = 'b', __BAR = 'bar';
}
/**
* "foo"
*/
FooEnum::desc('f');
/**
* "bar"
*/
FooEnum::desc(FooEnum::BAR);
使用格式來約束返回值
<?php
class FooFormat implements \Fangx\Enum\Contracts\Format
{
public function parse(\Fangx\Enum\Contracts\Definition $definition): array
{
return [['key' => $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
一致.
<?php
class BarEnum extends \Fangx\Enum\AbstractEnum
{
public function all()
{
return [
new \Fangx\Enum\Definition('f', 'foo'),
new \Fangx\Enum\Definition('b', 'bar'),
];
}
}
本作品採用《CC 協議》,轉載必須註明作者和本文連結