[CDBI] Turning Class::DBI on its side

mreece at vinq.com mreece at vinq.com
Wed Jul 25 15:59:21 BST 2007


sounds doable..

consider two classes.  one, CDBI::Prefs, is the typical CDBI class.  the
other, DB::Prefs, wraps it with the behavior you want.

this is untested, but probably 98% there:

  package DB::Prefs;
  use CDBI::Prefs;

  BEGIN {
    foreach my $pref ( CDBI::Prefs->retrieve_all ) {
        my $name = $pref->name;
        *{ __PACKAGE__ . "::$name" } = sub {
            my $class = shift;
            my $attr  = shift;
            my $row   = CDBI::Prefs->search( { name => $attr } );
            if (@_) {
                my $value = shift;
                $row->value($value);
                return $row->update;
            } else {
                return $row->value;
            }
        }
    }
  }
  1;

what it does is reads all rows from your table, then creates a custom
accessor/mutator for each.

hope this is of some use, should you pursue this approach.
michael.

> Bit of a strange cry for help this (not written a module before so
> some of my terminology is probably off, sorry)
>
> I want to turn the Class::DBI objects on their side; I want to store
> some application configuration within a database table, i.e.
>
> 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");
>
> So, how I can set up the accessors to point to a row in the database
> rather than a column?  There should only be one row per name (so name
> could be a primary key rather than id).  I can see that I probably
> have to provide/create each accessor for each distinct item in the
> table (or do a generic AUTOLOAD one to search for the item and get
> the value) but how do I create the correct object to be returned to
> the caller?
>
> TIA
>
>    Duncs_______________________________________________
> ClassDBI mailing list
> ClassDBI at lists.digitalcraftsmen.net
> http://lists.digitalcraftsmen.net/mailman/listinfo/classdbi
>




More information about the ClassDBI mailing list