add_to_ question
[prev]
[thread]
[next]
[Date index for 2004/09/09]
Consider this a cross between curiousity and using a sledge hammer in
a china shop. So forgive me for this is a ramble. :-)
For the sake of this email, let's assume we're talking about
Music::Artist and Music::CD from the SYNOPSIS pod. Let's also assume
that as a developer, I chose to use Class::DBI to make my life easier
[aka lazy], but that I want the consumer of my modules to use My API,
and not rely on the fact that the Class::DBI API may or may not always
be there underneath the covers.
For example, let's take the act of adding a CD to an Artist. I would
rather the consumer rely on my Music::Artist->add instead of
Music::Artist->add_to_cds()
No biggie, we can just create:
sub Music::Artist::add {
my ($self, $data) = @_;
return $self->add_to_cds($data);
}
Then I simply call:
my $artist = Music::Artist->create({ artistid => 1, name => 'U2' });
my $cd = $artist->add({
cdid => 1,
title => 'October',
year => 1980
});
Now, I would also like the consumer to be able to do something like
this (assuming a Music::CD object may be created/stored/passed aruond
elswhere and is used as more than just it's hash storage):
my $artist = Music::Artist->create({ artistid => 1, name => 'U2' });
$artist->add($cd);
where ref($cd) eq 'Music::CD', a CD object that has been created
elsewhere/earlier using:
my $cd = Music::CD->construct({
cdid => 1,
title => 'October',
year => 1980,
})
Obviously, this fails with:
"add_to_cds needs data" due to HasMany.pm line 82/83:
return $self->_croak("add_to_$accessor needs data")
unless ref $data eq "HASH";
Nothing surprising so far as I'm not passing a pure HASH. So, my
questions comes down to what is the lesser of a few evils.
I can copy my Music::CD's hash into a fresh hash, and send that along:
sub Music::Artist::add {
my ($self, $data) = @_;
if (ref $data eq 'Music::CD') {
my %hash = $data->{};
return $self->add_to_cds(\$%hash);
} else {
return $self->add_to_cds($data);
};
}
Or, there is another option. What if the add_to did the following instead?
return $self->_croak("add_to_$accessor needs data")
unless UNIVERSAL::isa($data, 'HASH');
What kinds of evils would ensue after that process? I'd file this
partly under DO What I Mean when add_to receives something other than
a hash.
The 3rd option is some ref/bless/reconsicrate magic that I yet don't
understand to make my $cd back into what add_to expects.
Thanks,
-=Chris
|
add_to_ question
Christopher Laco 13:55 on 09 Sep 2004
|