mleczek/enum

Enums in PHP

v1.1.0 2021-05-01 14:07 UTC

This package is auto-updated.

Last update: 2024-10-29 06:11:53 UTC


README

This package was created to provide simple way to create typed enums in PHP with IDE autocompletion.

The package is an alternative for SplEnum extension (PHP < 8.1) or native enum (PHP 8.1+). Why mleczek/enum over SplEnum? Much easier to install. Why mleczek/enum over native enum? Additional name/description field over traiditional key-value pair.

Installation

composer require mleczek/enum

Strict type

Properties, parameters and return types... strict type is everywhere.

function printStatus(StatusEnum $status) {
    echo $status->getDisplayName();
}

printStatus(StatusEnum::active()); // Active
printStatus(MyEnum::all()[0]); // PHP Fatal error:  Uncaught TypeError: Argument 1 passed to printStatus() must be an instance of StatusEnum, instance of MyEnum given

Accessing

One enum value or all available values? Not a problem.

StatusEnum::active(); // StatusEnum
StatusEnum::inactive(); // StatusEnum
StatusEnum::all(); // StatusEnum[]

The all() method returns enums that are sorted by value (case-insensitive for strings).

Comparing

The same enum instance is always returned, don't worry while using identical comparision.

StatusEnum::active() === StatusEnum::active(); // true
StatusEnum::active() === StatusEnum::inactive(); // false

Serializing

Serialize...

$value = $enum->getValue();

Deserializing

...and deserialize.

StatusEnum::parse($value); // StatusEnum
StatusEnum::parseOrDefault($value, StatusEnum::inactive()); // StatusEnum

Note: Implementation accept any type as enum value and use identical comparision. For complex types (which are not recommended) manually serialize and unserialize values.

Creating

Make class which extends Mleczek\Enum\Enum and define some static methods. That's all.

use Mleczek\Enum\Enum;

final class StatusEnum extends Enum
{
    public static function active(): self
    {
        return self::make('A', 'Active');
    }

    public static function inactive(): self
    {
        return self::make('I', 'Inactive');
    }
}