http://www.perlmonks.org?node_id=11137346

LanX has asked for the wisdom of the Perl Monks concerning the following question:

Update: added a more intuitive example here


Lets say we have two classes Container and Element

and you can

my $cont = Container->new(); my $elem = Element->new('name'); $cont->add_elem($elem); # method chaining $cont1->get_elem('name')->do_something(); # identical to $elem1 = $cont1->get_elem('name'); $elem1->do_something(); # *

For this to work does $elem2 obviously need to know that it belongs to $container.

So it's N->1 : N Element -> 1 Container

and $elem1 == $elem

with updated property $elem->{member_of}=$cont Now after using this for a long time new requirements arise and Elements need to belong to multiple Containers.

So now it's N->M : N Element -> M Container

Clearly the old model with $elem2 == $elem doesn't work anymore because

$elem2 = $cont2->get_elem('name'); can't be member_of two different containers to allow method chaining

I don't think that $elem1 and $elem2 should belong to class Element either, but to a "wrapper" class ContainerElement referencing $elem, i.e. $elem1->{master}=$elem

Then I could think of many solutions, some involving inheritance, some AUTOLOAD to make sure that

$elem1->do_something(...) always does $elem1->{master}->do_something(..)

without hardcoding all methods.

I don't wanna reinvent the wheel and I'm already starting to worry too much about performance so here the question ...

What are the usual OO-Patterns to solve this? :)

Cheers Rolf
(addicted to the Perl Programming Language :)
Wikisyntax for the Monastery

update

*) OK Sorry, do_something() is doing something with the relation $cont <- $elem like set_weight($cont,$elem)