Stop ACTA

Simple DB based configuration for CakePHP apps

Posted in CakePHP on 21.03.2008.

A simple yet effective way to store your settings in the database and make them available everywhere.

In this article we will create a simple DB based configuration system which can be easily extended for a more complex environment. It is currently implemented in Neutrino and if you can read this article, it is working just fine.

The goal is to create a simple NAME => VALUE mapping for our variables. We also want to keep them in one place and available at any time throughout our Cake app.

First, we create our simple database table for storing the values:

CREATE TABLE `configuration`
(
    `id` int(11) NOT NULL auto_increment,
    `name` varchar(50) NOT NULL,
    `value` text NOT NULL,
    PRIMARY KEY  (`id`),
    UNIQUE KEY `name` (`name`)
) ENGINE=InnoDB;

All we need for our settings are name and of course the value. We also need to make sure that the name is unique. Also, we've made the value to be of type "text" to make it as flexible as possible.

Next, we create our kick ass model to use the table:

class Configuration extends AppModel
{
    var $name = 'Configuration';
    var $useTable = 'configuration';

    var $validate =
        array
        (
            'name' =>
                array
                (
                    'rule'      => VALID_NOT_EMPTY,
                    'message'   => 'FATAL: No variable name specified'
                )
        );

    function load()
    {
        $settings = $this->find('all');

        foreach ($settings as $variable)
        {
            Configure::write
                (
                    'Neutrino.'.$variable['Configuration']['name'],
                    $variable['Configuration']['value']
                );
        }
    }
}

As you can see, the load() function is the heart of this whole system. We load each individual variable and store it using the Configure class. This way, you have a DB based config and you get to keep all the benefits of using the Configure class.

To wrap it all up, just call the load method in your AppController:

class AppController extends Controller
{
    var $uses = array('Configuration');

    function beforeFilter()
    {
        if (isset($this->Configuration) && !empty($this->Configuration->table))
        {
            $this->Configuration->load();
        }
    }
}

Let's look at an usage example. Let's say you want to store some names in the database. You might have something like this:

id name value
1 theDog Brian Griffin
2 theMan Vic Mackey

You can use the value easily in your controller, view, or wherever you want:

$dog = Configure::read('Neutrino.theDog');
$man = Configure::read('Neutrino.theMan');

As you probably know, you can use Configure to get all the values by typing:

$settings = Configure::read('Neutrino');

Which ought to return an array of values:

Array
(
    [theDog] => Brian Griffin
    [theMan] => Vic Mackey
)

As you can see, this system eliminates the need for settings cache because there is only one query to the database. Your settings are available everywhere, and modifying and adding new variables is easy to implement. If you need per-user settings, you can add additional fields in the database (such as the obvious user_id), and extend the idea even further.

If you have any comments or suggestions, do let me know!

Happy baking!

Article comments — View · Add


Page 1 of 2
1 · 2

Hau.Nguyen :: 20.10.2008 04:12:43
I tryed but I can't.
There has an error:
Error: Database table configuration for model Configuration was not found.

(I created a table configuration)
lecterror :: 23.10.2008 06:00:09
Hi there.

If you're 100% sure that the table exists and you're connected to the proper database, try clearing your application cache; maybe Cake needs a bit of refreshment :-)

Let me know it it helps!
dane_62 :: 08.05.2009 22:25:45
this is a great tool, but as far as I understand it doesn't follow cake namming conventions tables should be plural "configurations' no 'configuration'.
lecterror :: 09.05.2009 17:08:38
Yes, that's true, I did that on purpose. "configurations" seemed silly because it is not a "configuration profile" storage, it is a "single configuration".

But it doesn't really affect anything, so you can always change it for your app ;-)
James Revillini :: 17.05.2010 08:27:33
Thanks for your tutorial. In the end, I ended up using a plugin just for the sake of having a modular architecture, but this is basically what the plugin does.

Here's the link to the plugin for configurations for CakePHP 1.2 & 1.3: http://www.webtechnick.com/blogs/view/223/CakePHP_Configuration_Plugin