@@ -39,6 +39,10 @@ to the require section of your `composer.json` file.
39
39
## Declaration
40
40
41
41
``` php
42
+ <?php
43
+
44
+ namespace app\models\enums;
45
+
42
46
use yii2mod\enum\helpers\BaseEnum;
43
47
44
48
class PostStatus extends BaseEnum
@@ -66,7 +70,16 @@ class PostStatus extends BaseEnum
66
70
];
67
71
}
68
72
```
69
- ## Usage
73
+ ## Enum creation
74
+ ``` php
75
+ $status = new PostStatus(PostStatus::PENDING);
76
+
77
+ // or you can use the magic methods
78
+
79
+ $status = PostStatus::PENDING();
80
+ ```
81
+
82
+ ## Static methods
70
83
``` php
71
84
PostStatus::getConstantsByValue() // ['PENDING', 'APPROVED', 'REJECTED', 'POSTPONED']
72
85
PostStatus::getConstantsByName() // ['PENDING' => 0, 'APPROVED' => 1, 'REJECTED' => 2, 'POSTPONED' => 3]
@@ -78,3 +91,35 @@ PostStatus::listData() // ['Pending', 'Approved', 'Rejected', 'Postponed']
78
91
PostStatus::getLabel(1) // Approved
79
92
PostStatus::getValueByName('Approved') // 1
80
93
```
94
+ ## Type-Hint and Validation Rules
95
+ ``` php
96
+ <?php
97
+
98
+ use models\enums\PostStatus;
99
+ use yii\db\ActiveRecord;
100
+
101
+ class CommentModel extends ActiveRecord
102
+ {
103
+ public function rules()
104
+ {
105
+ return [
106
+ ['status', 'default', 'value' => PostStatus::APPROVED],
107
+ ['status', 'in', 'range' => PostStatus::getConstantsByName()],
108
+ ];
109
+ }
110
+
111
+ public function setStatus(PostStatus $status)
112
+ {
113
+ $this->status = $status;
114
+ }
115
+
116
+ public function getStatus()
117
+ {
118
+ if (!$this->status) {
119
+ $this->status = PostStatus::PENDING();
120
+ }
121
+ return $this->status;
122
+ }
123
+ }
124
+ ```
125
+
0 commit comments