Beefy Boxes and Bandwidth Generously Provided by pair Networks
P is for Practical

Class::DBI keys as accessors

by duncs (Beadle)
on Jul 25, 2007 at 15:14 UTC ( #628701=sourcecode: print w/replies, xml ) Need Help??
Category: Database Programming
Author/Contact Info
Description: When using Class::DBI with a table such as:
Table: preferences +----+------------------+----------------------------+ | id | name | value | +----+------------------+----------------------------+ | 0 | filename | /path/to/file.txt | | 1 | item_enabled | 1 | | 2 | task_name | something | +----+------------------+----------------------------+
you want to use:
print DB::Prefs->filename,$/; DB::Prefs->filename("/new/path/to/file");
instead of:
my $row=DB::Prefs->search({ name => "filename" })->first; print $row->value,$/; $row->value("/new/path/to/file");
Say you want to store configuration data in a database, such as:
Table: preferences
  | id | name             | value                      |
  |  0 | filename         | /path/to/file.txt          |
  |  1 | item_enabled     | 1                          |
  |  2 | task_name        | something                  |
but instead of doing:
  my $row=DB::Prefs->search({ name => "filename" })->first;
  print $row->value,$/;
you want to set up accessors to point to the row in the database rather than the column:
  print DB::Prefs->filename,$/;
which is much easier to use and looks cleaner. All you have to do is create your Prefs class with an AUTOLOAD function, as below:
  package App::Prefs;
  use base 'App';
  use strict;
  __PACKAGE__->columns( ALL => qw/ id name value/ );
  sub AUTOLOAD {
    my $self = shift;
    my $newval = shift;
    my $attr = our $AUTOLOAD;
    $attr =~ s/.*:://;
    return if($attr eq "DESTROY");
    my $row = $self->search({ name => "$attr" })->first();
    if(defined($newval)) {
      if(!$row) {
        $row=$self->insert({ name => "$attr" });
    return defined($row) ? $row->value : undef;
So calling an accessor with no matching "name" in the preferences table will return "undef", calling an accessor with a parameter will insert that name/value pair into the table, and thereafter calling the accessor will return the correct value for the name matching the accessor

Log In?

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: sourcecode [id://628701]
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others contemplating the Monastery: (4)
As of 2023-12-08 22:46 GMT
Find Nodes?
    Voting Booth?
    What's your preferred 'use VERSION' for new CPAN modules in 2023?

    Results (37 votes). Check out past polls.