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.
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:
- Try to get from cache.
- If cache not exists (returned null), load model, get settings, then cache it.
- Return settings array.
Have fun!