static/vendor/myclabs/php-enum/README.md

PHP Enum implementation inspired from SplEnum

Build Status Latest Stable Version Total Downloads psalm

Maintenance for this project is supported via Tidelift.

Why?

First, and mainly, SplEnum is not integrated to PHP, you have to install the extension separately.

Using an enum instead of class constants provides the following advantages:

This Enum class is not intended to replace class constants, but only to be used when it makes sense.

Installation

composer require myclabs/php-enum

Declaration

use MyCLabs\Enum\Enum;

/**
 * Action enum
 */
class Action extends Enum
{
    private const VIEW = 'view';
    private const EDIT = 'edit';
}

Usage

$action = Action::VIEW();

// or with a dynamic key:
$action = Action::$key();
// or with a dynamic value:
$action = new Action($value);

As you can see, static methods are automatically implemented to provide quick access to an enum value.

One advantage over using class constants is to be able to type-hint enum values:

function setAction(Action $action) {
    // ...
}

Documentation

Static methods:

Static methods

class Action extends Enum
{
    private const VIEW = 'view';
    private const EDIT = 'edit';
}

// Static method:
$action = Action::VIEW();
$action = Action::EDIT();

Static method helpers are implemented using __callStatic().

If you care about IDE autocompletion, you can either implement the static methods yourself:

class Action extends Enum
{
    private const VIEW = 'view';

    /**
     * @return Action
     */
    public static function VIEW() {
        return new Action(self::VIEW);
    }
}

or you can use phpdoc (this is supported in PhpStorm for example):

/**
 * @method static Action VIEW()
 * @method static Action EDIT()
 */
class Action extends Enum
{
    private const VIEW = 'view';
    private const EDIT = 'edit';
}

Related projects



kstawiski/OmicSelector documentation built on April 10, 2024, 11:11 p.m.