Home >Backend Development >PHP Problem >How to uniformly manage PHP Enum?
composer require fangx/php-enum
Use the ./vendor/bin/enum
command to create an enumeration class.
./vendor/bin/enum FooEnum --enum="1=foo" --enum="b=bar" --path=Enums
This command creates a FooEnum.php in the Enums directory of the current directory by default. File. The file content is as follows:
<?phpnamespace Enums;use Fangx\Enum\AbstractEnum;class FooEnum extends AbstractEnum{ const FOO = "f", __FOO = "foo"; const BAR = "b", __BAR = "bar";}
enumeration class to inherit by default \Fangx\Enum\AbstractEnum
. The following methods can be called statically:
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 = 'f', __FOO = 'foo'; const BAR = 'b', __BAR = 'bar';}/** * ['f' => 'foo', 'b' => 'bar'] */FooEnum::toArray();
<?phpclass FooEnum extends \Fangx\Enum\AbstractEnum{ const FOO = 'f', __FOO = 'foo'; const BAR = 'b', __BAR = 'bar';}/** * "foo" */FooEnum::desc('f');/** * "bar" */FooEnum::desc(FooEnum::BAR);
<?phpclass 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
.<?phpclass BarEnum extends \Fangx\Enum\AbstractEnum{ public function all() { return [ new \Fangx\Enum\Definition('f', 'foo'), new \Fangx\Enum\Definition('b', 'bar'), ]; }}
The above is the detailed content of How to uniformly manage PHP Enum?. For more information, please follow other related articles on the PHP Chinese website!