PHPackages                             mimosafa/php-enumeration - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. [Utility &amp; Helpers](/categories/utility)
4. /
5. mimosafa/php-enumeration

ActiveLibrary[Utility &amp; Helpers](/categories/utility)

mimosafa/php-enumeration
========================

A powerful PHP 8.1+ library to create inheritable, feature-rich enumerations that extend beyond native enum capabilities.

v1.1.0(2mo ago)09MITPHPPHP ^8.1CI failing

Since Oct 16Pushed 2mo agoCompare

[ Source](https://github.com/mimosafa/php-enumeration)[ Packagist](https://packagist.org/packages/mimosafa/php-enumeration)[ RSS](/packages/mimosafa-php-enumeration/feed)WikiDiscussions main Synced 1mo ago

READMEChangelog (1)Dependencies (4)Versions (3)Used By (0)

PHP Enumeration
===============

[](#php-enumeration)

[日本語のREADMEはこちら](README.ja.md)

[![Latest Stable Version](https://camo.githubusercontent.com/4d49695921e76a343701fcd4a7045700fc842d53bb878b9a5a779b00b8b60e2b/68747470733a2f2f706f7365722e707567782e6f72672f6d696d6f736166612f7068702d656e756d65726174696f6e2f762f737461626c65)](https://packagist.org/packages/mimosafa/php-enumeration)[![License](https://camo.githubusercontent.com/a74b8850474321773e2cc32092b3c91ccd49b81d7a344a0f1fdf402dac39656c/68747470733a2f2f706f7365722e707567782e6f72672f6d696d6f736166612f7068702d656e756d65726174696f6e2f6c6963656e7365)](https://packagist.org/packages/mimosafa/php-enumeration)

A powerful PHP 8.1+ library to create inheritable, feature-rich enumerations that extend beyond native enum capabilities.

---

Why PHP Enumeration?
--------------------

[](#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 `string` or `int` for 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 `string` or `int`.
- **Dynamic Case Control**: Subclasses can precisely control which cases to inherit from a parent class.

Comparison with Native PHP Enums
--------------------------------

[](#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 / AspectNative 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` keywordClass 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
------------

[](#installation)

You can install the package via composer:

```
composer require mimosafa/php-enumeration
```

Usage
-----

[](#usage)

### Pure Enums

[](#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

[](#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`

[](#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]` (for `PureEnum` subclasses)

**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
-------

[](#license)

The MIT License (MIT). Please see [License File](LICENSE) for more information.

###  Health Score

38

—

LowBetter than 85% of packages

Maintenance87

Actively maintained with recent releases

Popularity6

Limited adoption so far

Community6

Small or concentrated contributor base

Maturity45

Maturing project, gaining track record

 Bus Factor1

Top contributor holds 100% of commits — single point of failure

How is this calculated?**Maintenance (25%)** — Last commit recency, latest release date, and issue-to-star ratio. Uses a 2-year decay window.

**Popularity (30%)** — Total and monthly downloads, GitHub stars, and forks. Logarithmic scaling prevents top-heavy scores.

**Community (15%)** — Contributors, dependents, forks, watchers, and maintainers. Measures real ecosystem engagement.

**Maturity (30%)** — Project age, version count, PHP version support, and release stability.

###  Release Activity

Cadence

Every ~149 days

Total

2

Last Release

66d ago

### Community

Maintainers

![](https://www.gravatar.com/avatar/05236b7ac278d43c29071b254598c325a110d855f3a57f869dc80201437a1270?d=identicon)[mimosafa](/maintainers/mimosafa)

---

Top Contributors

[![mimosafa](https://avatars.githubusercontent.com/u/1770470?v=4)](https://github.com/mimosafa "mimosafa (5 commits)")

---

Tags

enumenumerationinheritable-enumadvanced-enum

###  Code Quality

TestsPest

Static AnalysisPHPStan

Code StylePHP CS Fixer

Type Coverage Yes

### Embed Badge

![Health badge](/badges/mimosafa-php-enumeration/health.svg)

```
[![Health](https://phpackages.com/badges/mimosafa-php-enumeration/health.svg)](https://phpackages.com/packages/mimosafa-php-enumeration)
```

###  Alternatives

[marc-mabe/php-enum

Simple and fast implementation of enumerations with native PHP

49644.8M97](/packages/marc-mabe-php-enum)[cerbero/enum

Zero-dependencies package to supercharge enum functionalities.

359207.5k2](/packages/cerbero-enum)[cerbero/laravel-enum

Laravel package to supercharge enum functionalities.

18989.6k](/packages/cerbero-laravel-enum)[emreyarligan/enum-concern

A PHP package for effortless Enumeration handling with Laravel Collections 📦 ✨

21156.3k1](/packages/emreyarligan-enum-concern)[rexlabs/enum

Enumeration (enum) implementation for PHP

48482.2k2](/packages/rexlabs-enum)[thunderer/platenum

PHP enum library

36145.7k](/packages/thunderer-platenum)

PHPackages © 2026

[Directory](/)[Categories](/categories)[Trending](/trending)[Changelog](/changelog)[Analyze](/analyze)
