Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Where to store huge constants that my OOP class needs

Tags:

oop

php

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 that 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;
}
like image 320
sameold Avatar asked Jan 28 '26 22:01

sameold


2 Answers

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()

like image 116
gdub Avatar answered Jan 30 '26 15:01

gdub


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.

like image 39
Ernest Friedman-Hill Avatar answered Jan 30 '26 15:01

Ernest Friedman-Hill



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!