Search code examples
phpkohana

Kohana edit config file dynamically


I would like to know if we can edit dynamically the config file.

Here is my example.

<?php
// config/system.php

return array(
    'data'=>"content",
    'data1' => "content2",
);

?>

I know that we can edit it by using the set() methode, but this methode doesn't edit the file.

example :

<?php

// get config file array
$config = Kohana::$config->load('system');

// set the new config .. but this function doesn't edit the file !
$config->set("data","MyContent");

?>

Any idea ?


Solution

  • Finally i did it myself, maybe this can help someone else too.

    1 - Create APPPATH.'config/Group.php' and put this script.

    <?php defined('SYSPATH') OR die('No direct script access.');
    
    // Save this file at APPPATH.'config/Group.php'
    
    // Extend the original Config_group
    class Config_Group extends Kohana_Config_Group {
    
        // This function allow us to save on the config file
        public function save()
        {
            $filename = APPPATH.'config'.DIRECTORY_SEPARATOR.$this->group_name().".php";
    
                    // test if the config file is writable or not.
            if (is_writable($filename))
            {
                            // save the array into the config file and return true/false
                return (file_put_contents($filename, "<?php defined('SYSPATH') or die('No direct script access.');".PHP_EOL
                                        ."return " . var_export($this->as_array(), true) . ";",LOCK_EX));
            }
    
            return FALSE;
        }
    }
    

    How to use :

    <?php
    
    // get config file array
    $config = Kohana::$config->load('system');
    
    // set the new config .. but this function doesn't edit the file !
    $config->set("data","MyContent");
    
    // Save the new file config.
    $config->save();
    
    ?>