Skip to content

Commit 31952e1

Browse files
authored
Merge pull request #1076 from cakephp/docs-add-enum-section
docs: Add Bake Enums section to usage documentation
2 parents 4fde09a + efa8c7f commit 31952e1

File tree

1 file changed

+49
-0
lines changed

1 file changed

+49
-0
lines changed

docs/en/usage.rst

Lines changed: 49 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -64,6 +64,55 @@ For non-conventional relations, you can use references in the constraints / fore
6464
->addForeignKey('shipping_country_id', 'countries', 'cid')
6565

6666

67+
Bake Enums
68+
==========
69+
70+
You can use bake to generate `backed enums <https://www.php.net/manual/en/language.enumerations.backed.php>`_
71+
for use in your models. Enums are placed in **src/Model/Enum/** and implement
72+
``EnumLabelInterface`` which provides a ``label()`` method for human-readable display.
73+
74+
To bake a string-backed enum::
75+
76+
bin/cake bake enum ArticleStatus draft,published,archived
77+
78+
This generates **src/Model/Enum/ArticleStatus.php**::
79+
80+
namespace App\Model\Enum;
81+
82+
use Cake\Database\Type\EnumLabelInterface;
83+
use Cake\Utility\Inflector;
84+
85+
enum ArticleStatus: string implements EnumLabelInterface
86+
{
87+
case Draft = 'draft';
88+
case Published = 'published';
89+
case Archived = 'archived';
90+
91+
public function label(): string
92+
{
93+
return Inflector::humanize(Inflector::underscore($this->name));
94+
}
95+
}
96+
97+
For int-backed enums, use the ``-i`` option and provide values with colons::
98+
99+
bin/cake bake enum Priority low:1,medium:2,high:3 -i
100+
101+
This generates an int-backed enum::
102+
103+
enum Priority: int implements EnumLabelInterface
104+
{
105+
case Low = 1;
106+
case Medium = 2;
107+
case High = 3;
108+
109+
// ...
110+
}
111+
112+
You can also bake enums into plugins::
113+
114+
bin/cake bake enum MyPlugin.OrderStatus pending,processing,shipped
115+
67116
Bake Themes
68117
===========
69118

0 commit comments

Comments
 (0)