Optionable Behavior / 03.19.2010
» Leia este post em português aqui.
The Optionable Behavior is a CakePHP behavior that tries to bring something from schemaless databases to RDBMS databases like MySQL. With it, you can add as much extra fields as you need to a table without touching the DB design / schema.
So, how do I use it?
Actually, we will store extra data on another table so, first of all, you need to create this auxiliary table:
CREATE TABLE IF NOT EXISTS `options` ( `id` int(11) NOT NULL auto_increment, `model` varchar(32) NOT NULL, `related_id` int(11) NOT NULL, `opt_key` varchar(32) NOT NULL, `opt_value` text NOT NULL, PRIMARY KEY (`id`), KEY `opt_key` (`opt_key`) );
If you can’t have a new table named ‘options’, don’t worry. Just name it something else. Now you need to create the model file for this table. Something like this should be enough:
class Option extends AppModel { }
If you are using a different table name, don’t forget to change the class name to whatever other name you have for it. Now you can download the behavior file here. Place it under your behaviors folder.
Now what?
Let’s pretend that you have a model named Blog which has three columns on it’s table: id, title and content. Generally, if I want to extend this table, I’ll have to deal with it’s schema, but using the Optionable Behavior, things get really easy. Imagine that I want to add my mood and the current weather to some posts on the blog. I just have to do something like this:
public $actsAs = array(
'Optionable' => array(
'model' => 'Option',
'fields' => array('mood', 'weather'),
'emptyFields' => true
)
);
Now I can just put those extra keys on a form, save some data and that is it. The data will be retrieved from the database just like if they were from the Blog’s schema itself.
See that we have three configuration keys to the behavior:
- model: defaults to ‘Option’. Just define this if you are using a different table name.
- fields: no default. Here you can define every optional field that you want to use in your model.
- emptyFields: defaults to true. If true, even if that option is not registered on the auxiliary table, the key will be present on the data array.
This behavior tries it’s best to make every optional field feels like a native one. This means that you can save, validate and retrieve optional data just like you would with common fields. We are working to make it possible to filter data by optional fields as well.
A great benefit of using this behavior is that you can store different data types on the DB seamlessly. Every data is serialized before getting saved to the table. That means that you can store arrays, objects and other data types not natively supported by RDBMSs without having any trouble converting them as they come and go.
Well, I guess this is it. If you have any idea on how to make this work any better, please, share with us! Here is the code: