Welcome Guest, Not a member yet? Register   Sign In
Load custom settings from database in all pages
#1

[eluser]Unknown[/eluser]
I'm trying to figure out how to do this but I'm not sure..

I want to save custom settings in the database which have to load on each page.

Current database structure:
Code:
Settings
-> id
-> name
-> value

For example:
Code:
Settings
-> 1
-> site_name
-> My swiss white shepherd dog

How can I load all the entries from this table into memory so that it can be accessed on every page?
Is it possible with a hook? And which code can I use to make the array (I think it has to be in an array?) accessible from every page?

Thank you in advance.
#2

[eluser]CroNiX[/eluser]
Lots of ways really. You could create a library with the __contsruct accessing it from the db and just autoload it. You could also create a MY_Controller and have your other controllers extend MY_Controller. Same thing, the __construct would access the db, so it would be available to all controllers.
#3

[eluser]CroNiX[/eluser]
An example of a library, which you would want to autoload to be available everywhere:

/application/libraries/site_config.php
Code:
class Site_config {
  public function __construct()
  {
    //get CI instance
    $CI =& get_instance();

    //This would normally be a model, but just to show...

    //Create new CI "site_config" property and assign data from db to it
    $CI->site_config = $CI->db->select('id, name, value')->get('your_table')->result_array();
  }
}

Now in all of your other controllers, models, etc, $this->site_config will contain the array of data from the db
#4

[eluser]ivantcholakov[/eluser]
From other project I've explored, indeed I see they tend to create a special library "Settings".

Here is a sample solution: https://github.com/ericbarnes/ci-settings. I did not use this original source, but it was a good starting point for me.

I don't need setting grouping, so I did something simplified: https://github.com/ivantcholakov/starter...ttings.php. I also added a data type guessing feature, it could be removed. If you like this library, you only have to rewrite the lines for database access, because I used a custom base class for models.
#5

[eluser]ivantcholakov[/eluser]
I also have a version that supports internationalization, but it is platform specific: https://github.com/ivantcholakov/starter...ttings.php.

For example, you may have settings within the database like 'site_name_en', 'site_name_fr', 'site_name_bg', ... You can get them this way:

Code:
$site_name = $this->settings->lang('site_name'); // Gets the value for the current language, let it be 'english'.
$site_name = $this->settings->lang('site_name', 'french'); // Gets the value for the specified language.




Theme © iAndrew 2016 - Forum software by © MyBB