I'm writng a small application in PHP + MySQL and have come to the point where there is an object that has a couple (8 so far but not expected to increase) of flags associated with it. The flags are pretty much unrelated although there are some combinations that would make no sense. The object represents a row in a DB (has some methods for saving/loading it too) so the question also applies to choosing a storage method.
The question is - how to best represent them both in code and DB? I can think of several ways:
One way to store them in the DB is in a single integer field as bitwise flags. On the PHP side then I can imagine several ways of representing them:
- Simply export the integer value and define a couple of flag constants; Let every place that needs the flags do their own bitwise magic;
- Define class methods
GetFlag()
,SetFlag()
andUnsetFlag()
that do the bitwise magic on a private integer variable; These methods would then be passed one of the flag constants as a parameters. - Define methods
GetFlagA()
,GetFlagB()
etc. (along with Set and Unset counterparts); - Define a bunch of member variables that each represent one flag; Set them on loading from the DB and gather them when saving.
- Create a member variable that is an array of all the flag values. Use predefined constants as array indices to access each flag. Also fill/gather the array on loading/saving.
Another way would be to store them in the DB as separate BIT fields. In PHP that would then translate to several member variables. IMHO this would complicate the queries.
And the last way would be to define anothed table for all the flags and an intermediate table for many-to-many relationship between flags and the original objects. IMHO the messiest of all solutions, considering that there would be only like 3 tables otherwise.
I haven't done much PHP development so I don't know what the best practice would be. In C# I would probably store them as bitwise flags and make properties that do the bitwise magic on a private integer. But PHP doesn't have properties (I'm using latest stable version)...
SELECT * FROM mytable WHERE field3 AND !field5;
– Aquiline