Welcome Guest, Not a member yet? Register   Sign In
Global Variables from database
#1

[eluser]nigelb[/eluser]
hi, new to CI but I have committed to build 3 commercial websites using it in the next 8 weeks.

Quick question... How could I write bunch of stuff from one database table (called options) into variables that I could access from any controller/view. Stuff like stylesheet, page titles, site name, site status (on/off) etc to allow some none techies control it.
#2

[eluser]Crafter[/eluser]
I'm tempted to say use PHP global variables, but this might not be best practice. That option is always there, provide you exercise restraint and take car not to overload memory with global variables.

Typically, in the MVC framework, your data will flow like this:
(request by controller) -> model -> controller -> view/library/,,/ -> (response to controller)

So ultimately, your controller should keep a copy of the config variables and pass it to views, libraries and so on as required.
#3

[eluser]tonanbarbarian[/eluser]
use the CI config class
It loads by default so you do not need to preload it
and you can not only read config options you can write them

Setting a Config Item

I would just build an array of values and then set them. Make sure the values are indexed by the keys of the data in the database I guess.
#4

[eluser]Rick Jolly[/eluser]
Just wanted to expand on what tonanbarbarian wrote. Setting/overwriting config variables is a good idea. Of course you'd want to do it in one place instead of in every controller. Maybe you could do it right in config.php, but I'd use inheritance and set the config variables in the constructor of your parent controller and have all controllers extend that common parent.
#5

[eluser]adamp1[/eluser]
I have the same exact thing on my site. I solved it by having a model which interacts with the options table, so if I want the site name I call

Code:
$this->settings->item('site_name');

To save sever calls it caches all settings. I don't like the adding it to a config class since it could overwrite a previous set config value.

But loading settings from a database seem to be a very wasteful use of DB queries. I think it would be best to store them in a config file and write all changes to the file. Then you could load it like a normal config file (with each setting having a special prefix name).

Then you could just have a helper file to save you having to remember the prefix,

Code:
get_setting('site_name')

would call something like

$this->config->item('settings_site_name');




Theme © iAndrew 2016 - Forum software by © MyBB