Extending PHP enums with attributes

By Rob Fonseca

With the release of PHP 8.1, the language gained native support for enums. Enums are a type-safe, readable and efficient way to encapsulate a small set of possible values a field can take in your data model. Using classes instead of database enums provides more flexibility if you need to add to the list in the future.

As an example, you have a user data model and that user might have a specific list of roles you can choose from.

namespace App\Enums;
 
enum UserRole: string
{
case Admin = 'admin';
case TeamAdmin = 'team_admin';
case Support = 'support';
case Basic = 'basic';
}

In your data model, Laravel also has support for enums by casting them to the value if you define it in your casts array.

/**
* The attributes that should be cast.
*
* @var array<string,string|class-string>
*/
protected $casts = [
'role' => UserRole::class,
];

Adding the enum casting will ensure that an exception will be thrown if we try to save a role to our user model not defined in the enum.

A very practical use of enums is to generate values for a dropdown in your HTML

<select name=”roles”>
@foreach(UserRole::cases() as $role)
<option value="{{ $role->value }}">{{ $role->name }}</option>
@endforeach
</select>

On the surface, nothing seems wrong with the example above until you look at the visible name of each option in the dropdown. Admin and TeamAdmin are great variable names, but Administrator and Team Administrator would be better to present in the UI, so it is crystal clear what the role is to the person managing user roles.

While enums are great for simple name/value pairs, in cases like this where you need to add a 3rd property, you have to get creative.

Enter PHP attributes. Borrowed from the concept of annotations in other languages, it is a way to associate metadata to properties, methods and classes, which sounds exactly like what we need.

First, we need to build a Description attribute.

namespace App\Enums\Attributes;
 
use Attribute;
 
#[Attribute]
class Description
{
public function __construct(
public string $description,
) {
}
}

We now have a Description attribute we can leverage in our enum so we can define the user-friendly role names we desire.

namespace App\Enums;
 
enum UserRole: string
{
#[Description('Administrator')]
case Admin = 'admin';
 
#[Description('Team Administrator')]
case TeamAdmin = 'team_admin';
 
case Support = 'support';
case basic = 'basic';
}

Now we need to retrieve these attributes, which can only be done via reflection. Since we may want to reuse this attribute on other enums, we will want to make a trait to make this easier.

namespace App\Enums\Concerns;
 
use Illuminate\Support\Str;
use ReflectionClassConstant;
use App\Enums\Attributes\Description;
 
trait GetsAttributes
{
/**
* @param self $enum
*/
private static function getDescription(self $enum): string
{
$ref = new ReflectionClassConstant(self::class, $enum->name);
$classAttributes = $ref->getAttributes(Description::class);
 
if (count($classAttributes) === 0) {
return Str::headline($enum->value);
}
 
return $classAttributes[0]->newInstance()->description;
}
}

If we break this method down, the first 2 lines are using reflection to get the attributes of the enum. Since not every enum may have a Description attribute, we set up a fallback to transform the value (or name) of that enum as our description.

Lastly, we pull the value of the description from the enum attributes. We can add another method to our trait to handle this.

/**
* @return array<string,string>
*/
public static function asSelectArray(): array
{
/** @var array<string,string> $values */
$values = collect(self::cases())
->map(function ($enum) {
return [
'name' => self::getDescription($enum),
'value' => $enum->value,
];
})->toArray();
 
return $values;
}

Now, in our HTML, we can simply change the method we call on the enum class

<select name=”roles”>
@foreach(UserRoles::asSelectArray() as $role)
<option value={{ $role->value }}>{{ $role->name }}</option>
@endforeach
</select>

While they are relative newcomers to PHP, enums and attributes are great additions to the language and provide native support for many common use cases.

Rob Fonseca
Web Application Developer
Author Image

Interested in speaking with a developer?

Connect with us.
©2024 Kirschbaum Development Group LLC Privacy Policy Terms of Service