環境變量
設置環境變量 /.env
[DATABASE]
USERNAME = root
PASSWORD = 123456
獲取環境變量 app/controller/Index.php
<?php
namespace app\controller;
use app\BaseController;
use think\facade\Env;
class Index extends BaseController
{
public function index()
{
$username = Env::get('database.username','root');
$password = Env::get('database.password');
$data = [
'username' => $username,
'password' => $password
];
return json_encode($data);
}
}
訪問測試
http://127.0.0.1:8000/index
{"username":"root","password":"123456"}
配置
配置設置 config/app.php
<?php
// +----------------------------------------------------------------------
// | 應用設置
// +----------------------------------------------------------------------
return [
// 應用地址
'app_host' => env('app.host', ''),
// 應用的命名空間
'app_namespace' => '',
// 是否啟用路由
'with_route' => true,
// 默認應用
'default_app' => 'index',
// 默認時區
'default_timezone' => 'Asia/Shanghai',
// 應用映射(自動多應用模式有效)
'app_map' => [],
// 域名綁定(自動多應用模式有效)
'domain_bind' => [],
// 禁止URL訪問的應用列表(自動多應用模式有效)
'deny_app_list' => [],
// 異常頁面的模板文件
'exception_tmpl' => app()->getThinkPath() . 'tpl/think_exception.tpl',
// 錯誤顯示信息,非調試模式有效
'error_message' => '頁面錯誤!請稍后再試~',
// 顯示錯誤信息
'show_error_msg' => false,
];
配置獲取
<?php
namespace app\controller;
use app\BaseController;
use think\facade\Config;
class Index extends BaseController
{
public function index()
{
$app = Config::get('app');
$timezone = Config::get('app.default_timezone');
$data = [
'app' => $app,
'timezone' => $timezone,
];
return json_encode($data);
}
}
訪問測試與結果
http://127.0.0.1:8000/index
{
"app": {
"app_host": "",
"app_namespace": "",
"with_route": true,
"default_app": "index",
"default_timezone": "Asia\/Shanghai",
"app_map": [],
"domain_bind": [],
"deny_app_list": [],
"exception_tmpl": "\/private\/var\/www\/tp\/vendor\/topthink\/framework\/src\/tpl\/think_exception.tpl",
"error_message": "\u9875\u9762\u9519\u8bef\uff01\u8bf7\u7a0d\u540e\u518d\u8bd5\uff5e",
"show_error_msg": false
},
"timezone": "Asia\/Shanghai"
}
新配置文件
添加配置文件 /config/test.php
<?php
return [
'name'=>'huyongjian'
];
獲取配置
<?php
namespace app\controller;
use app\BaseController;
use think\facade\Config;
class Index extends BaseController
{
public function index()
{
$test = Config::get('test');
$name = Config::get('test.name');
$data = [
'test' => $test,
'name' => $name,
];
return json_encode($data);
}
}
訪問測試與結果
http://127.0.0.1:8000/index
{"test":{"name":"huyongjian"},"name":"huyongjian"}
系統配置文件
配置文件名 描述
app.php 應用配置
cache.php 緩存配置
console.php 控制台配置
cookie.php Cookie配置
database.php 數據庫配置
filesystem.php 磁盤配置
lang.php 多語言配置
log.php 日志配置
middleware.php 中間件配置
route.php 路由和URL配置
session.php Session配置
trace.php 頁面Trace配置
view.php 視圖配置