laudis/typed-enum
Composer 安装命令:
composer require laudis/typed-enum
包简介
A small class allowing for typed enumerations.
README 文档
README
Typed-enum is A simple, lightweight and efficient enumeration library. Type hint your enumerated options efficiently and strictly to eliminate unintended side effects and bugs introduced by typos.
How to use:
Download
Download with composer:
Extending from TypedEnum
Extend from TypedEnum and use any scalar constants to define the enumeration:
final class Foo extends TypedEnum { private const BAR = 'bar'; private const BAZ = 2; private const FOO = 2.1; }
You can now create instances of Foo by using the __callstatic method based on the name of the constant:
Foo::BAR(); // Returns an instance of Foo with value 'bar'
Testing for equality
As a bonus, you can now use strict comparisons. TypedEnum guarantees there to be only one instance of the same enumerated value at runtime.
function isBar(Foo $enum): bool { return Foo::BAR() === $enum; }
Return the actual value:
If your application depends on the value assigned to the enumeration, you can easily fetch it with the getValue() getter.
echo Foo::BAR()->getValue(); //'bar'
Resolve the enumeration
Resolve an enumeration based on its value. The resolve method will return all enumerations with the same value in the array.
echo Foo::resolve('bar')[0] === Foo::BAR() // true
Tips
IDE integration
You can easily use the power of you ide by simply adding @method tags in the docblock of your class like this:
/** * @method static TypedEnum TEST() */ final class Foo extends TypedEnum { private const TEST = 'test'; }
Psalm
We built TypedEnum with psalm! With these powerful annotations, you can now hint the scalar value of the enumeration:
/** * @extends TypedEnum<string> */ final class Foo extends TypedEnum { private const TEST = 'test'; }
Easy Bug protection
Php 7.2 allows for protected constants, and 7.4 uses private ones. Use these features to protect against unintended side effects!
echo Foo::BAR === Foo::BAR() // echo's false but is impossible if it is a protected constant
Developed by laudis
laudis/typed-enum 适用场景与选型建议
laudis/typed-enum 是一款 基于 PHP 开发的 Composer 扩展包,目前已累计 695.75k 次下载、GitHub Stars 达 4, 最近一次更新时间为 2020 年 09 月 24 日, 在 PHP 生态内属于活跃度较高的组件。
我们在过去多个企业项目中使用过 laudis/typed-enum 或与其功能相近的方案,如果你在选型或落地过程中遇到问题,例如 版本兼容、二次改造、私有化封装、与内部系统对接、生产 BUG 排查,欢迎联系我们协助评估。
基于 laudis/typed-enum 在你已有业务上做功能扩展、字段裁剪、UI 适配、与内部账号 / 权限 / 日志系统的深度对接。
线上偶发问题、内存泄漏、慢查询、并发异常等排查修复;针对高流量场景做缓存、队列、索引层面的调优。
承接完整的项目从需求 → 设计 → 开发 → 上线 → 长期运维;也可按月提供技术保姆服务。
统计信息
- 总下载量: 695.75k
- 月度下载量: 0
- 日度下载量: 0
- 收藏数: 4
- 点击次数: 13
- 依赖项目数: 5
- 推荐数: 0
其他信息
- 授权协议: MIT
- 更新时间: 2020-09-24