开发者

Storing class constants (for use as bitmask) in a database?

开发者 https://www.devze.com 2022-12-25 20:58 出处:网络
Let\'s say I have a class called Medium which can represent different 开发者_C百科types of media. For instance:

Let's say I have a class called Medium which can represent different 开发者_C百科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)


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)

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号