Enum Helpers for PHP

Packages

February 24th, 2022

php-enum-helpers-featured.png

The release of PHP 8.1 brings native enumerations to PHP. The archtechx/enums composer package builds on native features and aims to make working with enums more lovable.

Using these library traits, you can add the following conveniences to your Enums in any PHP project:

  • Invokable cases - get the value of a backed Enum by invoking it
  • Names - return a list of case names in the enum
  • Values - return a list of case values in the enum
  • Options - return an associative array of case names and values

Given the above features, here are some examples from the package's readme file.

First up, here's how the InvokableCases trait works:

1// Invokable
2use ArchTech\Enums\InvokableCases;
3 
4enum TaskStatus: int
5{
6 use InvokableCases;
7 
8 case INCOMPLETE = 0;
9 case COMPLETED = 1;
10 case CANCELED = 2;
11}
12 
13TaskStatus::INCOMPLETE(); // 0
14TaskStatus::COMPLETED(); // 1
15TaskStatus::CANCELED(); // 2

Next, here's how to get case names from enums:

1use ArchTech\Enums\Names;
2 
3enum TaskStatus: int
4{
5 use Names;
6 
7 case INCOMPLETE = 0;
8 case COMPLETED = 1;
9 case CANCELED = 2;
10}
11 
12TaskStatus::names();
13// ['INCOMPLETE', 'COMPLETED', 'CANCELED']

The Values trait can return an array of possible enum values:

1use ArchTech\Enums\Values;
2 
3enum TaskStatus: int
4{
5 use Values;
6 
7 case INCOMPLETE = 0;
8 case COMPLETED = 1;
9 case CANCELED = 2;
10}
11 
12TaskStatus::values(); // [0, 1, 2]

Finally, the Options trait returns an associative array of names and values:

1use ArchTech\Enums\Options;
2 
3enum TaskStatus: int
4{
5 use Options;
6 
7 case INCOMPLETE = 0;
8 case COMPLETED = 1;
9 case CANCELED = 2;
10}
11 
12TaskStatus::options();
13// ['INCOMPLETE' => 0, 'COMPLETED' => 1, 'CANCELED' => 2]

You can learn more about this package, get full installation instructions, and view the source code on GitHub.

Filed in:

Paul Redmond

Full stack web developer. Author of Lumen Programming Guide and Docker for PHP Developers.

Laravel News Partners