2

auto-implement_stringable_for_string_backed_enums

 2 years ago
source link: https://wiki.php.net/rfc/auto-implement_stringable_for_string_backed_enums
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

The problem

As the community starts adopting enums, people realize that they don't always work with libraries that deal with strings as input, since they're type-incompatible with the string type. In other cases, using enums requires casting them explicitly to strings by accessing their “->value” property, forcing needless boilerplate for people that don't use strict-mode.

A typical example is when using attributes. For example, Symfony has an #[IsGranted('SOME_ROLE')] attribute and ppl want to use it with enums like in #[IsGranted(PossibleRoles::SomeRole)]. Yet this is forbidden by the engine and ppl suggest that the definition of the IsGranted attribute is patched to accept backed enums as arguments.

As experienced on the Symfony repository, this problem is especially visible at the boundary of libraries: when some component accepts a string as input, ppl want them to also accept backed-enums. This usually means that they propose widening the accepted types of some method to make them work seamslessly with enums. Such patched methods then start with something like $input = $input instanceof \BackedEnum ? $input->value : $input;.

The problem for maintainers is that 1. widening an accepted type is a BC break for non-final public APIs since this can break child classes and 2. potentially any string argument is a candidate for such widening. This means that going this way creates a scalability issue for the adoption of enums: there is no way all libraries in the PHP ecosystem at large are going to do these changes everywhere string is accepted since there are too many of them and many libs would require a major version bump.

The scale of the concern means this should likely be fixed at the engine level.

So, to sum it up, even if people use enum for their application logic in valid ways, they face limitations if they want to use external libraries with their enums. It would be great if we could find ways to make it easier for general-purpose libraries to support enums without cluttering libraries with if/else blocks and without changing existing interfaces in a backwards-incompatible way.


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK