首先需要在控制器內(nèi)引入Config類(lèi),這里使用5.1新增的facade,通過(guò)facade可以靜態(tài)的調(diào)用原本需要被繼承才能使用的方法。
獲取配置:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
|
namespace app\index\controller; use think\facade\Config; class index { public function index() { / / 獲取所有配置內(nèi)容,返回的是個(gè)Array dump(Config::get()); / / 獲取app中的配置內(nèi)容,返回的是個(gè)Array dump(Config::get( 'app.' )); / / 獲取app中的配置內(nèi)容,返回的是個(gè)Array dump(Config::pull( 'app' )); / / 獲取app中的debug中的配置內(nèi)容 dump(Config::get( 'app.app_debug' )); } } / / app是默認(rèn)的一級(jí)配置項(xiàng),app_debug是在app配置項(xiàng)下的,所以app.是可以省略的,但是 / / 像template. type 中的template.就不能省略,一旦省略了就變?yōu)榱四J(rèn)的app下的 type 了 |
獲取配置之前最好先判斷配置是否存在:
1
2
3
4
5
6
7
8
9
10
11
|
namespace app\index\controller; use think\facade\Config; class index { public function index() { //判斷template下的type項(xiàng)是否存在,返回true或者false dump(Config::has( 'template.type' )); } } |
動(dòng)態(tài)設(shè)置配置
1
2
3
4
5
6
7
8
|
namespace app\index\controller; use think\facade\Config; public function set() { dump(Config::get( 'app_debug' )); Config::set( 'app_debug' ,false); dump(Config::get( 'app_debug' )); } |
助手函數(shù)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
|
public function helper() { // 獲取配置 dump(config( 'database.hostname' )); // 用'?'判斷配置是否存在 dump(config( '?database.hostname' )); // 設(shè)置配置 config( 'database.hostname' , 'localhost' ); // 獲取配置 dump(config( 'database.hostname' )); // 還是推薦使用靜態(tài)類(lèi)Config::的方法來(lái)獲取或者設(shè)置配置 // 更容易被IDE支持 // 任何的助手函數(shù),都不依賴傳入的類(lèi),比如config助手函數(shù) // 不依賴Config類(lèi) } } |
到此這篇關(guān)于THINKPHP5.1 Config的配置與獲取詳解 的文章就介紹到這了,更多相關(guān)THINKPHP5.1 Config配置內(nèi)容請(qǐng)搜索服務(wù)器之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持服務(wù)器之家!
原文鏈接:https://blog.csdn.net/weixin_38468437/article/details/82052827