我刚开始使用PHP框架Kohana(V2.3.4),我正在尝试为每个控制器设置一个配置文件 .
我之前从未使用过框架,所以显然Kohana对我来说是新手 . 我想知道如何设置我的控制器来读取我的配置文件 .
例如,我有一个文章控制器和该控制器的配置文件 . 我有3种加载配置设置的方法
// 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
);
我是不是该
A)将所有内容加载到一组设置中
// set a config array
class article_controller extends controller{
public $config = array();
function __construct(){
$this->config = Kohana::config('article');
}
}
B)加载并将每个设置设置为自己的属性
// 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 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');
}
}
注意:Kohana :: config()返回一个项目数组 .
谢谢
3 回答
如果要读取控制器的一组配置项,如果要读取单个配置项,则将它们存储在类成员(
$this->config
)中;单独阅读 .我认为第一种方法(A)应该没问题,它的代码较少,并且目的很好 .
如果你想要从“任何地方”访问的网站范围的东西,另一种方法可能是这样做:
在bootstrap.php中 . 然后在application / config目录中创建global.php,例如:
然后当你需要代码时:
但我想所有这些都取决于你想要使用它的地方和方式 .