Introduce wider support for PHP Enum's #41246
Replies: 3 comments
-
To be honest, I think the example from Laravel.io is still one I wouldn't change. The constants on the policies are fine and keep all related code to policies in a single class. But I do agree enum support here could maybe be useful to others. |
Beta Was this translation helpful? Give feedback.
-
You could add a helper function 'enum' that can be used throughout the code. The existing 'value' helper function could also be changed, although that might have some unexpected results for some users if they use it somehow to get an enum as object. And when you add a helper function for it, you could also broaden the casting concept. That way laravel could add a lot more support than just backed enums. |
Beta Was this translation helpful? Give feedback.
-
I also think that enum support (especially string/int backed ones) is half baked at best.
|
Beta Was this translation helpful? Give feedback.
Uh oh!
There was an error while loading. Please reload this page.
-
Using a real-world example, I recently created a PR for Laravel.io here. Unfortunately, due to the complexity of PHP enums, we have to call
->value()
on the enum instance before passing it to methods (such asGate::authorise()
), this PR got rejected due to increased visual complexity.From my experience, it's common practice to use PHP constants for the following use case:
With the addition of backed enums in PHP 8.1, it stands to reason that people may seek to migrate these constants over to a PHP backed-enum. However, because these aren't supported by the underlying authorization gate, the above is not possible, instead we have to call
->value()
on the enum before it is passed to$this->authorize()
, causing the problem @driesvints had with the above PR.The solution to this is to broaden the scope of Laravel's adoption of PHP's backed-enums. We can already cast to enums in our Eloquent models, so adopting support for enums in other areas seems to me, like a sensible decision. The only problem I have is littering the codebase with
$ability = $ability instanceof \BackedEnum ? $ability->value() : $ability;
.Any thoughts / expansions on this would be welcome, I'm not sure on the best solution here, but widening support for enums I would envision having a broad adoption. Thanks for the consideration 💪
Beta Was this translation helpful? Give feedback.
All reactions