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,$/; $row->value("/new/path/to/file");
you want to set up accessors to point to the row in the database rather than the column:
print DB::Prefs->filename,$/; DB::Prefs->filename("/new/path/to/file");
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__->table("preferences"); __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" }); } $row->value($newval); $row->update(); } 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

In reply to Class::DBI keys as accessors by duncs

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.