dasprid/enum

repository·master·Indexed 18 days ago

https://github.com/dasprid/enum

A PHP library providing a robust enum implementation for PHP 7.1+ environments. It allows for the creation of simple and complex enums via AbstractEnum, supporting singletons, data mapping through protected constants, and instance methods.

Tokens
713
Snippets
2
Records
2
Agent score
14%

What's inside dasprid-enum

  1. How to create a complex enum with data and methods

    master

    Enums in this library are singletons and can hold state. You can define protected constants that contain arrays of data, which are then passed to a protected constructor to initialize instance properties. This allows you to attach behavior (methods) to specific enum instances.

    Key characteristics:

    • Singletons: Enum instances are not cloneable or serializable.
    • Data Mapping: Use protected constants to store the data required for each instance.
    • Iteration: Use Planet::values() (or your class name) to iterate over all defined enum members.
    use DASPRiD\Enum\AbstractEnum;
    
    /**
     * @method static self MERCURY()
     * @method static self VENUS()
     */
    final class Planet extends AbstractEnum
    {
        protected const MERCURY = [3.303e+23, 2.4397e6];
        protected const VENUS = [4.869e+24, 6.0518e6];
    
        private $mass;
        private $radius;
    
        protected function __construct(float $mass, float $radius)
        {
            $this->mass = $mass;
            $this->radius = $radius;
        }
    
        public function mass() : float
        {
            return $this->mass;
        }
    
        // ... other methods
    }
    
    // Iterating through all values
    foreach (Planet::values() as $planet) {
        echo $planet->mass();
    }
  2. How to create a simple enum using AbstractEnum

    master

    To create a basic enum, extend DASPRiD\Enum\AbstractEnum. Define your enum members as protected constants. For simple enums, the constant values can be null as they are not used for data storage.

    To enable IDE auto-completion, you should add @method static self NAME() annotations to the class docblock for each constant.

    Note: public or private constants are ignored by the enum; only protected constants are treated as valid enum values.

    use DASPRiD\Enum\AbstractEnum;
    
    /**
     * @method static self MONDAY()
     * @method static self TUESDAY()
     */
    final class WeekDay extends AbstractEnum
    {
        protected const MONDAY = null;
        protected const TUESDAY = null;
    }
    
    // Usage
    $day = WeekDay::MONDAY();