Ricardo SIGNES 😄


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);

   has_variant =>


   attr_value => 'Music::Track::Attribute::Transformer',
   inflate => 'inflate',
   deflate => 'deflate'

Using subs (this is a wildly contrived example):

   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:

 __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.

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.


   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.

   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.


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>>

(C) 2004, Ricardo SIGNES, and released under the same terms as Perl itself.