1
\$\begingroup\$

I'm working on a config class for PHP, where I can easily bring in config options. Any improvements/suggestions are appreciated.

class Config{
        private $defaultPath;
        private $config;
        private $file;
    public function __construct($filePath=null){
        $this->defaultPath = realpath(__DIR__.'/../../../..').'/GateConfig.php';
        if(is_file($filePath)){
              $this->file = $filePath;
        }else{
            $this->file = $this->defaultPath;
        }
        $this->load();
    }
    public function get($key, $default = null)
    {
        $array = $this->config;
        if (is_null($key)) return $default;
        if (isset($array[$key])) return $array[$key];
        foreach (explode('.', $key) as $segment) {
            if (!is_array($array) || !array_key_exists($segment, $array)) {
                return $default;
            }
            $array = $array[$segment];
        }
        return $array;
    }
    public function set($key, $value)
    {
        $array = &$this->config;
        if (isset($array[$key])) {
            $array[$key] = $value;
        }
        $keys = explode('.', $key);
        while (count($keys) > 1) {
            $key = array_shift($keys);
            $array = &$array[$key];
        }
        $array[array_shift($keys)] = $value;
    }

    protected function load()
    {
            try {
                $this->config = require $this->file;
            }catch (\Exception $e){
                throw new ConfigFileNotFoundException();
            }
    }

}

I got this file to config class :

return [
    'db'=> [
        'host' => 'localhost',
        'name' => 'name',
        'user' => 'user',
        'pass' => 'pass'
    ]
];

then I can use this with :

$config->get('db.user')
\$\endgroup\$
  • 1
    \$\begingroup\$ y o ur wh i tes p a c e i s o u t o f cont r o l... format that shit \$\endgroup\$ – I wrestled a bear once. Aug 2 '17 at 14:51
  • \$\begingroup\$ @Iwrestledabearonce. hahah made my day :D \$\endgroup\$ – DaAmidza Aug 4 '17 at 8:14
  • \$\begingroup\$ You should check out symfony yaml, basically you could setup a nice configuration from it.It would look clean, personally i use it. \$\endgroup\$ – DaAmidza Aug 4 '17 at 8:15

Your Answer

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

Browse other questions tagged or ask your own question.