Blog Detail

21

Oct
Powered Enum - Try Some Cool Features for Native PHP Enums cover image

arrow_back Powered Enum - Try Some Cool Features for Native PHP Enums

Powered Enum is a fantastic package that offers a trait that contains some cool features for native PHP enums. This package requires PHP 8.1 or higher.

Installation

Run this command in the terminal to install this package via composer.

composer require tkaratug/powered-enum

Declaration

All you need to do is use the PoweredEnum trait in your native PHP enums.

use Tkaratug\PoweredEnum\PoweredEnum;

enum MyEnum: int
{
    use PoweredEnum;
    
    case ONE    = 1;
    case TWO    = 2;
    case THREE  = 3;
}

Methods

is(), isNot()

You can check the equality of a case against any name by passing it to the is() and isNot() methods.

$myEnum = MyEnum::ONE;

$myEnum->is(MyEnum::ONE);      // true
$myEnum->is(MyEnum::TWO);      // false

$myEnum->isNot(MyEnum::ONE);   // false
$myEnum->isNot(MyEnum::TWO);   // true

Static Methods

hasName()

You can check whether an enum has a case by given name via the hasName() method.

enum MyEnum: int {
    use PoweredEnum;

    case ONE = 1;
    case TWO = 2;
}

MyEnum::hasName('ONE');     // true
MyEnum::hasName('THREE');   // false

hasValue()

You can check whether an enum has a case by given value via the hasValue() method.

enum MyEnum: int {
    use PoweredEnum;

    case ONE = 1;
    case TWO = 2;
}

MyEnum::hasValue(1);   // true
MyEnum::hasValue(3);   // false

getNames()

You can get enum case names as an array by using the getNames() method.

enum MyEnum: int {
    use PoweredEnum;

    case ONE = 1;
    case TWO = 2;
}

MyEnum::getNames();   // ['ONE', 'TWO']

getValues()

You can get enum case values as an array by using the getValues() method.

enum MyEnum: int {
    use PoweredEnum;

    case ONE = 1;
    case TWO = 2;
}

MyEnum::getValues();   // [1, 2]

Other Methods

  • toArray()
  • getNamesExcept()
  • getValuesExcept()
  • toArrayExcept()
  • getRandomName()
  • getRandomValue()
  • getRandomCase()

If you wanted to explore all available methods of this package, please visit to Github.

Published at : 21-10-2022

Author : Rizwan Aslam
AUTHOR
Rizwan Aslam

I am a highly results-driven professional with 12+ years of collective experience in the grounds of web application development especially in laravel, native android application development in java, and desktop application development in the dot net framework. Now managing a team of expert developers at Codebrisk.

Launch your project

Launch project