|
1 | 1 | # PHP Enum |
2 | 2 |
|
3 | | - |
| 3 | +[](LICENSE) |
| 4 | +[](https://packagist.org/packages/ekvedaras/php-enum) |
| 5 | +[](https://packagist.org/packages/ekvedaras/php-enum) |
| 6 | + |
4 | 7 |
|
5 | | -PHP enum implementation |
| 8 | +Original idea taken from [happy-types/enumerable-type](https://packagist.org/packages/happy-types/enumerable-type), so take a look, it may suit your needs better. |
| 9 | +This package adds `meta` field, provides a few more methods like `options`, `keys`, `json`, etc. |
| 10 | +and there are `array` and illuminate `collection` implementations to choose from. |
| 11 | + |
| 12 | +## Benefits |
| 13 | + |
| 14 | +* Enums in general allow to avoid [magic values](https://en.wikipedia.org/wiki/Magic_number_(programming)#Unnamed_numerical_constants) |
| 15 | +* By type hinting forces only allowed values to be passed to methods (or returned) |
| 16 | +* Easy way to list all possible values |
| 17 | +* More feature rich and flexible then other enum implementations |
| 18 | +* IDE friendly, so auto complete, usage analysis and refactorings all work |
| 19 | + |
| 20 | +## Usage |
| 21 | + |
| 22 | +Create enums by extending either `EKvedaras\PHPEnum\PHPArray\Enum` or `EKvedaras\PHPEnum\Illuminate\Collection\Enum`. |
| 23 | + |
| 24 | +```php |
| 25 | +<?php |
| 26 | + |
| 27 | +use EKvedaras\PHPEnum\PHPArray\Enum; |
| 28 | + |
| 29 | +class PaymentStatus extends Enum { |
| 30 | + /** |
| 31 | + * @return static |
| 32 | + */ |
| 33 | + final public static function pending(): self |
| 34 | + { |
| 35 | + return static::get('pending', 'Payment is pending'); |
| 36 | + } |
| 37 | + |
| 38 | + /** |
| 39 | + * @return static |
| 40 | + */ |
| 41 | + final public static function completed(): self |
| 42 | + { |
| 43 | + return static::get('completed', 'Payment has been processed'); |
| 44 | + } |
| 45 | + |
| 46 | + /** |
| 47 | + * @return static |
| 48 | + */ |
| 49 | + final public static function failed(): self |
| 50 | + { |
| 51 | + return static::get('failed', 'Payment has failed'); |
| 52 | + } |
| 53 | +} |
| 54 | +``` |
0 commit comments