Mastering Enum Tricks in PHP

itsimiro
3 min readMay 6, 2024

--

Let’s start with the basics. This is a special data type that allows you to define a set of named constants. Each constant represents a possible value of a variable, which makes your code more readable and less prone to errors.

I will not tell you how to create Enum, as I think everyone has already familiarized themselves with it.

What interesting things does Enum have to offer?

Consider some interesting facts you may not have known about.

Interfaces

Enum in PHP is very similar to a class, so you will have no problem creating it and using the interface.

enum UserRole: string implements FilterInterface
{
case ADMIN = 'admin';

public function applyFilter(): void
{
// TODO: Implement applyFilter() method.
}
}

Traits

You can expand the capabilities of your Enum by utilizing traits!

enum UserRole: string implements FilterInterface
{
use FilterTrait;

case ADMIN = 'admin';
}

Attributes

PHP attributes, introduced in version 8.1, can be effectively combined with enums to enhance their functionality.

Create an attribute

#[Attribute]
class Config
{
public function __construct(
public string $displayName,
public string $permission = ''
)
{}
}

And apply it to our enum constants. This is just an example of how you can use attributes.

enum UserRole: string implements FilterInterface
{
use FilterTrait, GetsAttributes;

#[Config(displayName: 'Administrator', permission: 'full_access')]
case Admin = 'admin';
}

What about using it in the project?

The vowel rule

Always adhere to the cardinal rule: use Enums for all enumerated cases.

// Not good
class Types
{
public const THEME = 'theme';
}

// Good
enum Type: string
{
case THEME = 'theme';
}

Rule of validation
Use the validation rule in your request to avoid unnecessary mistakes.

class CreateRequest extends FormRequest
{
public function rules(): array
{
return [
'type' => ['required', new Enum(TypeEnum::class)],
];
}

public function getType(): TypeEnum
{
return TypeEnum::from($this->validated('type'));
}
}

Enum as an inseparable part of the match

I’m not going to tell you what you can use match together with an enum, in my case, I’m using it for a factory. It is very useful to use enum here because your code editor will always tell you which case you haven’t implemented a handler for yet. Very handy!

return match ($type) {
Type::INTRO => $this->container->make(IntroAssetContentGenerator::class),
Type::TITLE => $this->container->make(TitleAssetContentGenerator::class),
Type::TESTIMONIAL => $this->container->make(TestimonialsAssetContentGenerator::class),
Type::FEATURES => $this->container->make(FeaturesAssetContentGenerator::class),
Type::CARDS => $this->container->make(CardsAssetContentGenerator::class),
Type::DYNAMIC_CONTENT => $this->container->make(DynamicContentAssetContentGenerator::class),
Type::CAROUSEL => $this->container->make(CarouselAssetContentGenerator::class),
Type::MEDIA => $this->container->make(MediaAssetContentGenerator::class),
};

Use Enum as the data type

Pass the enumerated data constant not as string but as Enum, this will improve code readability and reduce the number of errors.

public function sendCode(User $user): void
{
$this->otpService->send($user, OTPTypeEnum::TYPE_EMAIL);
}

// public function send(Notifiable $notifiable, OTPTypeEnum $type): void

Use Enum to cast

To avoid returning a string when getting data from the model, add enum casting, it is very useful in many cases.

protected $casts = [
'type' => TypeEnum::class,
];

Optional

You can also add a methodology for the convenient use of Enum. Most often I add the values method to get an array of values, but your imagination has no limits for using Enum.

public static function values(): array
{
return array_column(self::cases(), 'value');
}

public static function tryFromName(string $name): ?static
{
return collect(static::cases())
->first(fn (UnitEnum $case) => $case->name === $name);
}

Conclusion

Enums may seem simple at first glance, but they offer a wealth of benefits for PHP developers. By mastering Enum tricks and best practices, you can write cleaner, more maintainable code that’s less prone to errors. So why wait? Start leveraging the power of Enums in your PHP projects today!

--

--

itsimiro
itsimiro

Written by itsimiro

Passionate developer exploring the realms of software engineering. Writing about tech, coding adventures, and everything in between!

No responses yet