CakePHP Archivable Behavior

Alright folks ... yeh I know I've been out of the picture really long and me blog is looking deserted for real now. Anyhow, I've got a bunch of posts in the pipeline. Thanks to Ahmed of SoccerLens for convincing me to start posting again :).

Enough chit chat ... so the cool thing I bring you here my friends is this Behavior I just baked up for a client. The Archivable Behavior. I love CakePHP's behavior architecture and had Mariano Iglesias's SoftDeletable behavior in mind before baking this baby.

What it does ?

It simply puts the record you want to delete in another table. I see no use bloating my existing table by adding a "deleted" field, especially when it would need to go through this process many times. Imagine, how big your table would get when you simply soft delete a record and it just sits there and is rarely used. I've seen this kind of methodology run into trouble when you are search the table. MySQL has to go through a lot of unwanted, deleted records and extract the active ones, it slows down the search process, especially when you are using UUIDs.

Usage:

This example follows for a Model, say, "MyPosts".


public $actsAs = array('Archivable'=>array('table'=>'my_posts_archives'));

If you don't specify a the table key, it will simply look for the table, 'my_posts_archived'. The schema for the archives table is simple. It's the same as the table my_posts but it has an additional field, my_post_id. You're going to have to create that table yourself. If you're like me and use PhPMyAdmin it should be really simple by going into Table -> Operations -> copy.

Once you're done with setting up the table and attaching the Archivable behavior with your model, anytime you execute the statement $this->MyPost->del($id); it will simply move the record from my_posts table to my_posts_archives table.
You can also use $this->MyPost->unarchive($id); to achieve reverse, i.e. remove the archived record from the archive table and move it back to the main table. As simple as that ! :P

Notes:

I've baked this on CakePHP 1.3.0.0 with PHP 5.2.4. Although this should run smooth on CakePHP 1.2.x too but if you are using PHP 5.3 you're gonna have to make some adjustments when objects are passed via reference in the code.

Download the Behavior

Have fun ya'all ;)

One Response to “CakePHP Archivable Behavior”


Leave a Reply