Advertisement
hookman

Procedural DI

Jul 17th, 2012
47
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 1.16 KB | None | 0 0
  1. <?php
  2. class Config{
  3.  
  4.     private $_config = NULL;
  5.     private $_filepath = NULL;
  6.  
  7.     public function __construct($filepath){
  8.         $this->_filepath = $filepath;
  9.         $this->load();
  10.     }
  11.  
  12.     private function load(){
  13.         if (is_array($this->_config))
  14.             return;
  15.         if (!file_exists($this->_filepath))
  16.             throw new Exception('Configuration file not found');
  17.         $this->_config = parse_ini_file($this->_filepath);
  18.     }
  19.  
  20.     public function get($key){
  21.         if ($this->_config === NULL)
  22.             throw new Exception('Configuration file is not loaded');
  23.         if (isset($this->_config[$key]))
  24.             return $this->_config[$key];
  25.         else
  26.             throw new Exception('Variable ' . $key . ' does not exist in configuration file');
  27.     }
  28. }
  29.  
  30. #config instantiation
  31. $config = new Config(ABSPATH . '/app/config.ini');
  32.  
  33. #Any function which uses config
  34. function dbconnect($DBhost, $DBuser, $DBpass, $DBname){
  35.     $db = mysqli_connect($DBhost, $DBuser, $DBpass, $DBname);
  36.     if (!$db)
  37.         throw new Exception('MySQL connection failed');
  38.     else
  39.         return $db;
  40. }
  41.  
  42. try{
  43.     dbconnect($config->get('DBhost'), $config->get('DBuser'), $config->get('DBpass'), $config->get('DBname'));
  44. }catch(Exception $e){
  45.     echo $e->getMessage();
  46. }
  47. ?>
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement