Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations SkipVought on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Creating a wrapper module (multiple inheritance)

Status
Not open for further replies.

Zhris

Programmer
Aug 5, 2008
254
0
0
GB
Hello,

I have an issue which I would like an expert advise on.

I am "using existing" & "creating custom" Facebook modules, then wrapping them in a single module. The main issue is I don't want to create a bunch of accessor methods, I want to be able to call methods directly from the parent object (or not ?). The other issue is every module has its own constructor class. I have looked into multiple inheritance, but unable to find information regarding my specific requirements.

The only solution I have come up with is:
- Setup the objects I need in an init method in the wrapper module. Push them by priority into a list of objects.
- Use the AUTOLOAD method to loop through each object in the object list if the method cannot be found, testing whether the method can be successfully called using eval.

Does my solution seem feasible? I have produced an example below.

Thanks very much,

Chris

Code:
#! /usr/bin/perl
use strict;
use warnings;

{
	package Foo;

	sub new
	{
		my ($class) = @_;
		my $self = { };
		bless $self, $class;
		return $self;
	}

	sub foo
	{
		return "Foo...\n";
	}
}

{
	package Bar;

	sub new
	{
		my ($class) = @_;
		my $self = { };
		bless $self, $class;
		return $self;
	}

	sub bar
	{
		return "Bar...\n";
	}
}

{
	package FooBar;

	sub AUTOLOAD
	{
		my ($self, @args) = @_;

		my $return = undef;

		our $AUTOLOAD;
		my ($method) = $AUTOLOAD =~ m/::(.+)$/;
		return if ($method =~ m/DESTROY/); # Return if DESTROY method.

		foreach my $object (@{$self->{objects}})
		{
			eval { $return = $object->$method(@args); };
			last unless ($@);
		}

		return $return;
	}

	sub new
	{
		my ($class) = @_;
		my $self = { };
		bless $self, $class;
		$self->init();
		return $self;
	}

	sub init
	{
		my ($self) = @_;

		my $foo = Foo->new();
		my $bar = Bar->new();

		$self->{objects} = [$foo, $bar];
	}

	sub foobar
	{
		return "FooBar...\n";
	}
}

my $foobar = FooBar->new();
print $foobar->foobar();
print $foobar->bar();
print $foobar->foo();
 
Hello,

I've figured that a better way to call child methods would be to create object accessor methods in the parent class, i.e. :

Code:
sub foo_object
{
	return $_[0]->{objects}->[0]; # better if objects stored in hash ref.
}

sub bar_object
{
	return $_[0]->{objects}->[1]; # better if objects stored in hash ref.
}

Code:
print $foobar->bar_object->bar();
print $foobar->foo_object->foo();

This removes use of a clunky AUTOLOAD method.

Chris
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top