Skip to content

Commit db43a44

Browse files
committed
Documentation
1 parent d71fc4e commit db43a44

File tree

2 files changed

+71
-3
lines changed

2 files changed

+71
-3
lines changed

README.md

Lines changed: 70 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,2 +1,70 @@
1-
PHP Enum implementation inspired from SplEnum
2-
========
1+
# PHP Enum implementation inspired from SplEnum
2+
3+
4+
## Why?
5+
6+
Using an enum instead of class constants provides the following advantages:
7+
8+
- You can type-hint: `function setAction(Action $action) {`
9+
- You can enrich the enum with methods (e.g. `format`, `parse`, …)
10+
- You can extend the enum to add new values (make your enum `final` to prevent it)
11+
- You can get a list of all the possible values (see below)
12+
13+
This Enum class is not intended to replace class constants, but only to be used when it makes sense.
14+
15+
16+
## Declaration
17+
18+
```php
19+
use Mycsense\Enum\Enum;
20+
21+
/**
22+
* Action enum
23+
*/
24+
class Action extends Enum
25+
{
26+
const VIEW = 'view';
27+
const EDIT = 'edit';
28+
29+
/**
30+
* @return Action
31+
*/
32+
public static function VIEW() {
33+
return new Action(self::VIEW);
34+
}
35+
36+
/**
37+
* @return Action
38+
*/
39+
public static function EDIT() {
40+
return new Action(self::EDIT);
41+
}
42+
}
43+
```
44+
45+
Implementing the static methods `VIEW()` and `EDIT()` is optional, it only serves as shortcut to `new Action(Action::VIEW)`.
46+
47+
48+
## Usage
49+
50+
```php
51+
$action = Action::VIEW();
52+
53+
// or
54+
$action = new Action(Action::VIEW);
55+
```
56+
57+
One advantage over using class constants is to be able to type-hint enum values:
58+
59+
```
60+
function setAction(Action $action) {
61+
// ...
62+
}
63+
```
64+
65+
## Documentation
66+
67+
- `__construct()` The constructor checks that the value exist in the enum
68+
- `__toString()` You can `echo $myValue`, it will display the enum value (value of the constant)
69+
- `getValue()` Returns the current value of the enum
70+
- `toArray()` (static) Returns an array of all possible values (constant name in key, constant value in value)

src/Mycsense/Enum/Enum.php

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -51,7 +51,7 @@ public function __toString()
5151

5252
/**
5353
* Returns all possible values as an array
54-
* @return array
54+
* @return array Constant name in key, constant value in value
5555
*/
5656
public static function toArray()
5757
{

0 commit comments

Comments
 (0)