开发者

Proper way to use a config file?

开发者 https://www.devze.com 2022-12-27 03:21 出处:网络
I just started using a PHP framework, Kohana (V2.3.4) and I am trying to set up a config file for each of my controllers.

I just started using a PHP framework, Kohana (V2.3.4) and I am trying to set up a config file for each of my controllers.

I never used a framework before, so obviously Kohana is new to me. I was wondering how I should set up my controllers to read my config file.

For example, I have an article controller and a config file for that controller. I have 3 ways of loading config settings

// config/article.php
$config = array(
    'display_limit'         => 25, // limit of articles to list
    'comment_display_limit' => 20, // limit of comments to list for each article
    // other things
);

Should I

A) Load everything into an array of settings

// set a config array
class article_controller extends controller{

    public $config = array();

    function __construct(){
        $this->config = Kohana::config('article');
    }       
}

B) Load and set each setting as its own property

// set each config as a property
class article_controller extends controller{

    public $display_limit;
    public $comment_display_limit;

    function __construct(){
        $config = Kohana::config('article');

        foreach ($config as $key => $value){
            $this->$key = $value;
        }
    }
}

C) Load each setting only when needed

// load config settings only when needed
class article_controller extends controller{

    function __construct(){}

    // list all articles
    function show_all(){
        $display_limit = Kohana::config('article.display_limit');
    }

    // list article, with all comments
    function show($id = 0)开发者_高级运维{
        $comment_display)limit = Kohana::config('article.comment_display_limit');
    }
}

Note: Kohana::config() returns an array of items.

Thanks


If you are reading a group of configuration items for a controller, store them in class member ($this->config), if you are reading a single configuration item; read it individually.


I think first method (A) should be fine, it has lesser code and serves the purpose fine.


If you have site wide stuff that you want access to from "anywhere", another way of doing it may be to put something like:

Kohana::$config->attach(new Kohana_Config_File('global'));

in bootstrap.php. Then create global.php in the application/config directory with something like:

return (array ('MyFirstVar' => 'Is One',
               'MySecondVar' => 'Is Two'));

And then when you need it from your code:

Kohana::config ('global.MyFirstVar');

But I suppose all of this comes down to where and how you want to use it.

0

精彩评论

暂无评论...
验证码 换一张
取 消