thinkphp5.1不支持extra,thinkphp5.1中config函数已经取消了extra的支持;可以将“function editConfig($arr = [] ,$user='admin'){...}”代码贴入app或者application文件夹内的common.php中即可全局使用该函数。

本教程操作环境:Windows7系统、ThinkPHP5版、Dell G3电脑。
thinkphp5.1是否支持extra?
不支持。
ThinkPHP5.1 使用文件作为配置文件
ThinkPHP5.1 使用文件作为配置文件的踩坑记录
使用Tp5.1(版本限定)作为App后台的时候,用户频繁的请求,每一步操作都要访问数据库,每一步操作都要访问到 config 配置表,频繁的读取使数据库压力山大,在后台监控流量,发现将近30%的请求都是在访问config表,所以决定将配置固话到本地,使用文件作为配置.
但是查询多方资料,未能找到可以静态修改配置,Tp5.1提供的Config::set()函数只能动态的修改配置文件,而且仅限于本控制器内,实际配置文件并没有改变,这显然不符合我们的要求.
经查询多方资料后,发现这篇最为靠谱,但是实测无效,
进入config函数后,发现Tp5.1中,config函数已经取消了extra的支持,于是乎自己动手改写了一下
不多说,直接暴力上 代码.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 |
function editConfig( $arr = [] , $user ='admin')
{
if ( is_array ( $arr )) {
$filename = 'business.php';
$filepath = Env::get('CONFIG_PATH'). $filename ;
if (! file_exists ( $filepath ) ) {
if (! fopen ( $filepath , "w" )){
return 'PermissionError1';
}
}
if (! is_writable ( $filepath )) {
return 'PermissionError2';
}
$conf = include $filepath ;
foreach ( $arr as $key => $value ) {
$conf [ $key ] = $value ;
}
$time = date ('Y/m/d H:i:s');
$str = "<?php\r\n/**\r\n * 由" . $user . "修改.\r\n * $time\r\n */\r\nreturn [\r\n" ;
foreach ( $conf as $key => $value ) {
if ( is_array ( $value )){
$str .= "\t'$key'=>[\r\n" ;
foreach ( $value as $ikey => $r ) {
if ( is_numeric ( $ikey )){
$str .= "\t\t'$r'," ;
$str .= "\r\n" ;
} else {
$str .= "\t\t'$ikey' => '$r'," ;
$str .= "\r\n" ;
}
}
$str = rtrim( $str ,',');
$str .= "\t]," . "\r\n" ;
} else {
$str .= "\t'$key' => '$value'," ;
$str .= "\r\n" ;
}
}
$str .= '];';
$result = file_put_contents ( $filepath , $str );
if ( $result ){
return 'success';
} else {
return $result ;
}
} else {
return 'error';
}
}
|
Salin selepas log masuk
将本段代码贴入app(或者application)文件夹内的common.php中,即可全局使用该函数,进行修改配置文件.
范例:
在网站根目录的config文件夹中建立一个business.php文件(注意读写权限),
控制器中调用修改函数
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | public function setBusiness(){
$arr = array (
"WEB" => [
"web_status" =>'1',
1,3,4
],
);
$result =editConfig( $arr ,'admin123');
if ( $result =='success'){
echo ('修改成功');
} elseif ( $result =='error'){
echo ('修改失败');
}
elseif ( $result =='PermissionError'){
echo ('文件无权限,请联系管理员');
}
}
|
Salin selepas log masuk
config文件夹下的配置文件就会修改为
1 2 3 4 5 6 7 8 9 10 11 12 13 | <?php
return [
'WEB'=>[
'web_status' => '1',
'1',
'3',
'4',
],
];
|
Salin selepas log masuk
接下来,在其他控制器中,就可以直接使用config的法则来获取各种配置文件了,具体规则,请移步TP5.1手册配置获取章节.
逻辑程序直接从文件读取配置,用户读取配置,可以设置缓存或者直接从redis里读取.
推荐学习:《thinkPHP视频教程》
Atas ialah kandungan terperinci Adakah thinkphp5.1 menyokong tambahan?. Untuk maklumat lanjut, sila ikut artikel berkaitan lain di laman web China PHP!