哪种最佳方法可以访问函数中的config? [英] Which is the best practice to access config inside a function?

查看:64
本文介绍了哪种最佳方法可以访问函数中的config?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

 <?php 
define('ABSPATH',dirname(__ FILE__)); //索引的绝对路径

/ *
*方法1
*依赖注入
* /
class Config {

private $ _config = NULL;
private $ _filepath = NULL;

公共功能__construct($ filepath){
$ this-> _filepath = $ filepath;
$ this-> load();
}

私有函数load(){
if($ this-> _config === NULL){
if(!file_exists($ this-> ; _filepath)){
抛出新异常('未找到配置文件');
} else {
$ this-> _config = parse_ini_file($ this-> _filepath);
}
}
}

public function get($ key){
if($ this-> _config === NULL){
抛出新的异常(未加载配置文件);
}
if(isset($ this-> _config [$ key])){
return $ this-> _config [$ key];
} else {
抛出新的异常( Variable。$ key。配置文件中不存在);
}
}
}

函数getLost($ where,$ why,$ who){
// do smth
}

try {
$ config = new Config(ABSPATH。'/app/config.ini');
getLost('这里','因为',$ config-> get('who'));
} catch(Exception $ e){
echo $ e-> getMessage();
}
?>






 < ;?php 
/ *
*方法2
*配置是通过静态类
* /

类Config {

private static $ _config = NULL;
private static $ _filepath = NULL;

公共静态函数load($ filepath){
if(self :: $ _ config === NULL){
self :: $ _ filepath = $ filepath;
if(!file_exists(self :: $ _ filepath)){
抛出新异常(未找到配置文件);
} else {
self :: $ _ config = parse_ini_file(self :: $ _ filepath);
}
}
}

公共静态函数get($ key){
if(self :: $ _ config!== NULL){
抛出新的异常(未加载配置文件);
}
if(isset(self :: $ _ config [$ key])){
return self :: $ _ config [$ key];
} else {
抛出新的异常( Variable。$ key。配置文件中不存在);
}
}
}

函数getLost($ where,$ why){
$ who = Config :: get(’who’);
}

try {
Config :: load(ABSPATH。//app/config.ini');
getLost(在这里,因为);
} catch(Exception $ e){
echo $ e-> getMessage();
}
?>






 < ;?php 
/ **
*方法3
*所需的配置变量作为函数参数
* /
$ config = parse_ini_file(ABSPATH。'/ app /config.ini');

函数getLost($ where,$ why,$ who){
// do smth
}

getLost('here','因为',$ config ['who']);
?>






 < ;?php 
/ *
* Mathod 4
*在函数内部通过全局
* /
$ config = config = parse_ini_file(ABSPATH。'/ app / config.ini');

函数getLost($ where,$ why){
global $ config;
$ who = $ config [’who’];
}

getLost(在这里,因为);
?>

以下哪种变体是最佳实践解决方案?如果没有,请提供您的变量。

解决方案

我会选择变量1(依赖注入)。



变体2使用静态方法,这些方法已经说过,只是 global 的另一种方式方法。我们都知道那是不好的吧?



Variant 3不是我最喜欢的,因为它不够面向对象;-),但是很严重:如果您(或使用代码的人)想要更改怎么办?配置文件的格式?



变体4: global ...



所以基本上我在其他选择上的问题是:可测试性,紧密耦合,全局。



所以是变体1。我还将为config类创建一个接口,以便稍后可以为您的配置内容添加其他类。例如。您(或其他人)想使用XML文件进行配置。



我要更改的另一件事是 private 东西。如果有人想扩展课程,他/她将无法通过这种方式访问​​变量。我的经验法则(不确定每个人是否都同意)只是在您希望人们可以使用它的情况下将东西私有(例如,它将在某个时候改变) 。使用 private 的危险是,人们会通过黑客绕过它来做自己想要的事情。



阅读更多内容关于 SOLID 并查看Google 干净的代码讨论了更多信息。


只是我的2美分。


<?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');
?>

Which of these variants is the best practice solution? If none, please provide your variant.

解决方案

I would go for variant 1 (dependency injection).

Variant 2 uses static methods which are as already stated just enother way of global methods. And we all know that is bad right? right?

Variant 3 isn't me favorite because it's not OOP enough ;-), but serious: what if you (or the person using your code) wants to change the format of the config file?

Variant 4: global...

So basically my issues with other options are: testability, tight coupling, global.

So variant 1 it is. I would also create an interface for the config class so you may add a different class for your config stuff at a later point. E.g. you (or someone else for that matter) wants to use XML files for config.

Another thing I would change is private stuff. If someone wants to extend the class he/she wouldn't have access to the variables this way. My rule of thumb (not sure if everybody agrees with this though) is only make stuff private if you want people to have access to it (e.g. it will change at some point). The danger of using private is that people will get around it by hacks to do what they want.

Read more about SOLID and see the Google clean code talks for more info.

Just my 2 cents.

这篇关于哪种最佳方法可以访问函数中的config?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆