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
-
Are you posting in the right place? Check out Where do I post X? to know for sure.
-
Posts may use any of the Perl Monks Approved HTML tags. Currently these include the following:
<code> <a> <b> <big>
<blockquote> <br /> <dd>
<dl> <dt> <em> <font>
<h1> <h2> <h3> <h4>
<h5> <h6> <hr /> <i>
<li> <nbsp> <ol> <p>
<small> <strike> <strong>
<sub> <sup> <table>
<td> <th> <tr> <tt>
<u> <ul>
-
Snippets of code should be wrapped in
<code> tags not
<pre> tags. In fact, <pre>
tags should generally be avoided. If they must
be used, extreme care should be
taken to ensure that their contents do not
have long lines (<70 chars), in order to prevent
horizontal scrolling (and possible janitor
intervention).
-
Want more info? How to link
or How to display code and escape characters
are good places to start.