Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 585
Sabya Avatar asked Feb 21 '26 20:02

Sabya


2 Answers

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.

like image 198
jmccartie Avatar answered Feb 24 '26 09:02

jmccartie


As Eric mentioned use environments.

You may load different configuration files depending on the current environment.

To create an environment-specific configuration file, create or copy a configuration file in application/config/{ENVIRONMENT}/{FILENAME}.php

Note: CodeIgniter always tries to load the configuration files for the current environment first. If the file does not exist, the global config file (i.e., the one in application/config/) is loaded. This means you are not obligated to place all of your configuration files in an environment folder − only the files that change per environment.

Why implement logic, when it's already there? ;)

like image 26
Mickey Joe Avatar answered Feb 24 '26 09:02

Mickey Joe



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!