Looking for more information on how to do PHP the right way? Check out PHP: The Right Way

Ben Sampson:
Using enums in Laravel
May 31, 2018 @ 17:26:57

Ben Sampson has written up a tutorial showing you how to use enums in Laravel despite them not being natively supported in PHP.

I'm a big fan of enums. Having recently worked for a company who use C#, where enums are used extensively, I've got used to being able to reach for them and miss them when they're not available. I use them for anything with a limited set of possible options, such as days of the week, the status of an order or, as in the examples below, user type.

[...] Enums aren't natively supported in PHP but an equivalent is fairly easy to achieve using constants on a class. Futhermore I've created a Laravel package called laravel-enum which allows you access helper functions such as listing keys and values, attaching descriptions to values, and validating requests which are expecting enum values.

He then walks you through the Composer installation of the package and provides an example of it in use. In his example he sets up an enum for types of users, defined in a special UserType file (admins, members and paid members). He stores these values in the database and then makes use of the type property on the user to see what type of user they are. He finishes up the post with an example of showing the value of the enum and performing validation on the value with Laravel's built-in validators.

tagged: enum laravel tutorial package laravelenum example

Link: https://sampo.co.uk/blog/using-enums-in-laravel

Alejandro Celaya:
Working with custom column types in Doctrine. Enums.
Jul 30, 2015 @ 13:37:45

Alejandro Celaya has a post to his site showing you how to work with custom types in Doctrine, more specifically with the "enum" type.

Doctrine is currently the most used ORM in PHP. It makes it very easy to work with databases in an object oriented way. It comes with a set of built-in column types that map database types with PHP types. For example, the datetime column type, persists the value of an entity column as a datetime in the database and handles it as a DateTime object when the entity is hydrated.

Type conversions work both ways, so column types take care of casting database to PHP types and vice versa. In this article I'm going to explain how to define custom column types so that we can persist our own objects into the database and hydrate them back.

He points out that, while PHP itself lacks the "enum" data type, you can simulate it with a library like this. He uses this library to create a custom Doctrine object type that mimic enums in the getting and setting of a value to one of a few options. In this case it's values representing the CRUD methods. He shows the code to link the Type back to the Action which then gives it understanding of what the valid enum values can be. He also points out another package that he published recently that takes some of the work out of creating the boilerplate code for the enum.

tagged: package action tutorial enum type doctrine custom library

Link: http://blog.alejandrocelaya.com/2015/07/28/working-with-custom-column-types-in-doctrine-enums/

Lee Davis' Blog:
The enum conundrum
Jul 06, 2012 @ 16:56:52

In a new post to his blog Lee Davis describes the enum conundrum - what's the right solution for effectively using ENUM-type fields in your data?

So a user signs up and I want to store a status that reflects their account, or at least an identifier representing that status. Their account could be active, disabled (temporarily), pending approval or maybe deleted. Should I use an enum? I’ve heard they’re evil. Maybe having a reference table with statuses would be better? But now I have to manage a separate table just for that one snippet of data, is that overkill? Could I maybe use that status table for other entities? Or, could I instead just use an integer and reference it on the code level? What is the right solution?

He presents three of the most common situations he's seen for people using enums in the application:

  • "I used enums all over the place" (maintenance between code and DB values)
  • "use a reference table"
  • "I could use a class constant to represent the enum" (enforced in the app)

Of the three, he suggests the third as the option with the most advantages. Not only does it make it simpler to get the allowed values for the field, but you're also more flexible in the kinds of validation you can do on the values.

tagged: enum conundrum reference table constant maintenance

Link:

Giulio Pons' Blog:
PHP to get enum/set values from mysql field
Jan 21, 2010 @ 17:14:26

Giulio Pons has a quick post with a code snippet showing how to grab the possible values for an ENUM or SET field on a MySQL database.

This function returns an array with the elements allowed in a ENUM or SET mysql field. This can be usefull if you’re making some automation and need to retrieve those values without writing them in your code.

The function uses the database's metadata to get the column information for a table and filter out the "enum" information from that. The column information includes the set of values possible and a few simple string handling functions make it easy to grab them. They could also be replaced by a regular expression or two to grab the same information more concisely.

tagged: enum mysql allowed values

Link:

Debuggable Blog:
How to Fetch the ENUM Options of a Field - The CakePHP Enumerable Behavior
Sep 08, 2009 @ 16:47:09

On the Debuggable blog, Tim Koschutzki has added a quick post looking at fetching ENUM options of a database's fields in a CakePHP application.

The field users.level is an enum type and can have the values 'guest', 'user', 'admin', 'superadmin' and 'root'. The problem is that it could be possible that new levels were added in the future. [...] So what I came up with is a very simple behavior that can extract the options for any ENUM field. It uses simple caching in order for the query to not be run all the time, so make sure to clear your cache as you update your enum field options in the db.

His code snippet creates an EnumerableBehavior for the model and grabs the column names from the given table to check the access level for each and write them out to a cache.

tagged: cakephp framework enum option database

Link:

Benjamin Eberlei's Blog:
Enums in PHP
Sep 01, 2009 @ 17:46:34

In a new post to his blog Benjamin Eberlei talks about enum data types in PHP and how the is getting close but still isn't quite there yet.

If you want to implement Enum behaviour with a simple string or int value you end up with having to validate the values at several different locations in the code rather than being able to strictly enforce the Enum structure by using typehints.

In an effort to try to help the situation he and a colleague came up with an abstract class MyEnum that uses the __toString method to do value checking. Code examples are included for the class and how to use it.

tagged: enum splenum example code

Link:

Jeremy Johnstone's Blog:
Enums in PHP
Oct 06, 2008 @ 12:56:08

In this new post Jeremy Johnstone looks at creating a class to add that's missing from the basic datatype set of the language - enums.

I stumbled across a blog post on how to implement Enums in PHP via userland code written by Jonathan Hohle. I liked the concept he had, but the implementation was a bit unappealing because it used eval() among other more minor issues. You shouldn't need to generate Enums at runtime, so I took that as a challenge to find a way to do it at compile time, thus making the code much more efficient.

His enums would support type hinting and would, ideally, be iterable. He gives the code he's worked up - a base class, another than extends it to make a basic enum structure and some handy changes to support comparisons. A few more changes (and a few other extended classes later) he has some pretty well functioning enums that can even bee iterated through.

tagged: enum tutorial base datatype userland class

Link:

PHP in Action Blog:
I want enums in PHP
May 12, 2008 @ 13:41:16

I want Enums in PHP

That's how this new post on the PHP in Action blog starts this morning. The one thing that he wants is enumeration support in PHP. He shows how it can currently come close with a "roles" system:

Useful examples I've encountered in web programming are states or stages in a process and user roles. Another kind of example is one I used in PHP In Action: an authorization system with three fixed roles or categories of user: regular, webmaster and administrator.

He sets up an example class that sets constants for the different access levels rather than just relying on strings to handle it (which, as he points out, could very easily be misspelled and not throw any kind of error) .

tagged: enumeraction enum phpinaction multiple value constant

Link:


Trending Topics: