mimosafa/php-enumeration
Composer 安装命令:
composer require mimosafa/php-enumeration
包简介
A powerful PHP 8.1+ library to create inheritable, feature-rich enumerations that extend beyond native enum capabilities.
README 文档
README
A powerful PHP 8.1+ library to create inheritable, feature-rich enumerations that extend beyond native enum capabilities.
Why PHP Enumeration?
PHP 8.1 introduced native enumerations, which are a great addition to the language. However, they come with a few limitations:
- They cannot be extended (no
extends). - They are strictly typed as
stringorintfor backed enums.
This package provides a set of base classes and traits to create enumerations that overcome these limitations, offering a more flexible and powerful way to work with enums in your PHP 8.1+ projects.
Key features include:
- Inheritance: Extend your enums to create more complex and reusable structures.
- Convenient Factory Methods: Get enum instances by case name using
::of()and::tryOf(). - Flexible Backed Values: Use any scalar value for your backed enums, not just
stringorint. - Dynamic Case Control: Subclasses can precisely control which cases to inherit from a parent class.
Comparison with Native PHP Enums
While this library offers powerful features, it's important to understand the differences and choose the right tool for your needs.
| Feature / Aspect | Native PHP Enums (PHP 8.1+) | This Library (mimosafa/php-enumeration) |
|---|---|---|
| Inheritance | ❌ Not supported | ✅ Supported |
| Flexible Backed Values | ❌ string or int only |
✅ Any scalar (string, int, float, bool) |
| Instance lookup by name | ✅ (Direct static access) | ✅ Supported (via ::of() / ::tryOf()) |
| Dynamic Case Definition | ❌ Not supported | ✅ Supported (via toArray() or EnumerateConstantsTrait) |
match Expression |
✅ Supported | ❌ Not directly supported |
| Type Hinting | enum keyword |
Class name (e.g., PureEnum, BackedEnum) |
Built-in cases() |
✅ Supported | ✅ Supported (via custom implementation) |
Choose this library if you need advanced features like inheritance or flexible backed values. For simpler use cases where match expression support and strict string/int backed values are preferred, native PHP Enums might be sufficient.
Installation
You can install the package via composer:
composer require mimosafa/php-enumeration
Usage
Pure Enums
Create a simple enum without backed values. The toArray() method allows for dynamic definition of cases.
If you want IDE autocompletion for magic static calls like Status::PUBLISHED(), add @method annotations to the child class PHPDoc as shown below.
use Enumeration\PureEnum; /** * @method static self PENDING() * @method static self PUBLISHED() * @method static self ARCHIVED() */ class Status extends PureEnum { public static function toArray(): array { return ['PENDING', 'PUBLISHED', 'ARCHIVED']; } } $status = Status::PUBLISHED(); assert($status->name === 'PUBLISHED'); assert(Status::of('PENDING') === Status::PENDING());
Dynamic Case Definition Example:
You can define enum cases dynamically, for instance, by reading file names from a directory:
use Enumeration\PureEnum; use function Safe\glob; // Assuming Safe\glob for robustness /** * @method static self BACKED_ENUM_PHP() * @method static self ENUMERATE_CONSTANTS_TRAIT_PHP() * @method static self PURE_ENUM_PHP() */ class SourceFiles extends PureEnum { public static function toArray(): array { $files = glob(__DIR__ . '/src/*.php'); // Adjust path as needed return array_map(fn($file) => strtoupper(str_replace('.', '_', basename($file))), $files); } } // Example usage: // assert(SourceFiles::PURE_ENUM_PHP() instanceof SourceFiles);
Backed Enums
Create enums with scalar values.
If you want IDE autocompletion for magic static calls like Suit::Diamonds(), add @method annotations to the child class PHPDoc as shown below.
use Enumeration\BackedEnum; /** * @method static self Hearts() * @method static self Diamonds() * @method static self Clubs() * @method static self Spades() */ class Suit extends BackedEnum { public static function toArray(): array { return [ 'Hearts' => 'H', 'Diamonds' => 'D', 'Clubs' => 'C', 'Spades' => 'S', ]; } } $suit = Suit::Diamonds(); assert($suit->name === 'Diamonds'); assert($suit->value === 'D'); assert(Suit::from('S') === Suit::Spades());
Inheritance with EnumerateConstantsTrait
This is where the magic happens. Define your cases as class constants and use inheritance to build powerful, domain-specific enums.
The EnumerateConstantsTrait automatically turns your class constants into enum cases.
1. Define a base enum:
use Enumeration\BackedEnum; use Enumeration\EnumerateConstantsTrait; abstract class UserRole extends BackedEnum { use EnumerateConstantsTrait; const Reader = 1; const Editor = 2; const Admin = 3; const SuperAdmin = 4; }
2. Extend and control the cases:
Now, you can create specialized enums that inherit from UserRole but only expose a subset of the cases.
// An enum for regular site roles, excluding SuperAdmin. class SiteUserRole extends UserRole { protected static function excludedConstantsFromEnumeration(): array { return ['SuperAdmin']; } } // An enum for administrative roles. class AdminRole extends UserRole { protected static function includedConstantsFromEnumeration(): array { return ['Admin', 'SuperAdmin']; } }
You can also configure this declaratively with PHP attributes (useful for IDE discoverability):
use Enumeration\Attributes\ExcludeConstants; use Enumeration\Attributes\IncludeConstants; #[ExcludeConstants('SuperAdmin')] class SiteUserRole extends UserRole { } #[IncludeConstants('Admin', 'SuperAdmin')] class AdminRole extends UserRole { }
Available attributes:
#[IncludeConstants('A', 'B')]#[ExcludeConstants('A', 'B')]#[AllowDuplicateValues(false)]#[DisableCaseNameStaticCall](forPureEnumsubclasses)
3. Use them in your application:
// Returns [1, 2, 3] SiteUserRole::values(); // Returns ['Admin', 'SuperAdmin'] AdminRole::names(); // Throws a ValueError because 'Reader' is not in AdminRole AdminRole::of('Reader'); // You can still use the parent class for type hinting function grantPermission(UserRole $role) { // ... } // Both are valid grantPermission(SiteUserRole::Admin()); grantPermission(AdminRole::SuperAdmin());
License
The MIT License (MIT). Please see License File for more information.
mimosafa/php-enumeration 适用场景与选型建议
mimosafa/php-enumeration 是一款 基于 PHP 开发的 Composer 扩展包,目前已累计 9 次下载、GitHub Stars 达 0, 最近一次更新时间为 2025 年 10 月 16 日, 在 PHP 生态内属于活跃度较高的组件。
它主要适用于以下技术方向: 「enum」 「enumeration」 「inheritable-enum」 「advanced-enum」 等业务场景。在实际项目中,围绕这些方向常见需要落地的问题包括:接口对接、性能调优、并发安全、与既有框架(Laravel / ThinkPHP / Yii / Webman 等)的兼容适配,以及生产环境的日志埋点与稳定性保障。
我们在过去多个企业项目中使用过 mimosafa/php-enumeration 或与其功能相近的方案,如果你在选型或落地过程中遇到问题,例如 版本兼容、二次改造、私有化封装、与内部系统对接、生产 BUG 排查,欢迎联系我们协助评估。
基于 mimosafa/php-enumeration 在你已有业务上做功能扩展、字段裁剪、UI 适配、与内部账号 / 权限 / 日志系统的深度对接。
线上偶发问题、内存泄漏、慢查询、并发异常等排查修复;针对高流量场景做缓存、队列、索引层面的调优。
承接完整的项目从需求 → 设计 → 开发 → 上线 → 长期运维;也可按月提供技术保姆服务。
与 mimosafa/php-enumeration 相关的其它包
同方向 / 同关键字的高下载量 PHP Composer 包推荐,方便对比选型:
Enum type behavior for Yii2 based on class constants
A PHP Abstract Enum Class
Compatibility layer for emulating enumerations in PHP < 8.1 and native enumerations in PHP >= 8.1
Enum type behavior and helper for Yii2, for PostgreSQL only
Enum libraries used by Zimbra Api
Bundle for Doctrine enumerations extension for Postgres
统计信息
- 总下载量: 9
- 月度下载量: 0
- 日度下载量: 0
- 收藏数: 0
- 点击次数: 13
- 依赖项目数: 0
- 推荐数: 0
其他信息
- 授权协议: MIT
- 更新时间: 2025-10-16