Home > Software engineering >  Codeigniter 4 /CI4/ Using database to keep site configurations/ How to make key and value accessible
Codeigniter 4 /CI4/ Using database to keep site configurations/ How to make key and value accessible

Time:12-28

I have a database that holds several basis configuration settings for my site. The idea is to pull the values from the database and then make the values accessible globally. I also would like to implement $this->cachePage(DAY); to make sure the site is not constantly asking for configurations settings.

This is mysql table app_setting table

I have put the following code into public function initController method of the BaseController:

    $global_app_settings = array();
    
    $this->AppSettingModel        = new \App\Models\AppSettingModel;    
    
    $app_settings = $this->AppSettingModel->getAppSettings();
    
    foreach ($app_settings as $row) {
        $global_app_settings[$row->app_setting_key] = $row->app_setting_value;
    }

The above code works fine. If I print to screen, it produces the following;

Array
(
[dh_company_name] => A Big Company
[dh_phone_number] =>  81-3-5555-5555
[dh_fax_number] =>  81-3-5555-5556
)

My questions are as follows;

  • how can I make the array viable globally in my app?
  • Where can I add this? $this->cachePage(DAY);

CodePudding user response:

Define a protected variable in BaseController class and set it in initController

Put this in your controller

public function __construct()
{
    this->cachePage(15);
}

CodePudding user response:

It's simple actually.

public function loadGlobalSettings()
{
    $globalSettings = cache('global_settings');

    if (null === $globalSettings) {
        $appSettingModel = model('\App\Models\AppSettingModel');
        
        $app_settings = $appSettingModel->getAppSettings();
        $globalSettings = [];
    
        foreach ($app_settings as $row) {
            $globalSettings[$row->app_setting_key] = $row->app_setting_value;
        }
        
        cache()->save('global_settings', $globalSettings, DAY*15);
    }

    return $globalSettings;
}

How it runs:

  1. Try to get from cache.
  2. If cache not exists (returned null), load model, get settings, then cache it.
  3. Return settings array.

Have fun!

  • Related