2
\$\begingroup\$

I have an object which stores an app configuration in an associative array, as this:

[
  'Database' => 
    [
      'DB_SERVER' => 'localhost'
      'DB_NAME' => 'adbname'
      'DB_USER' => 'theuser'
      'DB_PASS' => 'thepass'
    ]
]

It could have more than two levels.

And a function, get(), which receives a variable number of arguments and returns the configuration value for this parameters. For example, Config::get('Database','DB_PASS') will return 'thepass'.

This is an excerpt of the code:

class Config
{
    protected static $values;

    ...

    public static function get()
    {
        $val = &self::$values;
        $argList = func_get_args();
        for ($i = 0; $i < count($argList); $i++) {
            $val = &$val[$argList[$i]];
            if(empty($val)) break;
        }
        return (is_null($val)?"":$val);
    }
}

Is there a more elegant / efficient way of accessing the value?

(note: I posted the question here but I was notified this web was a proper place to ask)

\$\endgroup\$
  • \$\begingroup\$ Do you really need to be able to pass in an arbitrary length list of parameters to this function? \$\endgroup\$ – Mike Brant Jun 8 '16 at 15:05
3
\$\begingroup\$

Your code seems fine, but it's a bit verbose. You can make it more elegant with a foreach loop, clean up the way you exit the function, and if you're using PHP 5.6 or above you can use a real variable-length argument list. See:

http://php.net/manual/en/functions.arguments.php#functions.variable-arg-list

class ConfigurationHandle
{
    protected static $configuration;

    <...>

    public static function get(...$arguments)
    {
        $value = &self::$configuration;
        foreach($arguments as $argument)
        {  
          $value = &$value[$argument];
          if(empty($value)) return "";
        }
        return $value;
    }
}

I've written out full words, because there is no need to abbreviate. I think this code is more elegant, because it is easier to read and understand, but it is not more efficient.

It would be more efficient if you dumped the Config class altogether, and used a one dimensional array like this:

$configuration = ['DATABASE_SERVER' => 'localhost',
                  'DATABASE_NAME'   => 'adbname',
                  'DATABASE_USER'   => 'theuser',
                  'DATABASE_PASS'   => 'thepass'];

That is immeasurable more efficient, and might I say it's elegant too?

If top speed is not important to you, but multiple levels, and more control, are, then go for the class.

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.