如何在Laravel中编辑和保存自定义配置文件?

sco*_*909 7 php configuration-files laravel laravel-4

我正在Laravel 4中创建简单的Web应用程序。我具有用于管理应用程序内容的后端。作为后端的一部分,我希望拥有UI来管理应用程序设置。我希望将配置变量存储在文件[文件夹:/app/config/customconfig.php ]中。

我想知道Laravel中是否有可能具有可通过后端UI进行管理/更新的自定义配置文件?

小智 6

我是这样做的...

config(['YOURKONFIG.YOURKEY' => 'NEW_VALUE']);
$fp = fopen(base_path() .'/config/YOURKONFIG.php' , 'w');
fwrite($fp, '<?php return ' . var_export(config('YOURKONFIG'), true) . ';');
fclose($fp);
Run Code Online (Sandbox Code Playgroud)


Ant*_*iro 5

您必须扩展Fileloader,但这很简单:

class FileLoader extends \Illuminate\Config\FileLoader
{
    public function save($items, $environment, $group, $namespace = null)
    {
        $path = $this->getPath($namespace);

        if (is_null($path))
        {
            return;
        }

        $file = (!$environment || ($environment == 'production'))
            ? "{$path}/{$group}.php"
            : "{$path}/{$environment}/{$group}.php";

        $this->files->put($file, '<?php return ' . var_export($items, true) . ';');
    }
}
Run Code Online (Sandbox Code Playgroud)

用法:

$l = new FileLoader(
    new Illuminate\Filesystem\Filesystem(), 
    base_path().'/config'
);

$conf = ['mykey' => 'thevalue'];

$l->save($conf, '', 'customconfig');
Run Code Online (Sandbox Code Playgroud)


Nic*_*aki 5

基于 @Batman 对当前版本(从 5.1 到 6.x)的回答:

config(['YOUR-CONFIG.YOUR_KEY' => 'NEW_VALUE']);
$text = '<?php return ' . var_export(config('YOUR-CONFIG'), true) . ';';
file_put_contents(config_path('YOUR-CONFIG.php'), $text);
Run Code Online (Sandbox Code Playgroud)


pas*_*der 2

Afiak 没有用于操作配置文件的内置功能。我看到有两个选择可以实现这一目标:

  • 您可以将自定义配置存储在数据库中,并在运行时覆盖默认配置,Config::set('key', 'value');但请注意

在运行时设置的配置值仅针对当前请求设置,不会延续到后续请求。@参见: http: //laravel.com/docs/configuration

  • 由于配置文件是简单的 php 数组,因此很容易读取、操作和写入它们。因此,通过一些自定义代码,这应该可以很快完成。

一般来说,我更喜欢第一个选项。在版本控制、部署、自动化测试等方面,覆盖配置文件可能会导致一些麻烦。但与往常一样,这在很大程度上取决于您的项目设置。