Re: has many problems (again)

[prev] [thread] [next] [Date index for 2005/07/07]

From: Shane McEwan
Subject: Re: has many problems (again)
Date: 00:20 on 07 Jul 2005
G'day Patrik!

You can do it with an AUTOLOAD method in your Item package. Assuming
you've defined your ItemsToContacts package like this:

package ItemsToContacts;
use base 'Foo';
__PACKAGE__->table('ItemsToContacts');
__PACKAGE__->columns(Primary => 'ITEMSTOCONTACTS_ID');
__PACKAGE__->columns(Essential => qw(ITEM_ID CONTACT_ID TYPE));
__PACKAGE__->has_a(ITEM_ID => 'Item');
__PACKAGE__->has_a(CONTACT_ID => 'Contact');

Then the Item package would look like this:

package Item;
use base 'Foo';
use Carp;
our $AUTOLOAD;

__PACKAGE__->table('Item');
__PACKAGE__->columns(Primary => 'ITEM_ID');
__PACKAGE__->columns(Essential => 'ITEM_INFO');

sub AUTOLOAD {
  my $self = shift;
  my $class = ref($self) or croak "$self is not an object";

  my $name = $AUTOLOAD;
  $name =~ s/.*://;

  return (ItemsToContacts->search(ITEM_ID => $self, TYPE =>
$name))[0]->CONTACT_ID;
}

Of course, for proof on concept I'm only returning the FIRST contact
that matches. If you need to handle more than one match you'll need to
return an array of Contact objects or the iterator from the search.

Hope this helps!

On Wed, 2005-07-06 at 16:51 +0200, Patrik Wallstrom wrote:
> Hi!
> 
> I am building an application where I have Items and Contacts like
> this:
> 
> package Item;
> __PACKAGE__->columns(Primary => 'ITEM_ID');
> __PACKAGE__->columns(Essential => 'ITEM_INFO');
> 
> package Contact;
> __PACKAGE__->columns(Primary => CONTACT_ID');
> __PACKAGE__->columns(Essential => CONTACT_INFO');
> 
> I also have a table that looks like this:
> 
> ItemsToContacts:
> ITEMSTOCONTACTS_ID
> ITEM_ID
> CONTACT_ID
> TYPE
> 
> where TYPE can be one of "billing", "tech" and "admin".
> 
> What I would like to be able to do is something like this:
> $item->billing->contact_info and
> $item->tech->contact_info
> 
> Do I make things too complicated for myself?
> How would I solve this?
> 
        -- 
        Shane McEwan AKA Line Noise @ Virtual Doughnutland & EyeScabs
http://www.virtualdoughnutland.com/ - TV, Movie and DVD chat.
http://www.eyescabs.com/showUser.html?User=2 - My DVD collection.

***** WARNING ***** This E-Mail and any attachments may be confidential.
If received in error please delete all copies, format your hard disk and
wash your eyes in soapy water.

** VIRUS WARNING ** This E-Mail message has been scanned for outgoing viruses
however if you do manage to catch a virus from this message then you're an
idiot for opening attachments sent to you in an E-Mail message. What were you
thinking?!?!?!?!?!

has many problems (again)
Patrik Wallstrom 14:51 on 06 Jul 2005

Re: has many problems (again)
Shane McEwan 00:20 on 07 Jul 2005

Generated at 16:35 on 28 Jul 2005 by mariachi v0.52