linmad / ordinary-enum
此包已被废弃,不再维护。未建议替代包。
PHP的普通枚举类型实现
0.1
2018-01-01 23:02 UTC
Requires (Dev)
- phpunit/phpunit: ^6.5
This package is not auto-updated.
Last update: 2020-01-24 17:30:57 UTC
README
'Ordinary' enum it's another implementation for PHP, but with one difference - simple as it's possible.
在哪里以及为什么使用
我建议在需要以严格方式构建某些内容时使用,因此出现了枚举类型。您可以在某个类的构造函数或方法中定义一个枚举类,该类将等待枚举类子类的常量值。在这种情况下,您将控制代码并减少代码中的dummy switch\if,用于验证状态或字符串值等。
它是如何工作的以及如何使用
尽可能简单,您创建一些类并扩展Ordinary的枚举类,然后定义所需的常量值。如下所示
class StoreEnum extends Enum { public const __default = self::GROCERY; public const GROCERY = Grocery::class; public const COSMETIC = Cosmetic::class; }
正如您所看到的,创建受控值列表非常简单,这有助于您保持代码的整洁,并减少依赖项。
示例
... // Let's imagine you have fabric with stores $fruitStore = $this->storeFabric()->create(StoreEnum::GROCERY); ... // Now let's see how can be used Enum in create method ... public function create(Enum $storeType): StoreInterface { try { $storeType = new StoreEnum($type); } catch(InvalidEnumTypeException $e) { throw new \RuntimeException('Unable to create store from factory'); } return new $storeType->getValue(); } ...
就是这样,您定义对象并提供它们或处理错误,简单而轻便。
备注。对我来说,我在不同的Web服务和客户端库中使用这种实现来保持代码的可控性并减少错误,这些错误是由于预期中的未知值而产生的。