From b10465d55805aba0abdc26877e01dff886eba6c1 Mon Sep 17 00:00:00 2001 From: Mark Story Date: Fri, 4 Jul 2025 00:09:08 -0400 Subject: [PATCH] Expand the enum docs Add more content to the enum type documentation. I've included a similar code example using `match`, and a couple of the `bake` examples from https://www.dereuromark.de/2024/01/30/enums-in-cakephp-reloaded/ as recommended in the #8049. --- en/orm/database-basics.rst | 34 ++++++++++++++++++++++++++++++++-- 1 file changed, 32 insertions(+), 2 deletions(-) diff --git a/en/orm/database-basics.rst b/en/orm/database-basics.rst index 6e2c7205c7..742f6d38ad 100644 --- a/en/orm/database-basics.rst +++ b/en/orm/database-basics.rst @@ -493,7 +493,7 @@ To use this type you need to specify which column is associated to which BackedE $this->getSchema()->setColumnType('status', EnumType::from(ArticleStatus::class)); } -Where ``ArticleStatus`` contains something like:: +A simple ``ArticleStatus`` could look like:: namespace App\Model\Enum; @@ -503,6 +503,36 @@ Where ``ArticleStatus`` contains something like:: case Unpublished = 'N'; } +CakePHP also provides the ``EnumLabelInterface`` which can be implemented by +Enums that want to provide a map of human-readable labels:: + + namespace App\Model\Enum; + + use Cake\Database\Type\EnumLabelInterface; + + enum ArticleStatus: string implements EnumLabelInterface + { + case Published = 'Y'; + case Unpublished = 'N'; + + public static function label(): string + { + return match ($this) { + self::Published->value => __('Published'), + self::Unpublished->value => __('Unpublished'), + }; + } + } + +This can be useful if you want to use your enums in ``FormHelper`` select +inputs. You can use `bake `_ to generate an enum class:: + + # generate an enum class with two cases and stored as an integer + bin/cake bake enum UserStatus inactive:0,active:1 -i + + # generate an enum class with two cases as a string + bin/cake bake enum UserStatus published:Y,unpublished:N + CakePHP recommends a few conventions for enums: - Enum classnames should follow ``{Entity}{ColumnName}`` style to enable @@ -1100,7 +1130,7 @@ databases. For example to create a database:: .. note:: When creating a database it is a good idea to set the character set and - collation parameters (e.g. ``DEFAULT CHARACTER SET utf8mb4 DEFAULT COLLATE utf8mb4_unicode_ci``). + collation parameters (e.g. ``DEFAULT CHARACTER SET utf8mb4 DEFAULT COLLATE utf8mb4_unicode_ci``). If these values are missing, the database will set whatever system default values it uses. .. meta::