views:

45

answers:

1

Let's say I have a class called Medium which can represent different types of media. For instance:

  • uploaded video
  • embedded video
  • uploaded image
  • embedded image

I represent these types with contants, like this:

class MediumAbstract
{
    const UPLOAD       = 0x0001;
    const EMBED        = 0x0010;
    const VIDEO        = 0x0100;
    const IMAGE        = 0x1000;

    const VIDEO_UPLOAD = 0x0101; // for convenience
    const VIDEO_EMBED  = 0x0110; // for convenience
    const IMAGE_UPLOAD = 0x1001; // for convenience
    const IMAGE_EMBED  = 0x1010; // for convenience

    const ALL          = 0x1111; // for convenience
}

Thus, it is easy for me to do a combined search on them on an (abstract) repository, with something like:

{
    public function findAllByType( $type )
    {
        ...
    }
}

$media = $repo->findAllByType( MediumAbstract::VIDEO | MediumAbstract::IMAGE_UPLOAD );
// or
$media = $repo->findAllByType( MediumAbstract::ALL );
// etc..

How do you feel about using these constant values in a concrete repository like a database? Is it ok? Or should I substitute them with meaningful data in the database.

Table medium:

| id |                type | location    | etc..
-------------------------------------------------
|  1 | use constants here? | /some/path  | etc..

(Of course I'll only be using the meaningful constants: VIDEO_UPLOAD, VIDEO_EMBED, IMAGE_UPLOAD and IMAGE_EMBED)

A: 

In mySQL, I would use SET. They are stored internally using the smallest amount of data, but give you a predefined clear text representation of the value:

SET('UPLOAD','EMBED','VIDEO','IMAGE); // costs 1 byte

Documentation on SET

You can apply database queries: SELECT * FROM table WHERE type IN ("UPLOAD", "EMBED")

If you use that, it would probably be easier to make the constants match the string values:

class MediumAbstract
{
    const UPLOAD       = "UPLOAD";
    const EMBED        = "EMBED";
    const VIDEO        = "VIDEO";
    const IMAGE        = "IMAGE";

(What you're doing right now: 0x0001 is not a bit mask anyway, but a hexadecimal value, isn't it? More here)

Pekka
Hi Pekka, thanks for your answer. Good that you mention mysql, as this is my DB of choice. So I added the tag. I believe the hex representation is still considered a bitmask as it still allows bitwise operations on them (not completely sure though). The hex values just illustrate the values more clear. See http://stackoverflow.com/questions/243712/why-use-hex also about this. Your solution is sound, but doesn't allow the bitwise operations on them. And I like using bitwise operations. That's why I asked the question.
fireeyedboy