An approach to saving enum data types in PHP

Salar Gholizadeh
ITNEXT
Published in
2 min readNov 3, 2019

--

Update: PHP has implemented Enums since version 8.1 now which is more efficient and official way of using enums.

For any application crafted with PHP, It commonly happens that some classes have enum properties such as Status, Type and publish status. There might be several ways to save and fetch these values to and from the database, however, to have clean code and project-wide data structure convention, It’s a good idea to follow one method for the whole project.

let’s say we have a class named Post with a property called status. We want an easy way to determine and use a post’ status when coding. In this article, I assume that we are not going to need dynamic statuses.

The first approach that might come to mind is to save and use them in string format (like the way WordPress saves post status):

Although this might seem a good way at first, I don’t think it’s quite optimized mainly because addressing the post status inside a string might cause us not to quickly discover misspellings during the coding process.

The method I’m going to introduce in this article is quite simple and straight forward: Declare Constants in your class:

Unlike the previous method, Statically declaring each status is far more error-safe. Besides, If it’s needed to access text-based statuses (e.g. for translation purposes), we can add simply add a method for that. It’s also a good idea to store all statuses in one static array in order to access them as a whole. This is usually useful when it comes to validations and listings or selects.

As per suggestions on Reddit post, You can use Psalm to prevent your internal callers from setting invalid statuses. Also, It is a good idea to throw an Exception if an invalid value is given to setStatus function.

As you can see now it’s possible to get the post’s textual status when needed. and in this example, It is used for translation.

When it comes to storing things in the database, You can store the status in a Tinyint which is much smaller than string formats however, This could become considerable only when there are a big number of records in the database.

The whole idea is to have a sensible flow for parts of the project and there might be other effective ways of using and saving enums as per project and it’s requirements. If you read this article, I would be much appreciative to hear your ideas and opinions on this.

--

--