Class::DBI::Relationship::HasVariant - columns with varying types
version 0.02
$Id: HasVariant.pm,v 1.3 2004/10/12 16:53:07 rjbs Exp $
Using a class to transform values:
package Music::Track::Attribute; use base qw(Music::DBI); Music::Track::Attribute->add_relationship_type( has_variant => 'Class::DBI::Relationship::HasVariant' ); Music::Track::Attribute->table("trackattributes"); Music::Track::Attribute->has_variant( attr_value => 'Music::Track::Attribute::Transformer', inflate => 'inflate', deflate => 'deflate' );
Using subs (this is a wildly contrived example):
Boolean::Stored->has_variant( boolean => undef, deflate => sub { return undef if ($_[0] and $_[0] == 0); return 1 if $_[0]; return 0; } );
The has_a relationship in Class::DBI works like this:
has_a
__PACKAGE__->has_a($columnname => $class, %options);
The column is inflated into an instance of the named class, using methods from the options or default methods. The inflated value must be of class $class, or an exception is thrown.
$class
The has_variant relationship allows one column to inflate to different types. If a class is given, it is not used for type checking, but for finding a transformation method.
has_variant
__PACKAGE__->has_variant( variant => 'Variant::Auto', inflate => 'inflate', deflate => 'deflate' );
This example will pass the value of the "variant" column to Variant::Auto's <inflate> method before returning it, and to its <deflate> method before storing it.
<inflate
<deflate
__PACKAGE__->has_variant( variant => undef, inflate => sub { return ($_[0] % 2) ? Oddity->new($_[0]) : Normal->new($_[0]) } deflate => sub { $_[0]->isa('Oddity') ? $_[0]->value : $_[0]->number } );
The above example will inflate odd numbers to Oddity objects and other values to Normals. Oddities are deflated with the <value> methods, and others with the <number> method.
<value
<number
My understanding of the Class::DBI internals isn't beyond question, and I expect that I've done something foolish inside here. I've tried to compensate for my naivety with testing, but stupidy may have leaked through. Feedback is welcome.
Ricardo SIGNES <<rjbs@cpan.org>>
<rjbs@cpan.org
(C) 2004, Ricardo SIGNES, and released under the same terms as Perl itself.
To install Class::DBI::Relationship::HasVariant, copy and paste the appropriate command in to your terminal.
cpanm
cpanm Class::DBI::Relationship::HasVariant
CPAN shell
perl -MCPAN -e shell install Class::DBI::Relationship::HasVariant
For more information on module installation, please visit the detailed CPAN module installation guide.