Search code examples
phpcodeigniter

How to Conditionally Load Configuration Files Within CodeIgniter?


I need to create something similar to the following within my CodeIgniter project:

  • my_config.php
  • config_production.php
  • config_development.php

Now, my_config.php will be autoloaded. From there, if it is a production server, config_production.php will be loaded; else config_development.php will be loaded.

How should I go about executing this?

I've tried doing the following in my_config.php:

<?php
if(gethostbyaddr ("127.0.0.1") == 'hello.sabya'){
    $this->config->load('config_production');
} else {
    $this->config->load('config_development');
}
?>

It is not working as $this->config is not initialized. How can I achieve this?


Solution

  • Two options: You can try referencing the object with $CI instead of $this:

    $CI =& get_instance();    //do this only once in this file
    $CI->config->load();  
    $CI->whatever;
    

    ...which is the correct way to reference the CI object from the outside.

    Or secondly, you could switch configs from within your config.php file:

    <?php
    if(gethostbyaddr ("127.0.0.1") == 'hello.sabya'){
        $config['base_url'] = "http://dev.example.com/";
    } else {
        $config['base_url'] = "http://prod.example.com/";
    
    }
    ?>
    

    ...etc. Load all the differences between the two if/else blocks.