usable in any place a human can be used

20101029

Auto-timestamps in Flourish

This will be a short post, I just wanted to share a protip for anyone using Flourish and in particular using the fActiveRecord ORM. fActiveRecord is pretty awesome, with it and fRecordSet I find myself very rarely having to drop down to raw SQL, although for some reports it can't be avoided and then fORMDatabase::retrieve()->query() is your friend. Anyways one of the really cool features about fActiveRecord is that it has a plug in module based off of hooks and I wanted to pass along something that I've started doing as a convention that's worked out really well for me.


I like all of my model classes to have a created_at and an updated_at timestamp that automatically do the correct thing to provide a very basic audit trail. This does not let you off the hook for doing actual auditing, but it is a nice way to do sanity checks and get some instant information about records. fActiveRecord makes this pretty easy to do, let's dive into some code.


[php]
class someModel extends fActiveRecord {
/**
* The fActiveRecord class provides the configure function to let you set-up Active Record hooks. Let's do that now
*/
protected function configure() {
fORMDate::configureDateCreatedColumn($this, 'created_at');
fORMDate::configureDateUpdatedColumn($this, 'updated_at');
}
}
[/php]

Easy as that you now have your created_ats and updated_ats working great for the someModel class. Here's the cool part though, because boilerplate code is stupid ugly code, if you want to use this across your project simply do the following.
[php]
class ActiveRecord extends fActiveRecord {
/**
* For this project every model should record created_at and updated_at
*/
protected function configure() {
fORMDate::configureDateCreatedColumn($this, 'created_at');
fORMDate::configureDateUpdatedColumn($this, 'updated_at');
}
}
[/php]

Now when you need to create a new model simply extend ActiveRecord instead of fActiveRecord and auto timestamps are done.

No comments:

Post a Comment