Re: perl inheritance
by jandrew (Chaplain) on Mar 24, 2012 at 04:38 UTC
|
Moose is kind of a deep place to jump into, if you are new to OOP in perl, but the things you are asking for are fairly simple to do in the Moose framework.
In Moose there are separate ideas of a Class and a Role and objects created from these blocks can be joined either at the Class level or the instance level.
An example from the documentation for basic pre-instance mixing and method conflicts is found in the Moose::Role Manual
Update: The Moose is flying part I and II are the gentlest introductions that I know of. (by Randal L. Schwartz++)
| [reply] [Watch: Dir/Any] [d/l] [select] |
Re: perl inheritance
by JavaFan (Canon) on Mar 23, 2012 at 18:26 UTC
|
foreach my $method (... list of methods to override ...) {
eval <<"EOT";
sub $method {
my (\$self, \@args) = \@_;
my $result = \$self->SUPER::$method(\@args);
bless \$result, __PACKAGE__;
\$result;
}
EOT
}
| [reply] [Watch: Dir/Any] [d/l] |
|
| [reply] [Watch: Dir/Any] |
|
Would this be invoked in the constructor of the derived class?
Of course not! This is something you need to be done once, and on class level. So, you'd do it outside of any method. That way, it get executed when you use the module.
| [reply] [Watch: Dir/Any] [d/l] |
|
|
|
|
|
Re: perl inheritance
by chromatic (Archbishop) on Mar 23, 2012 at 20:38 UTC
|
If I derive from this class and I call one of these methods, I'm interested in getting back the derived class (not the base).
The best way to do this is to fix the superclass to return new objects of the correct class. How does it return new objects?
| [reply] [Watch: Dir/Any] |
|
sub new {
if (ref $class eq 'base') {
//return derived object built from base class object
}
//return derived object built from parameters
}
Would invoking this form of the derived class constructor through AUTOLOAD be considered bad practice? This is so that all base class methods do not have to be overridden?
| [reply] [Watch: Dir/Any] [d/l] |
|
Would you have the constructor take a base class object and convert it to the derived?
I'd get the class of the provided object, then call its constructor directly.
Something like the following...
No. You're overcomplicating this and confusing yourself. Please post the existing code that constructs a new object so we can all see what you're doing.
| [reply] [Watch: Dir/Any] |
|
|
|