PHP Enum - get rid of boilerplate mappings
Hey there. Just decided to put together a small package, that will help me to get rid of boilerplate mappings likepublic function getAll(): array // returns some static array of strings
.
You just need to define constants, and myEnum\Enum
class will do the rest for you, thanks to Reflection API.
Here is an example:
<?phpnamespaceApp;useEnum\Enum;classStatusextendsEnum{constACTIVE='active';constINACTIVE='inactive';constBLOCKED='blocked';}$status=newStatus();$status->toArray();// will return [ 'active' => 'active', 'inactive' => 'inactive', 'blocked' => 'blocked' ]$status->hasValue('active');// will return boolean$status->hasKey('blocked');// will return boolean
Enum
's constructor has 2 parameters:$caseLower=true
and$caseUpper=false
.
If you want the case of array keys to be same as constants case - passfalse
as$caseLower
.
$status=newStatus(false);
If you want the case of array keys to be uppercase - passfalse
as$caseLower
andtrue
as$caseUpper
.
$status=newStatus(false,true);
We just created our custom typeEnum
. Now I can even use it to have better typed properties in my classes. For example:
<?phpnamespaceApp;useEnum\Enum;classPerson{publicint$identifier;publicstring$name;publicEnum$status;}
Now I know exactly what type has my$status
and I know exactly how I should work with that type. I find this much better than using some raw arrays.
GitHub repo:
hakobyansen / phpenum
All constants in your class, which extends Enum, will be converted to array of enum options.
Have a nice day!
Top comments(0)
For further actions, you may consider blocking this person and/orreporting abuse