PHPackages                             somnambulist/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. somnambulist/enumeration

ActiveLibrary

somnambulist/enumeration
========================

An enumeration implementation for PHP derived from eloquent/enumeration.

1.0.1(1y ago)01.1k↓100%1MITPHPPHP &gt;=8.1

Since Jan 3Pushed 1y ago1 watchersCompare

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

READMEChangelogDependencies (1)Versions (3)Used By (1)

Somnambulist Enumeration
========================

[](#somnambulist-enumeration)

[![GitHub Actions Build Status](https://camo.githubusercontent.com/4cb494892058662cd349bda957fe678c48a4dd34e2c9fae6d54535836826dbf7/68747470733a2f2f696d672e736869656c64732e696f2f6769746875622f616374696f6e732f776f726b666c6f772f7374617475732f736f6d6e616d62756c6973742d746563682f656e756d65726174696f6e2f74657374732e796d6c3f6c6f676f3d676974687562266272616e63683d6d61696e)](https://github.com/somnambulist-tech/enumeration/actions?query=workflow%3Atests)[![Issues](https://camo.githubusercontent.com/afef08d64eebc5ba5d575776eb865545b772380fe104b6ea7246783827251ae0/68747470733a2f2f696d672e736869656c64732e696f2f6769746875622f6973737565732f736f6d6e616d62756c6973742d746563682f656e756d65726174696f6e3f6c6f676f3d676974687562)](https://github.com/somnambulist-tech/enumeration/issues)[![License](https://camo.githubusercontent.com/39e46aa8af36fa5056feade60584d87fe69542313ba0ef67653857f18cb78477/68747470733a2f2f696d672e736869656c64732e696f2f6769746875622f6c6963656e73652f736f6d6e616d62756c6973742d746563682f656e756d65726174696f6e3f6c6f676f3d676974687562)](https://github.com/somnambulist-tech/enumeration/blob/master/LICENSE)[![PHP Version](https://camo.githubusercontent.com/4b5f04cbe41003c49d46ab09078634e51f31031ca95e3242068b84f32b1673fd/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f7068702d762f736f6d6e616d62756c6973742f656e756d65726174696f6e3f6c6f676f3d706870266c6f676f436f6c6f723d7768697465)](https://packagist.org/packages/somnambulist/enumeration)[![Current Version](https://camo.githubusercontent.com/a853a062e86e596f4407dd960522f5d6bc3aa27d27a64f7cbd81d3c362d3d8c6/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f762f736f6d6e616d62756c6973742f656e756d65726174696f6e3f6c6f676f3d7061636b6167697374266c6f676f436f6c6f723d7768697465)](https://packagist.org/packages/somnambulist/enumeration)

Provides extended enumeration support for PHP beyond what the PHP 8+ enum allows for. This project is a continuation of [eloquent/enumeration](https://github.com/eloquent/enumeration).

Installation
------------

[](#installation)

- Available as [Composer](http://getcomposer.org/) package [somnambulist/enumeration](https://packagist.org/packages/somnambulist/enumeration).

What is an Enumeration?
-----------------------

[](#what-is-an-enumeration)

In terms of software development, an enumeration (or "enumerated type") is essentially a fixed set of values. These values are called "members" or "elements".

An enumeration is used in circumstances where it is desirable to allow an argument to be only one of a particular set of values, and where anything else is considered invalid.

A basic example
---------------

[](#a-basic-example)

*Enumeration* can be used like [C++ enumerated types](https://en.wikipedia.org/wiki/Enumerated_type#C.2B.2B). Here is an example, representing a set of HTTP request methods:

```
use Somnambulist\Enumeration\AbstractEnumeration;

final class HttpRequestMethod extends AbstractEnumeration
{
    const OPTIONS = 'OPTIONS';
    const GET = 'GET';
    const HEAD = 'HEAD';
    const POST = 'POST';
    const PUT = 'PUT';
    const DELETE = 'DELETE';
    const TRACE = 'TRACE';
    const CONNECT = 'CONNECT';
}
```

This class can now be used in a type hint to easily accept any valid HTTP request method:

```
function handleHttpRequest(HttpRequestMethod $method, $url, $body = null)
{
    // handle request...
}
```

**Note:** for simple enumerations, it is recommended to use PHPs native backed enums.

Accessing enumeration members
-----------------------------

[](#accessing-enumeration-members)

Members are accessed by static method calls, like so:

```
handleHttpRequest(HttpRequestMethod::GET(), 'http://example.org/');
handleHttpRequest(HttpRequestMethod::POST(), 'http://example.org/', 'foo=bar&baz=qux');
```

For each member of the enumeration, a single instance of the enumeration class is instantiated (that is, an instance of `HttpRequestMethod` in the above example). This means that strict comparison (===) can be used to determine which member has been passed to a function:

```
function handleHttpRequest(HttpRequestMethod $method, $url, $body = null)
{
    if ($method === HttpRequestMethod::POST()) {
        // handle POST requests...
    } else {
        // handle other requests...
    }
}
```

Java-style enumerations
-----------------------

[](#java-style-enumerations)

[Java's enum types](https://en.wikipedia.org/wiki/Enumerated_type#Java) have slightly more functionality than C++ enumerated types. They can have additional properties and/or methods, and are really just a specialised kind of class where there are a fixed set of instances.

This is sometimes called the [Multiton](http://en.wikipedia.org/wiki/Multiton_pattern) pattern, and in fact, all enumerations in this implementation are Multitons. The `AbstractEnumeration` class simply defines its members based upon class constants.

Here is an example borrowed from the Java documentation for its enum types. The following multiton describes all the planets in our solar system, including their masses and radii:

```
use Somnambulist\Enumeration\AbstractMultiton;

final class Planet extends AbstractMultiton
{
    /**
     * Universal gravitational constant.
     *
     * @var float
     */
    const G = 6.67300E-11;

    /**
     * @return float
     */
    public function surfaceGravity()
    {
        return self::G * $this->mass / ($this->radius * $this->radius);
    }

    /**
     * @param float $otherMass
     *
     * @return float
     */
    public function surfaceWeight($otherMass)
    {
        return $otherMass * $this->surfaceGravity();
    }

    protected static function initializeMembers()
    {
        new static('MERCURY', 3.302e23,  2.4397e6);
        new static('VENUS',   4.869e24,  6.0518e6);
        new static('EARTH',   5.9742e24, 6.37814e6);
        new static('MARS',    6.4191e23, 3.3972e6);
        new static('JUPITER', 1.8987e27, 7.1492e7);
        new static('SATURN',  5.6851e26, 6.0268e7);
        new static('URANUS',  8.6849e25, 2.5559e7);
        new static('NEPTUNE', 1.0244e26, 2.4764e7);
        // Pluto will always be a planet to me!
        new static('PLUTO',   1.31e22,   1.180e6);
    }

    /**
     * @param string $key
     * @param float  $mass
     * @param float  $radius
     */
    protected function __construct($key, $mass, $radius)
    {
        parent::__construct($key);

        $this->mass = $mass;
        $this->radius = $radius;
    }

    private $mass;
    private $radius;
}
```

The above class can be used to take a known weight on earth (in any unit) and calculate the weight on all the planets (in the same unit):

```
$earthWeight = 175;
$mass = $earthWeight / Planet::EARTH()->surfaceGravity();

foreach (Planet::members() as $planet) {
    echo sprintf(
        'Your weight on %s is %f' . PHP_EOL,
        $planet,
        $planet->surfaceWeight($mass)
    );
}
```

If the above script is executed, it will produce something like the following output:

```
Your weight on MERCURY is 66.107480
Your weight on VENUS is 158.422560
Your weight on EARTH is 175.000000
Your weight on MARS is 66.279359
Your weight on JUPITER is 442.677903
Your weight on SATURN is 186.513785
Your weight on URANUS is 158.424919
Your weight on NEPTUNE is 199.055584

```

Enumerations and class inheritance
----------------------------------

[](#enumerations-and-class-inheritance)

When an enumeration is defined, the intent is usually to define a set of valid values that should not change, at least within the lifetime of a program's execution.

Since PHP has no in-built support for enumerations, this library implements them as regular PHP classes. Classes, however, allow for much more extensibility than is desirable in a true enumeration.

For example, a naive enumeration implementation might allow a developer to extend the `HttpRequestMethod` class from the examples above (assuming the `final` keyword is removed):

```
class CustomHttpMethod extends HttpRequestMethod
{
    const PATCH = 'PATCH';
}
```

The problem with this scenario is that all the code written to expect only the HTTP methods defined in `HttpRequestMethod` is now compromised. Anybody can extend `HttpRequestMethod` to add custom values, essentially voiding the reason for defining `HttpRequestMethod` in the first place.

This library provides built-in protection from these kinds of circumstances. Attempting to define an enumeration that extends another enumeration will result in an exception being thrown, unless the 'base' enumeration is abstract.

### Abstract enumerations

[](#abstract-enumerations)

Assuming that there really is a need to extend `HttpRequestMethod`, the way to go about it is to define an abstract base class, then extend this class to create the desired concrete enumerations:

```
use Somnambulist\Enumeration\AbstractEnumeration;

abstract class AbstractHttpRequestMethod extends AbstractEnumeration
{
    const OPTIONS = 'OPTIONS';
    const GET = 'GET';
    const HEAD = 'HEAD';
    const POST = 'POST';
    const PUT = 'PUT';
    const DELETE = 'DELETE';
    const TRACE = 'TRACE';
    const CONNECT = 'CONNECT';
}

final class HttpRequestMethod extends AbstractHttpRequestMethod {}

final class CustomHttpMethod extends AbstractHttpRequestMethod
{
    const PATCH = 'PATCH';
}
```

In this way, when a developer uses a type hint for `HttpRequestMethod`, there is no chance they will ever receive the 'PATCH' method:

```
function handleHttpRequest(HttpRequestMethod $method, $url, $body = null)
{
    // only handles normal requests...
}

function handleCustomHttpRequest(
    CustomHttpRequestMethod $method,
    $url,
    $body = null
) {
    // handles normal requests, and custom requests...
}
```

###  Health Score

33

—

LowBetter than 74% of packages

Maintenance41

Moderate activity, may be stable

Popularity19

Limited adoption so far

Community9

Small or concentrated contributor base

Maturity51

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 ~329 days

Total

2

Last Release

527d ago

### Community

Maintainers

![](https://www.gravatar.com/avatar/c0e439bf91b68c2e81e0250c752d3a552e78752c91acdf00c72a1f93aeb1ceca?d=identicon)[dredfern](/maintainers/dredfern)

---

Top Contributors

[![dave-redfern](https://avatars.githubusercontent.com/u/1477147?v=4)](https://github.com/dave-redfern "dave-redfern (6 commits)")

---

Tags

typeenumclassenumerationsetmultiton

###  Code Quality

TestsPHPUnit

### Embed Badge

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

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

###  Alternatives

[marc-mabe/php-enum

Simple and fast implementation of enumerations with native PHP

49444.8M97](/packages/marc-mabe-php-enum)[fresh/doctrine-enum-bundle

Provides support of ENUM type for Doctrine2 in Symfony applications.

4636.8M12](/packages/fresh-doctrine-enum-bundle)[consistence/consistence

Consistence - consistent approach and additions to PHP's functionality

1831.1M18](/packages/consistence-consistence)[cerbero/enum

Zero-dependencies package to supercharge enum functionalities.

359207.5k2](/packages/cerbero-enum)[garoevans/php-enum

Convenient way to always have an Enum object available and utilise Spl Types if available.

19158.8k5](/packages/garoevans-php-enum)[cerbero/laravel-enum

Laravel package to supercharge enum functionalities.

18989.6k](/packages/cerbero-laravel-enum)

PHPackages © 2026

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