How to edit and save custom config files in Laravel?

 ̄綄美尐妖づ 提交于 2020-01-22 07:45:48

问题


I am creating simple web application in Laravel 4. I have backend for managing applications content. As a part of backend i want to have UI to manage applications settings. I want my configuration variables to be stored in file [FOLDER: /app/config/customconfig.php].

I was wondering if there's any possibility in Laravel how to have custom config file, which can be managed/updated thru backend UI?


回答1:


I did it like this ...

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



回答2:


You'll have to extend the Fileloader, but it's very simple:

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) . ';');
    }
}

Usage:

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

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

$l->save($conf, '', 'customconfig');



回答3:


Afiak there is no built-in functionality for manipulating config files. I see 2 options to achieve this:

  • You can store your custom config in your database and override the default config at runtime with Config::set('key', 'value'); But be aware that

Configuration values that are set at run-time are only set for the current request, and will not be carried over to subsequent requests. @see: http://laravel.com/docs/configuration

  • Since config files are simple php arrays, it's easy to read, manipulate and write them. So with a little custom code this should be done quickly.

In general I'd prefer the first option. Overriding config files can might cause some troubles when it comes to version control, deployment, automated testing, etc. But as always, this strongly depends on your project setup.




回答4:


Based upon @Batman answer with respect to current version (from 5.1 to 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);


来源:https://stackoverflow.com/questions/25711296/how-to-edit-and-save-custom-config-files-in-laravel

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!