will.thoughts.pop
RSS icon Email icon Home icon
  • Getting ActiveRecord-like ‘created_at’ behaviour with Perl’s Class::DBI

    Posted on November 2nd, 2006 Will 1 comment

    I really like ActiveRecord and on a recent project I wanted to be able to create fields in my database called ‘created_at’ and have them automatically filled with the current date at time of insert just as ActiveRecord does. Unfortunatly I was forced to use Perl’s Class::DBI* so I came up a simple method of creating the same behaviour.

    First, create a parent class that all of your Class::DBI table classes will inherit from:

    package DB::DBI;
    use base 'Class::DBI';
    use POSIX qw(strftime);

    #Your connection string will vary:
    __PACKAGE__->connection('dbi:mysql:database=db_name;host=127.0.0.1',"username","password");

    # Automatically add timestamp to 'created_at' fields.
    __PACKAGE__->add_trigger(before_create => sub {
    my $self = shift;
    $self->can('created_at') and $self->set('created_at', strftime("%Y-%m-%d %H:%M:%S", localtime));
    });

    Now create a class for each of your tables inheriting from the parent class:

    package DB::MyTable;
    # Inherit from DB::DBI
    use base 'DB::DBI';

    __PACKAGE__->table('my_table');
    __PACKAGE__->columns(All => qw/id field1 field2 field3 created_at/);

    And now when you do a DB::MyTable->create({...}) your created_at field will be automatically populated with the current timestamp. Yay!

    * And no, I wasn’t allowed to use DBIx::Class.