Apostrophe 1.5: legacy documentation

Still using Apostrophe 1.5? Check out Apostrophe 2 for your future projects.

sf Doctrine Act As Key Value Store Plugin


What It's For

sfDoctrineActAsKeyValueStorePlugin is a Doctrine behavior that lets you store additional attribute values along with any Doctrine object without the need for a schema change.

GOOD EXAMPLE: "whoops, we need to store whether each user has clicked the 'close' button for each hint box. Do we really need a table and a relation for that?"

BAD EXAMPLE: "hey, let's use it to store the ages of our users! Oh, you want all the users over 40? Oops, I guess I have to loop over every user now..."

How To Use It

To add the behavior to a table in schema.yml:

    - KeyValueStore

(Hint: yes, you can modify existing table definitions from plugin tables in your project-level schema.yml, adding more behaviors...)

To store an attribute:

$item = new MyModelClass();
$item->aSet('saw_hint_box', true);

To retrieve an attribute:

$item = // query to fetch the item by some criteria
// Defaults are supported when getting attribute values
$item->aGet('saw_hint_box', false);

To retrieve all attributes at once:


To set all attributes at once:


Storing Data Structures and Large Data

Since this plugin uses serialize(), you can pass almost any PHP data structure when setting an attribute. With MySQL the key value store is a LONGBLOB column, so large data (up to 2GB) can theoretically be stored. However in practice you will want to keep the amount of data relatively small so that your objects load quickly. For truly huge data you ought to consider joining with another table that has a blob column only in those cases when you actually need it or looking at a file related to your object by its ID.

How It Works

sfDoctrineActAsKeyValueStorePlugin adds a BLOB column to your table and uses serialize() and unserialize() to store an associative array of keys and values.

Where To Get It

svn co http://svn.apostrophenow.org/plugins/sfDoctrineActAsKeyValueStorePlugin/trunk

Don't forget to add the plugin in your ProjectConfiguration class.


Also consider Ryan Weaver's  sfDoctrineSlotPlugin, which solves the problem in a different way, using a separate table for each "slot" and calls to add each slot as a runtime alternative to schema entries. It's another good solution with different advantages. While sfDoctrineActAsKeyValueStorePlugin efficiently stores all of your attributes in one column of the original table, saving time and memory especially when attributes are fairly small and/or frequently needed, sfDoctrineSlotPlugin allows you to query for users with a particular setting without looping over all users.

For More Information

Contact Tom Boutell at tom at punkave.com. If there is a lot of interest I'll make a Google Group.

Thanks to Dan Ordille, John Benson, Wes John-Alder and Geoff DiMasi for their contributions to this plugin.