Dessert #13 - A simple Config Model

Posted by Felix Geisendörfer, on Sep 20, 2006 - in PHP & CakePHP » DataSources, Models & Behaviors

A lot of you probably like the idea of storing some of your applications configuration in a database since this way you can easily tweak things at run time versus having to edit configuration files on the server.

For me I found it pretty useful to just have a simple table called configs which contains two fields: "name" and "value". "name" is the primary key and it's type is varchar(255). The "value" fields type is text. After setting this up, I created a simple Model called Config and added two convenient little function named get & store to it which I can call from my controllers.

The code for the Config Model is this:

php
  1. class Config extends AppModel
  2. {
  3.     var $name = 'Config';    
  4.     var $primaryKey = 'name';
  5.     var $validate = array('name' => VALID_NOT_EMPTY);
  6.    
  7.     function get($name, $default = null)
  8.     {
  9.         $config = $this->findByName($name);
  10.         if (isset($config['Config']['value']))
  11.             return $config['Config']['value'];
  12.         else
  13.             return $default;
  14.     }
  15.    
  16.     function store($name, $value)
  17.     {
  18.         return $this->save(array('name' => $name, 'value' => $value));
  19.     }
  20. }

And usage is as simple as this:

php
  1. class AppController extends Controller
  2. {    
  3.     var $uses = array('Config');
  4.    
  5.     function beforeFilter()
  6.     {
  7.         $this->theme = $this->Config->get('theme', 'summer');
  8.     }
  9. }

So in the example above the beforeFilter tries to get the value of 'theme' out of the configs table and in case that fails (theme isn't set), it will return 'summer' as default value.

--Felix Geisendörfer aka the_undefined