Hindle
Hindle

Reputation: 163

Create CakePHP custom configuration

I am trying to store configuration settings for my app. The details to be stored should be available throughout the app and it should be possible to update them. Examples of the details include the link for the logo image and contact details.

I did start this by storing the details in the database, creating a model and controller. However, as the logo is on every page, this requires querying the database on every page load.

I have read about the Configure class, but I can't get it too work. Can anyone explain how I could use Configure to store these configuration variables in a file, read them and update them in the file. I have looked at the cook book and the API, but it is not very clear.

Upvotes: 1

Views: 1486

Answers (1)

Kevin Vandenborne
Kevin Vandenborne

Reputation: 1387

You can loop through your settings table in the app_controller's beforeFilter using a name as a way to write the settings.

Like this:

<?php 
    $settings = Cache::read('AppSettings');

    if(!$settings){
        $settings = $this->Settings->find('all');
        Cache::write('AppSettings', $settings);
    }

    foreach($settings as $setting){
        Configure::write('Settings.' . $setting['Setting']['name'], $setting['Setting']['value']);
    }
?>

So you'd have a database with fields id, name and value where name is what you use to get your configures and value is the value you expect from it.

A row with a field 'name' that has the value "sitename" and field 'value' with value "MySite"

Could be called with Configure::read('Settings.sitename'); and would return 'MySite'

Then in the settings model, you put Cache::delete('AppSettings'); in the afterSave method . This way, the cache is destroyed when a record is updated or added and the settings will be re-cached and reconfigured.

Upvotes: 3

Related Questions