开发者

Where to store huge constants that my OOP class needs

I'm new to OOP and wondering what's the right OOP way to do this. My class has a method getValue which is passed input (a key) that it uses to search an array and return a value.

The thing is the array is HUGE close to 200 entries and really disrupts the readability of the method, so I'm inclined to remove it from this class, but not sure where to put it. Should I create a separate class for it, or put it in a constants class Constants::getValue() or any other suggestions? Would it be wrong to remove it from this class since it should be contained within the object t开发者_运维知识库hat needs it?

public function getValue($input) {
    switch ($input) {
        case 'in1' : { $value = array('wsj', 'kwo'); break; }
        case 'in2' : { $value = array('wpo', 'ki2'); break; }
        .....
        default:      { $value = array('wap', 'k90'); break; }
    }
    return $value;
}


You could create a key=>value array in another php file and include it in your class

content_array.php:

$ARRAY = array(
               'in1' => array('wsj','kwo'),
               'in2' => array('wpo','ki2'),
                ...
               'default' => array('wap','k90')
              );

then your function could look up these values like this:

public function getValue($input){
    include_once('content_array.php');
    if(array_key_exists($input, $ARRAY)){
        $value = $ARRAY[$input];
    } else {
        $value = $ARRAY['default'];
    }
    return $value;
}

If you don't like this method, you could put all your information in a JSON file, and then read that file into an array using json_decode()


If there are two hundred cases, and each one consists of constructing a small array from a few constants, then I'd strongly consider moving all the data into a file, and replacing it with a small amount of code that reads the file and stores everything in a map/lookup table, and then a bit of code that retrieves the correct response from the map. It would certainly be easier to maintain that way, and the code would be easier to understand.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜