<?php
define('ABSPATH', dirname(__FILE__)); //Absolute path to index
/*
* Method 1
* Dependency Injection
*/
class Config{
private $_config = NULL;
private $_filepath = NULL;
public function __construct($filepath){
$this->_filepath = $filepath;
$this->load();
}
private function load(){
if ($this->_config === NULL){
if (!file_exists($this->_filepath)){
throw new Exception('Configuration file not found');
}else{
$this->_config = parse_ini_file($this->_filepath);
}
}
}
public function get($key){
if ($this->_config === NULL){
throw new Exception('Configuration file is not loaded');
}
if (isset($this->_config[$key])){
return $this->_config[$key];
}else{
throw new Exception('Variable ' . $key . ' does not exist in configuration file');
}
}
}
function getLost($where, $why, $who){
//do smth
}
try{
$config = new Config(ABSPATH . '/app/config.ini');
getLost('here', 'because', $config->get('who'));
}catch(Exception $e){
echo $e->getMessage();
}
?>
<?php
/*
* Method 2
* Config is accessed via static class
*/
class Config{
private static $_config = NULL;
private static $_filepath = NULL;
public static function load($filepath){
if (self::$_config === NULL){
self::$_filepath = $filepath;
if (!file_exists(self::$_filepath)){
throw new Exception('Configuration file not found');
}else{
self::$_config = parse_ini_file(self::$_filepath);
}
}
}
public static function get($key){
if (self::$_config !== NULL){
throw new Exception('Configuration file is not loaded');
}
if (isset(self::$_config[$key])){
return self::$_config[$key];
}else{
throw new Exception('Variable ' . $key . ' does not exist in configuration file');
}
}
}
function getLost($where, $why){
$who = Config::get('who');
}
try{
Config::load(ABSPATH . '/app/config.ini');
getLost('here', 'because');
}catch(Exception $e){
echo $e->getMessage();
}
?>
<?php
/**
* Method 3
* Config variable needed is passed as function parameter
*/
$config = parse_ini_file(ABSPATH . '/app/config.ini');
function getLost($where, $why, $who){
//do smth
}
getLost('here', 'because', $config['who']);
?>
<?php
/*
* Mathod 4
* Config is accessed inside a function via global
*/
$config = parse_ini_file(ABSPATH . '/app/config.ini');
function getLost($where, $why){
global $config;
$who = $config['who'];
}
getLost('here', 'because');
?>
这些变体中的哪一个是最佳实践解决方案?如果没有,请提供您的变体。