views:

667

answers:

3

I am using CodeIgniter to write a application. I need to create something like this: - I will have: -

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

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

how should I do this?

I tried doing like this 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 because, the "$this->config" is not initialized yet.

How can I achieve this?

A: 

When do you need the config initialised by? - could you not define a hook to load up the correct configuration once everything else had been initialised but before the controller had executed?

Phill Sacre
+3  A: 

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 in between the two if/else blocks.

jmccartie
+1 exactly. I did something like that and it worked.
Sabya
A: 

I got it working like this: -

$ci = & get_instance();

if (gethostbyaddr ("127.0.0.1") == 'production.example.com') {
    //Load production configuration
    $ci->load->config('config_production');
} elseif(gethostbyaddr ("127.0.0.1") == 'staging.example.com') {
    //Load staging configuration
    $ci->load->config('config_staging');
} else {
    //Load development configuration
    $ci->load->config('config_development');
}
Sabya
Just out of "better practice", you should probably do something like: $host = gethostbyaddr ("127.0.0.1"); if( $host == 'production.example.com' ){That way you only need to call gethostbyaddr once.
Christopher W. Allen-Poole
+1. Yes, of course.
Sabya