开发者

CodeIgniter Setting config item that is in array

So I just started using CodeIgniter... and got stuck in setting config item

I have read that replacing the value of a config item is as easy as this:

$this->config->set_item('item_name', 'item_value');

But what if I want to set a config item that is part of an array of config items... like this one:

$api_config = $this->config->load('api'); //loading the created configuration under config folder

api.php

$facebook['app_id'] = '123213213';
$facebook['api_key'] = '123123WERWERWE123123';

$config['facebook'] = $facebook;

and I want to dynamically replace app_开发者_StackOverflow中文版id.


Sure you can do it, but you'll need to manually unwrap/rewrap the config item. For example, given this config file:

$f['a'] = "1";
$f['b'] = "2";

$config['t'] = $f;

And this controller function:

function t()
  {
    var_dump($this->config->item("t"));
    echo "<br>";
    $v = $this->config->item("t");
    $v['a'] = "3";
    $this->config->set_item('t', $v);
    var_dump($this->config->item("t"));
  }

You will get this output:

array(2) { ["a"]=> string(1) "1" ["b"]=> string(1) "2" }
array(2) { ["a"]=> string(1) "3" ["b"]=> string(1) "2" } 

One thing to note: the actual config value in the file hasn't changed: you will need to re-apply your change on each request.


Unfortunately, you can't do that as you have things right now.

A look at the code in question:

// from CI 2, CI 1 has no differences which will effect the current situation
include($file_path);

if ( ! isset($config) OR ! is_array($config))
{
    if ($fail_gracefully === TRUE)
    {
        return FALSE;
    }
    show_error('Your '.$file_path.' file does not appear to contain a valid configuration array.');
}

if ($use_sections === TRUE)
{
    if (isset($this->config[$file]))
    {
        $this->config[$file] = array_merge($this->config[$file], $config);
    }
    else
    {
        $this->config[$file] = $config;
    }
}
else
{
    $this->config = array_merge($this->config, $config);
}

As you can see, the only value which is picked up from the config file is $config. CI pretty much discards everything else. You should not be able to access that value through config for reading or writing.

Your options are that you can have a facebook config file, you can store the facebook array as a value in the $config variable in the api config file, or you can store the value as some special key like 'facebook_app_id' in the same file. You'll have to decide which option is best for your needs, but I would be inclined to store the value as 'facebook_app_id'.


$this->config->load('api', true);//load config first

//begin set new value

$this->config->set_item('app_Ckey',‘your new value’);
$this->config->set_item('app_id',‘your new value’);

$this->load->library('api');

echo $this->config->item('app_Ckey');
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜