in reply to Moose + ORM

For those it may concern -- I have this now:
package Table; use Moose::Role; use Moose::Exporter; use DBI; Moose::Exporter->setup_import_methods( with_caller => ['parse_table'], also => 'Moose', ); sub parse_table { my $table = shift; my $dbh = DBI->connect( ... ); my $sth = $dbh->selectall_arrayref( "describe $table" ); # loop thru $sth and add Moose attributes }
And I can create a class that consumes it:
package MyTable; use Moose; with 'Table'; parse_table( 'my_table' );
This compiles. Now it seems all I need to do is what that comment says "loop thru $sth and add Moose attributes" ... but how does one add Moose attributes inside such a role?

Thanks again, you folks help make things like this turn into reusable CPAN modules. :)

Replies are listed 'Best First'.
Re^2: Moose + ORM
by stvn (Monsignor) on Jul 23, 2009 at 21:12 UTC

    This is not the right way to do this, a role should not export new sugar into the class. I think perhaps you want MooseX::Roles::Parameterized instead.

    -stvn

      And here is what it might look like ...

      package Table; use MooseX::Role::Parameterized; parameter table_name => ( isa => 'Str', required => 1, ); role { my $p = shift; my $table = $p->table_name; my $dbh = DBI->connect( ... ); my $sth = $dbh->selectall_arrayref( "describe $table" ); my @columns = ... do DBI magic here ... foreach my $col (@column) { has $col->{name} => ( is => 'rw', isa => $col->{type}, default => $col->{default}, ); } }; package MyTable; use Moose; with 'Table' => { table_name => 'my_table' };

      -stvn
        Thank you very much for this. I tinkered around with my code last night and realized that I should not be exporting like that. This is what I came up with: I wonder what kind of contracts I am breaking with any class that wants to use this ... but it seems to work. The trick is loading the data into the object after it has been defined.

        Question if you have the gumption ... how would you handle loading the data? How would you pass the unique identifier of the database table row to be loaded into your MooseX::Role::Parameterized solution? That's the trouble I seem to have now, and hence why I added the Table::Loader role.

        Thanks again!

        1. The issues of connecting to a database need to be resolved in a configurable flexible way
        2. "The future of DBIx::Class talk" covers that syntax (32 minutes in) Maybe you could contribute to that.
        3. Joins need to be solved?
        4. If you just want an easy access to one table, maybe Tie::DBI is enough?