本章节讲解了如何加载其他位置的配置文件,因为配置文件不一定非要在应用目录下,也不一定非要在
config
目录下,也不一定非要是config.php
文件,也可以是任意的文件名。
其他位置的配置文件
首先,创建文件:/config/newconf/conf.php
,随便写些内容:
<?php
return [
'welcome' => '欢迎光临',
];
?>
如何加载呢?
在application
底下的默认控制器里的/application/index/controller/Index.php
文件中,加载其他地方的配置文件,需要用到Config
类的load
方法,因为Config
类在框架目录下面,需要用命名空间来访问它:
class Index
{
public function index()
{
\think\Config::load(APP_PATH.'../config/newconf/conf.php');
dump(\think\Config::get());
}
}
保存,刷新一下,就可以看到,对应配置项welcome
已经加载出来了。
下面我们再创建一个非PHP文件:/config/newconf/conf.ini
,随便写点配置:
target_site = 百度
target_domain = www.baidu.com
下一步,就是在/application/index/controller/Index.php
文件中,修改支持ini
格式的配置文件:
class Index
{
public function index()
{
// \think\Config::load(APP_PATH.'../config/newconf/conf.php');
\think\Config::parse(APP_PATH.'../config/newconf/conf.ini','ini');
dump(\think\Config::get());
}
}
保存,刷新一下,就可以看到,对应配置项target_site
,target_domain
已经加载出来了。
加载任意位置、非PHP格式的配置文件,不仅提高了灵活性,还为其他应用提供了一个配置接口。