Skip to content

Simple and fast implementation of enumerations with native PHP 5.3 and upper

License

Notifications You must be signed in to change notification settings

mglowala/php-enum

 
 

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

php-enum

Build Status Quality Score Code Coverage Total Downloads Latest Stable Dependency Status

This is a native PHP implementation to add enumeration support to PHP >= 5.3. It's an abstract class that needs to be extended to use it.

What is an Enumeration?

Wikipedia

In computer programming, an enumerated type (also called enumeration or enum) is a data type consisting of a set of named values called elements, members or enumerators of the type. The enumerator names are usually identifiers that behave as constants in the language. A variable that has been declared as having an enumerated type can be assigned any of the enumerators as a value. In other words, an enumerated type has values that are different from each other, and that can be compared and assigned, but which do not have any particular concrete representation in the computer's memory; compilers and interpreters can represent them arbitrarily.

Usage

Basics

    use MabeEnum\Enum;

    // define an own enumeration class
    class UserStatus extends Enum
    {
        const INACTIVE = 0;
        const ACTIVE   = 1;
        const DELETED  = 2;

        // all scalar datatypes are supported
        const NIL     = null;
        const BOOLEAN = true;
        const INT     = 1234;
        const STR     = 'string';
        const FLOAT   = 0.123;
    }
    
    // different ways to instantiate an enumerator
    $status = UserStatus::get(UserStatus::ACTIVE);
    $status = UserStatus::ACTIVE();
    $status = UserStatus::getByName('ACTIVE');
    $status = UserStatus::getByOrdinal(1);
    
    // available methods to get the selected entry
    $status->getValue();   // returns the selected constant value
    $status->getName();    // returns the selected constant name
    $status->getOrdinal(); // returns the ordinal number of the selected constant
    (string) $status;      // returns the selected constant name
    
    // same enumerators (of the same enumeration class) holds the same instance
    UserStatus::get(UserStatus::ACTIVE) === UserStatus::ACTIVE()
    UserStatus::get(UserStatus::DELETED) != UserStatus::INACTIVE()

    // simplified way to compare two enumerators
    UserStatus::ACTIVE()->is(UserStatus::ACTIVE);     // true
    UserStatus::ACTIVE()->is(UserStatus::ACTIVE());   // true
    UserStatus::ACTIVE()->is(UserStatus::DELETED);    // false
    UserStatus::ACTIVE()->is(UserStatus::DELETED());  // false

Type-Hint

    use MabeEnum\Enum;

    class User
    {
        protected $status;
    
        public function setStatus(UserStatus $status)
        {
            $this->status = $status;
        }
    
        public function getStatus()
        {
            if (!$this->status) {
                // initialize the default enumerator
                $this->status = UserStatus::get(UserStatus::INACTIVE);
            }
            return $this->status;
        }
    }

Type-Hint issue

Because in normal OOP the above example allows UserStatus and types inherited from it.

Please think about the following example:

    class ExtendedUserStatus
    {
        const EXTENDED = 'extended';
    }

    $user->setStatus(ExtendedUserStatus::EXTENDED());

Now the setter receives a status it doesn't know about but allows it. If your User class doesn't allow it the following is the recommanded way:

    class User
    {
        // ...
        public function setStatus($status)
        {
            $this->status = UserStatus::get($status);
        }
        // ...
    }

Now you are 100% sure to work with an exact instance of UserStatus.

(If the setter receives an extended status the value will be used to receive the corresponding instance of UserStatus else an exception will be thrown.)

EnumMap

An EnumMap maps enumerators of the same type to data assigned to.

Internally the EnumMap is based of SplObjectStorage.

    use MabeEnum\EnumMap;

    // create a new EnumMap
    $enumMap = new EnumMap('UserStatus');

    // attach entries (by value or by instance)
    $enumMap->attach(UserStatus::INACTIVE, 'inaktiv');
    $enumMap->attach(UserStatus::ACTIVE(), 'aktiv');
    $enumMap->attach(UserStatus::DELETED(), 'gelöscht');
    
    // detach entries (by value or by instance)
    $enumMap->detach(UserStatus::INACTIVE);
    $enumMap->detach(UserStatus::DELETED());
    
    // iterate
    var_dump(iterator_to_array($enumSet)); // array(0 => UserStatus{$value=1});

    // define key and value used for iteration
    $enumSet->setFlags(EnumMap::KEY_AS_NAME | EnumMap::CURRENT_AS_DATA);
    var_dump(iterator_to_array($enumSet)); // array('ACTIVE' => 'aktiv');

EnumSet

An EnumSet groups enumerators of the same enumeration type together.

Internally it's based of an integer bit set.

The maximun number of enumerators are limited by the size of an integer.

Enumerators will be ordered by the ordinal number.

    use MabeEnum\EnumSet;

    // create a new EnumSet
    $enumSet = new EnumSet('UserStatus');

    // attach entries (by value or by instance)
    $enumSet->attach(UserStatus::INACTIVE);
    $enumSet->attach(UserStatus::ACTIVE());
    $enumSet->attach(UserStatus::DELETED());
    
    // detach entries (by value or by instance)
    $enumSet->detach(UserStatus::INACTIVE);
    $enumSet->detach(UserStatus::DELETED());
    
    // iterate
    var_dump(iterator_to_array($enumSet)); // array(0 => UserStatus{$value=1});

Serializing

Because this enumeration implementation is based on a singleton pattern and in PHP it's currently impossible to unserialize a singleton without creating a new instance this feature isn't supported without any additional work.

As of it's an often requested feature there is a trait that can be added to your enumeration definition. This trait adds this functionallity and does some magic stuff to reduce singleton breakage but it can only avoid such beak if an enumerator will be unserialized before it will be instantiated normally.

Use it with caution!

Example of using EnumSerializableTrait

    use MabeEnum\Enum;
    use MabeEnum\EnumSerializableTrait;
    use Serializable;
    
    class CardinalDirection extends Enum implements Serializable
    {
        use EnumSerializableTrait;
    
        const NORTH = 'n';
        const EAST  = 'e';
        const WEST  = 'w';
        const SOUTH = 's';
    }
    
    $north1 = CardinalDirection::NORTH();
    $north2 = unserialize(serialize($north1));
    
    // The following could be FALSE as described above
    var_dump($north1 === $north2);

Why not SplEnum

  • SplEnum is not build-in into PHP and requires pecl extension installed.
  • Instances of the same value of an SplEnum are not the same instance.
  • SplEnum doesn't have implemented EnumMap or EnumSet.

Install

Composer

Add marc-mabe/php-enum to the project's composer.json dependencies and run php composer.phar install

GIT

git clone git://github.com/marc-mabe/php-enum.git

ZIP / TAR

Download the last version from Github and extract it.

New BSD License

The files in this archive are released under the New BSD License. You can find a copy of this license in LICENSE.txt file.

About

Simple and fast implementation of enumerations with native PHP 5.3 and upper

Resources

License

Stars

Watchers

Forks

Packages

No packages published

Languages

  • PHP 100.0%