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:
GetFlag()
, SetFlag()
and UnsetFlag()
that do the bitwise magic on a private integer variable; These methods would then be passed one of the flag constants as a parameters.GetFlagA()
, GetFlagB()
etc. (along with Set and Unset counterparts);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)...
In your model, the object has 8 boolean properties. That implies 8 boolean (TINYINT for MySQL) columns in your database table and 8 getter/setter methods in your object. Simple and conventional.
Rethink your current approach. Imagine what the next guy who has to maintain this thing will be saying.
CREATE TABLE mytable (myfield BIT(8));
OK, looks like we're going to have some binary data happening here.
INSERT INTO mytable VALUES (b'00101000');
Wait, somebody tell me again what each of those 1s and 0s stands for.
SELECT * FROM mytable;
+------------+
| mybitfield |
+------------+
| ( |
+------------+
What?
SELECT * FROM mytable WHERE myfield & b'00101000' = b'00100000';
WTF!? WTF!?
stabs self in face
-- meanwhile, in an alternate universe where fairies play with unicorns and programmers don't hate DBAs... --
SELECT * FROM mytable WHERE field3 = 1 AND field5 = 0;
Happiness and sunshine!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With