No Compromises artwork

No Compromises · Joel Clermont and Aaron Saray

How much logic is too much logic in a PHP enum

Have you ever added a method to an enum and then wondered if you just turned it into something it was never meant to be? In the latest episode of the No Compromises podcast, we discuss where to draw the line when adding methods and logic to PHP enums. We trace the evolution from magic strings to constants to interfaces, and explain why enums were the missing piece PHP needed all along. We also cover when label methods and data structure helpers belong on an enum, why Eloquent queries cross a line, and how to avoid turning a simple enum into a bloated helper class. (00:00) - Why magic strings and constants fall short (01:43) - How PHP enums replaced interface constants (02:26) - What methods belong on an enum (06:58) - The rule for keeping enum methods focused (10:44) - Silly bit Join developers who think carefully about clean code decisions in the No Compromises community.

Jun 62026
13 minlength
129transcript lines
Publishertranscript source

Transcript first 15 of 129 lines

0:00JoelWelcome to No Compromises. A peek into the mind of two old web devs who have seen some things. This is Joel.

0:08AaronAnd this is Aaron.

0:16You know, I really hate magic strings. You know what I mean when I say magic strings or magic numbers?

0:22JoelYeah, abracadabra.

0:23AaronNo. But strings are numbers in our application that mean something. So, for example, ID 1 is a user, maybe negative 99 means something else

0:33which is a horrible thing to do.

0:35JoelRight.

0:36AaronOr, you have a status, a connection status, and it's the word good. Or problem, or something like that.

0:43JoelIt's something you're matching against in logic where it has a special meaning to it.

0:47AaronYeah. They're called magic because they are strings, but they have a meaning so, that's the magic to it.

0:53So, in PHP, for a long time, we didn't really have anything to do about that. I was really jealous of

0:57other languages when they started talking about things like enums, and we didn't have that. So, what we did a lot of times is use constants.

1:04JoelSure.

1:05AaronYou could define a constant in your runtime, but then I extended that. And I learned it from someone, too, I'm sure.

1:11But interfaces can have constants defined on them. So you could use an interface in PHP to define the properties...

More No Compromises episodes →