Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reading CodeIgniter config values from database instead of config file

As you might know, when you create a new project with CI you'll have to manually enter base url, encryption key in config/config.php. I'm trying to overcome this and is hence looking for a way to read those values from a database instead - making the installation for a customer and the set up time as a whole decrease a lot.

A customer isn't able to edit a PHP file's variables, but is most likely able to, with some guidance, enter base url and have a encryption key automatically filled in by the system.

Is there any way to accomplish this?

like image 793
Zar Avatar asked Feb 21 '23 10:02

Zar


2 Answers

Of course! Add a hook - post_controller and set these config values through that file.

config/hooks.php

$hook['pre_controller'][] = array(  'class'    => 'MyOtherClass',
                                    'function' => 'MyOtherfunction',
                                    'filename' => 'Myotherclass.php',
                                    'filepath' => 'hooks');

hooks/myotherclass.php

<?

class MyOtherClass {

    function MyOtherfunction() {

        $CI =& get_instance();

        $row = $CI->db->get_where('configs', array('site_id' => 1))->row();

        $CI->config->set_item('base_url', $row->base_url);

    }

}

Basicly you set these values before they're used in any controller or similiar.

like image 143
Robin Castlin Avatar answered Feb 22 '23 23:02

Robin Castlin


As far Codeigniter 3.1.7 pre_controller won't work because it will return NULL value while initializing $CI =& get_instance();

To solve this:

Change the hook point from pre_controller to post_controller_constructor

Modified source:

config/hooks.php

$hook['post_controller_constructor'][] = array(  'class'    => 'MyOtherClass',
                                'function' => 'MyOtherfunction',
                                'filename' => 'Myotherclass.php',
                                'filepath' => 'hooks');

and in hooks/myotherclass.php

<?

class MyOtherClass {

    function MyOtherfunction() {

        $CI =& get_instance();

        $row = $CI->db->get_where('configs', array('site_id' => 1))->row();

        $CI->config->set_item('base_url', $row->base_url);

    }

}

Now it will work!

like image 26
Anbuselvan Rocky Avatar answered Feb 22 '23 22:02

Anbuselvan Rocky