Question

I would like to have a base class Vehicle and most of my system to just use ARRAYs of this type. With subtypes such as Car, Airplane etc. When calling a method such as canFly a Car would responsed false, while an Airplane would response true.

I'm planning to use a single DB table (will listen to other suggestions) with a subtype column indicating the actual subclass type and NULL values for the columns used by other sibling subclasses. How can I at DB query intercept the creation of Vehicle classes and rather given(subclasstype) create the appropriate subclass? (If this question is not clear I will attempt to clarify better Saturday night (about 28 hrs from now.))

Was it helpful?

Solution

What you looking for is called Dynamic Subclassing in DBIx::Class. In Rails/ActiveRecord they call it Single Table Inheritance (STI).

The page to which I've linked is in the DBIC Cookbook describes how to override inflate_result so that you can test your row's vehicle type, and then rebless it into the desired subclass.

OTHER TIPS

A conventional constructor looks like:

package MyObject;
sub new {
    my ($package, @args) = @_;
    my $self = { };
    ... use @args, initialize $self ...
    return bless $self, $package;    # or sometimes  bless $self,__PACKAGE__
}

It is the bless statement that assigns a "type" to the data structure in $self. Usually, the second argument to bless is the name of the current package. But this is Perl, so you don't always have to do things the usual way. Even in the constructor for MyObject, you don't have to pass MyObject to bless:

package MyObject;
sub new {
    my ($package, %args) = @_;
    my $self = { };
    ... use @args, initialize $self ...
    if ($args{"type"} == 1)    { $package = "MyObject::Foo"; }
    elsif ($args{"type"} == 2) { $package = "MyObject::Bar"; }
    elsif ($args{"type"} == 3) { ... }
    return bless $self, $package;
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top