پولیایفスキ / 枚举
PHP 枚举类型的简单实现
v1.2.7
2015-09-04 19:21 UTC
Requires
- php: >=5.4.0
Requires (Dev)
- phpunit/phpunit: 4.3.*
README
枚举组件允许开发者为基于标准PHP类的枚举类型定义严格的枚举。使用此组件稍微有些冗长,但它允许您摆脱对实体中每个枚举字段进行常量验证。这种实现与您可以在其他地方找到的所有实现(包括SplEnum)非常相似,但更精确。
这是一个从不再维护的 startuplabs/enum
分支出来的。
用法
1. 定义枚举类的祖先。例如
<?php namespace Acme\Example; use Pulyaevskiy\Enum; /** * @method static Shape triangle() * @method static Shape square() * @method static Shape pentagon() * @method static Shape hexagon() */ class Shape extends Enum { const TRIANGLE = 'triangle'; const SQUARE = 'square'; const PENTAGON = 'pentagon'; const HEXAGON = 'hexagon'; }
2. 在类中使用类型提示
<?php namespace Acme\Example; class Model { /** @var Shape */ private $shape; public function setShape(Shape $value) { // Here it is guaranteed that the $value has already been validated $this->shape = $value; } }
3. 使用静态方法创建新实例
<?php namespace Acme\Example; class Application { public function changeShapeToSquare(Model $model) { // Enum class has __callStatic method that checks if there is constant with name of called function // and then create instance of Shape class with this value $shape = Shape::square(); $model->setShape($shape); } }
贡献者
- Алексей Тихомиров
- Анатoly Pulyaevskiy
许可证
此库在MIT许可证下。请参阅与库源代码一起提供的完整许可证文件中的许可证。