【问题标题】:CodeIgniter Setting config item that is in arrayCodeIgniter 设置数组中的配置项
【发布时间】:2011-07-14 00:49:28
【问题描述】:

所以我刚开始使用 CodeIgniter... 并且卡在设置配置项中

我已经读到替换配置项的值就像这样简单:

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

但是,如果我想设置一个配置项,它是一组配置项的一部分……比如这个:

$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;

我想动态替换 app_id。

【问题讨论】:

    标签: codeigniter


    【解决方案1】:

    当然可以,但您需要手动打开/重新包装配置项。例如,给定这个配置文件:

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

    还有这个控制器功能:

    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"));
      }
    

    你会得到这个输出:

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

    需要注意的一点:文件中的实际配置值没有更改:您需要对每个请求重新应用更改。

    【讨论】:

      【解决方案2】:

      不幸的是,你不能这样做,因为你现在有东西。

      看看有问题的代码:

      // 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);
      }
      

      如您所见,从配置文件中获取的唯一值是$config。 CI 几乎丢弃了其他所有东西。您应该无法通过配置访问该值以进行读取或写入。

      您的选择是您可以拥有一个 facebook 配置文件,您可以将 facebook 数组作为一个值存储在 api 配置文件中的 $config 变量中,或者您可以将该值存储为一些特殊键,例如 'facebook_app_id'同一个文件。您必须决定哪个选项最适合您的需求,但我倾向于将该值存储为“facebook_app_id”。

      【讨论】:

        【解决方案3】:
        $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');
        

        【讨论】:

        • 添加更多关于你在做什么的信息。
        猜你喜欢
        • 2013-03-28
        • 2012-02-27
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多