tags:

views:

46

answers:

2

Hi all,

For a project I'm working I need to have some sort of enumaration class since the data won't be changed It's useless to store it in a database and exhaust the db-server with unnecessary request. So after reading some related posts on SO I tried the following:

class Model_MaintenanceTerminology
{
  const SetDefault = array("id" => 1, "title" => "set 1", "levels" => array("OLM", "ILM", "DLM"));
  const SetABC     = array("id" => 2, "title" => "A, B, C", "levels" => array("A", "B", "C"));
  const SetLevel   = array("id" => 3, "title" => "Level 1, Level 2, Level 3, Level 4", "levels" => array(1, 2, 3, 4);
}

The problem is that I have to build a dynamic form and the amount of levels used differ per country (some project related info). So I figured an enum-class like above would perfectly fit for my needs.

Now the problem seems that I can't declare arrays as constants. Anyone some thoughts about a different, better approach?

A: 

Never mind, after reading my own post for typo's I thought of a different approach getting the same result. My working solution is below, maybe it comes in handy for someone some day :)

My working solution:

class Model_MaintenanceTerminology
{
  const SetDefault = 1; 
  const SetABC     = 2; 
  const SetLevel   = 3; 


  public function getSetById(Integer $id)
  {
    switch($id->value)
    {
      case 2 : return array("id" => 2, "title" => "A, B, C", "levels" => array("A", "B", "C")); break;
      case 3 : return array("id" => 3, "title" => "Level 1, Level 2, Level 3, Level 4", "levels" => array(1, 2, 3, 4); break;
      default : return array("id" => 1, "title" => "set 1", "levels" => array("OLM", "ILM", "DLM"));
    }
  }
}
Ben Fransen
+1  A: 

If there aren't many different values, you could just use static accessor methods:

class Enum
{
    static function getFirstArray()
    {
        return array(/* ... */);
    }

    static function getSecondArray()
    {
        return array(/* ... */);
    }
}
Ignas R
Nice answer, +1, indeed there aren't many. I'll remember that :)
Ben Fransen