in reply to object oriented Perl advice / constructor creation in child class
Well, your example doesn't actually show inheritance. Your constructor creates a "has-a" relationship, because your C1 objects will have one object of each of the classes A, B, C and D as attributes. This is a solid pattern in many cases, but it doesn't give you direct access to the methods of the four classes.
I'd say that today's perlish way to do OOP is Moose or its lightweight cousin Moo, and I definitely recommend those if you have several classes to inherit from. Here's a short example:
# A.pm package A; use 5.014; use Moo; sub say_hello { my $self = shift; my ($name) = @_; say "Hello, $name!"; } 1;
# C.pm package C; use 5.014; use Moo; has 'name' => (is => 'rw'); sub say_goodbye { my $self = shift; say 'Goodbye, ', $self->name, '!'; } 1;
Now you can do things like this:# C1.pm package C1; use 5.014; use strict; use warnings; use Moo; extends 'C'; use A; has '_a' => (is => 'ro', default => sub { A->new() }, handles => [qw(say_hello)] ); 1;
use strict; use warnings; use C1; my $c = C1->new(name => 'John Doe'); $c->say_hello('World'); $c->say_goodbye;
So, your C1 objects have direct access to both the say_hello method from A.pm, and the say_goodbye method from C.pm.
- Access to say_goodbye is done with inheritance, by the extends keyword of Moo. With inheritance you have access to all attributes and all methods of the parent class, so if you have more than one parent, you need to take care for possible conflicts.
- Access to say_hello is achieved with method delegation. In that case, the A object needs to be created and has its own attributes, and the package must be loaded. On the plus side, you have control which methods of A you want to expose through the public interface of C1, and there's no problem with conflicts. You can, of course, always call the methods of A indirectly with $c->_a->say_hello('World').
Note that Moo (and Moose) will take care for object constructors: You don't write new methods!
If you want to do object inheritance without an object framework, you do it like this:
However, in that case you need to take care for calling parent constructors and conflict resolution yourself, which is why I don't expand on this.package C1; use parent (qw(A B C D));
|
---|
Replies are listed 'Best First'. | |
---|---|
Re^2: object oriented Perl advice / constructor creation in child class
by smarthacker67 (Beadle) on Jul 11, 2018 at 06:16 UTC | |
by haj (Vicar) on Jul 11, 2018 at 09:43 UTC |