Re: [CDBI] Turning Class::DBI on its side
Duncan Ferguson <duncan_j_ferguson-/[email protected]> Wed, 25 Jul 2007 15:50:52 +0100
| Newsgroups | gmane.comp.lang.perl.modules.class-dbi |
|---|---|
| Message-ID | <[email protected]> |
On 25 Jul 2007, at 15:34, Bill Moseley wrote:
> On Wed, Jul 25, 2007 at 02:32:42PM +0100, Duncan Ferguson wrote:
>
>> Table: prefs
>> +----+------------------+----------------------------+
>> | id | name | value |
>> +----+------------------+----------------------------+
>> | 0 | filename | /path/to/file.txt |
>> | 1 | item_enabled | 1 |
>> | 2 | task_name | something |
>> +----+------------------+----------------------------+
>
>
>>
>> so instead of doing
>>
>> my $row=DB::Prefs->search({ name => " filename}})->first;
>> print $row->value,$/;
>> $row->value("/new/path/to/file");
>>
>> I can do
>>
>> print DB::Prefs->filename,$/;
>>
>> or
>>
>> DB::Prefs->filename("/new/path/to/file");
>
> sub AUTOLOAD {}
Never having coded a module before i didn't appreciate how easy that
would be...
My module is now:
=====
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;
}
=====
and it all seems to work as expected :-)
Thanks for the ear, all. I'll see if i can stick this on the class-
dbi wiki and perlmonks (since those are the two places i searched but
came up blank on this)
Duncs