I've just been introduced to Class::DBI. While I like it lots in general,
it seems like it's missing one obvious feature, but being new to the
module I think it's more likely I'm missing the point than Class::DBI is
missing a feature.

Here's the situation.

I set up two classes, like so:

    package Survey;

    use base 'My::DBI';
    use strict;

    __PACKAGE__->table('surveys');
    __PACKAGE__->columns(Primary => 'survey_id');
    __PACKAGE__->columns(All     => qw(title text));
    __PACKAGE__->has_many('questions', Survey::Question => 'survey_id');

    package Survey::Question;

    use base 'My::DBI';
    use strict;

    __PACKAGE__->table('questions');
    __PACKAGE__->columns(Primary => 'question_id');
    __PACKAGE__->columns(All     => qw(title text));

    (the My::DBI class has all the db connection details in it and is a
    subclass of Class::DBI, so I don't have to keep that in the
    sub-classes.  also, there's a class for answers as well but let's
    leave that out for clarity.)

So what I wanted to be able to do is this:

    my $survey = Survey->retrieve($survey_id);
    ## get question data from somewhere
    $survey->add_question(\%question_data);

where the 'add_question' method is created automagically in the same way
the 'questions' method is created by Class::DBI, rather than having to do
this:
    
    my $survey = Survey->retrieve($survey_id);
    ## get question data
    my $question = Survey::Question->create(\%question_data);
    $question->survey($survey);

which is, as far as I can tell, the only way to add a child object to a
parent object. (child being the 'hasa' end of the relationship and parent
being the 'has_many' end.) I don't like this because I have to hard-code
the name of the child class somewhere else besides the has_many
initialization statement, and that feels messy. It also just feels
backwards.

I've overridden 'has_many' with a version that does what I want, but my
question is, am I missing a trick? Is there a standard idiom for doing
things more or less the way I wanted to within the existing Class::DBI
framework?

michael






Reply via email to