I'm trying to implement a Moose::Role class that behaves like an abstract class would in Java. I'd like to implement some methods in the Role, but then have the ability to override those methods in concrete classes. If I try this using the same style that works when I extend classes I get the error Cannot add an override method if a local method is already present. Here's an example:
My abstract class:
package AbstractClass;
use Moose::Role;
sub my_ac_sub {
my $self = shift;
print "In AbstractClass!\n";
return;
}
1;
My concrete class:
package Class;
use Moose;
with 'AbstractClass';
override 'my_ac_sub' => sub {
my $self = shift;
super;
print "In Class!\n";
return;
};
__PACKAGE__->meta->make_immutable;
1;
And then:
use Class;
my $class = Class->new;
$class->my_ac_sub;
Am I doing something wrong? Is what I'm trying to accomplish supposed to be done a different way? Is what I'm trying to do not supposed to be done at all?
Turns out I was using it incorrectly. I opened a ticket and was shown the correct way of doing this:
package Class;
use Moose;
with 'AbstractClass';
around 'my_ac_sub' => sub {
my $next = shift;
my $self = shift;
$self->$next();
print "In Class!\n";
return;
};
__PACKAGE__->meta->make_immutable;
1;
Making this change has the desired effect.
Some time ago, I did this by having a role that consists solely of requires statements. That forms the abstract base class. Then, you can put your default implementations in another class and inherit from that:
#!/usr/bin/env perl
use 5.014;
package AbstractClass;
use Moose::Role;
requires 'my_virtual_method_this';
requires 'my_virtual_method_that';
package DefaultImpl;
use Moose;
with 'AbstractClass';
sub my_virtual_method_this {
say 'this';
}
sub my_virtual_method_that {
say 'that'
}
package MyImpl;
use Moose;
extends 'DefaultImpl';
with 'AbstractClass';
override my_virtual_method_that => sub {
super;
say '... and the other';
};
package main;
my $x = MyImpl->new;
$x->my_virtual_method_this;
$x->my_virtual_method_that;
If you want to provide default implementations for only a few methods define in the role, remove the requires from DefaultImpl.
Output:
$ ./zpx.pl
this
that
... and the other
Related
Reworded question - sorry, it is a bit long.
Have a simplyfied package for example
package My;
use Moose;
use namespace::sweep;
sub cmd1 {1}
sub smd2 {2}
__PACKAGE__->meta->make_immutable;
1;
I want allow to others extending the My with another methods, such
package My::Cmd3;
use Moose;
extends 'My';
sub cmd3 {3}
1;
This allows to use the methods from the "base" My and My::Cmd3 with the next:
use My::Cmd3;
my $obj = My::Cmd3->new();
say $obj->cmd1(); #from the base My
say $obj->cmd3(); #from the My::Cmd3;
But this isn't what I want. I don't want use My::Cmd3;, (here will be more extension packages), I want use My;.
Using roles is NICER, like:
package My;
use Moose;
with 'My::Cmd3';
sub cmd1 {1}
sub cmd2 {2}
__PACKAGE__->meta->make_immutable;
1;
package My::Cmd3;
use Moose::Role;
use namespace::autoclean;
sub cmd3 {3};
no Moose::Role;
1;
This allows me:
use My;
my $obj = My->new();
say $obj->cmd1();
say $obj->cmd3(); #from the role-package
But when someone make an My::Cmd4 will need change the base My package to add with My::Cmd4. ;(
I'm looking for a way, how to achieve the next:
use My;
#and load all needed packages on demand with the interface like the next
my $obj = My->new( commands => [qw(Cmd3 Cmd4)] );
#what should load the methods from the "base" My and from the wanted extensions too
say $obj->cmd1(); # from the base My package
say $obj->cmd3(); # from the "extension" package My::Cmd3
say $obj->cmd4(); # from the My::Cmd4
So, the what I have now:
package My;
use Moose;
has 'commands' => (
is => 'rw',
isa => 'ArrayRef[Str]|Undef', #??
default => sub { undef },
);
# WHAT HERE?
# need something here, what loads the packages My::Names... based on the supplied "commands"
# probably the BUILD { ... } ???
sub cmd1 {1}
sub smd2 {2}
__PACKAGE__->meta->make_immutable;
1;
Designing an right object hierarchy is my everlasting problem.. ;(
I'm absolutely sure than this isn't should be an big problem, only need some pointers what I should study; and therefore Would be nice to know some CPAN modules, what using such technique ...
So the questions:
What I need to put in place of the above "WHAT HERE?"
The "extension" packages should be roles? (probably it is the best for this, but asking for sure)
Should i move the "base" commands from the My to the e.g. My::Base and load the on-demand as other My::Something or should they remain in the My? And why?
Some other recommendations?
To allow get a list of methods (and loaded packages), in Moose I can use
my $obj = My->new(....);
my #methods = $obj->meta->get_all_methods();
This has only Moose and I couldn't use something smaller as Moo, right?
Ps: Sorry again for the extremelly long question.
Here is a solution that fills in your WHAT HERE? section, with the extensions remaining as roles.
package My;
use Moose;
use Class::Load 'load_class';
has commands => (
is => 'ro',
isa => 'ArrayRef',
default => sub { [ ] },
);
sub BUILD {
my ($self) = #_;
my $namespace = __PACKAGE__;
foreach ( #{ $self->commands } ) {
my $role = "$namespace::$_";
load_class $role; # load the module
$role->meta->apply($self); # apply the role to the object
}
return;
}
...
Notes:
You will need to load your role during runtime. This is akin to require My::Role but the module deals with some issues with loading modules at runtime. Here I have used Class::Load, but a number of alternatives exist including Module::Load.
Then you need to apply the role to your object (see also this Moose Cookbook entry as a reference).
I recommend keeping methods cmd1 and cmd2 in this base class unless you have a reason for separating them out and loading them on demand also.
I use the BUILD method which in Moose is invoked automatically after construction.
I don't allow commands to be undef so I don't need to check for it - If there are no commands, then it can be left as an empty arrayref.
You could also use a module that gives you the infrastructure for applying the roles without you having to write it yourself. Here I have used MooseX::Traits, but again there are a number of alternatives listed here: https://metacpan.org/pod/Task::Moose#Traits-Roles
package My;
use Moose;
with 'MooseX::Traits';
has '+_trait_namespace' => ( default => 'My' );
sub cmd1 {1}
sub cmd2 {2}
__PACKAGE__->meta->make_immutable;
1;
# your roles remain unchanged
Then to use the class:
use My;
my $obj = My->with_traits(qw[ Cmd3 Cmd4 ])->new;
# or my $obj = My->new_with_traits( traits => [qw( Cmd3 Cmd4 )] );
say $obj->cmd1;
say $obj->cmd3;
say $obj->cmd4;
It is still possible to do something like this with Moo if you don't want to use Moose:
use Moo::Role ();
my $class = Moo::Role->create_class_with_roles( 'My2', 'My::Cmd3', 'My::Cmd4' );
my $obj = $class->new;
say $obj->cmd1;
say $obj->cmd3;
say $obj->cmd4;
First: Inheritance
Using Moo or Moose is a super-easy task:
package My::Sub3;
use Moo;
extends 'My';
sub cmd3 {3}
1;
Second: Dynamic object build. Define a build function and load at runtime the proper module. There are several ways to do this, I like the Module::Load CPAN module:
use Module::Load;
sub my_factory_builder {
my $class_name = shift;
load $class_name;
return $class_name->new(#_);
}
And then, in your code:
my #new_params = ();
my $object = my_factory_builder('My::Sub3', #new_params);
As described, "My" itself should be implemented as a role. With few exceptions, classes represent nouns. If the consumers of your class genuinely need to add behavior without subclassing, then your class probably isn't finished yet. For example:
package Animal;
use Moose;
sub eat { ... }
sub excrete { ... }
If the consumers of your code need a "procreate" method, then they should modify the Animal class itself rather than create another module for dynamic loading. If you don't want them modifying Animal, then the right thing for them to do is to subclass it in a new class, say, "FruitfulAnimal".
If your consumers want "eat" and "excrete" behaviors when they happen to be implementing an Animal class, it would be better for them to consume a role that provides those behaviors.
Here is an implementation of My as a Role:
package My;
use Moose::Role;
sub cmd1 { 1 }
sub cmd2 { 2 }
1;
Cmd3
package Cmd3;
use Moose::Role;
with 'My'; # consumes the behaviors of the 'My' Role
sub cmd3 { 3 }
1;
Cmd4
package Cmd4;
use Moose::Role;
with 'My'; # consumes the behaviors of the 'My' Role
sub cmd4 { 4 }
1;
How the role is consumed
package AnyClassThatConsumesMy;
use Moose;
# Instead of My->new( commands => [qw(Cmd3 Cmd4)] );
with 'My', 'Cmd3', 'Cmd4';
1;
test
#!/usr/bin/perl
use Modern::Perl;
use AnyClassThatConsumesMy;
my $my = AnyClassThatConsumesMy->new();
say $my->cmd1();
say $my->cmd2();
say $my->cmd3();
say $my->cmd4();
Output
1
2
3
4
The reason I suggest this approach is that your example is deeply concerned with behaviors rather than modeling something specific. You want to start with a set of behaviors and have others contribute new behaviors. This may seem counter-intuitive because Roles aren't typically emphasized in OO design texts. This is because so many OO languages don't have robust support for Role-like behavior. It doesn't have to be instantiate-able to be usable.
I could tell from the question, you need to use methods heirs
General package
package My;
sub new ($$) {
my $caller = shift;
my $commands = shift;
# blank
my $self = {};
# commands for implements
foreach my $cmd (#{$commands}) {
# implement support extend commands
require "My/".ucfirst($cmd).".pm";
push #ISA, "My::".ucfirst($cmd);
}
return bless $self, $caller;;
}
sub cmd1 {1};
sub cmd2 {2};
1;
My::Cmd3
package My::Cmd3;
sub cmd3 {ref shift};
1;
My::Cmd4
package My::Cmd4;
sub cmd4 {ref shift};
sub isCMd4 {print "it is cmd4"};
1;
test
#!/usr/bin/perl
use strict;
use warnings;
use utf8;
use v5.10;
use My;
my $my = My->new([qw(cmd3 cmd4)]);
say $my->cmd1();
say $my->cmd2();
say $my->cmd3();
say $my->cmd4();
say $my->isCMd4();
1;
Output
1
2
My
My
it is cmd41
Get a list of methods
for(keys %My::) {
say $_ if My->can($_);
}
I'm trying to create child classes in Perl that inherit class functions from a single parent. I got it to partially work, using the object method syntax Child->inheritedMethod() to call inherited functions outside the child, and my $class=shift; $class->inheritedMethod(); inside the child class, as described here.
However, for inherited methods, it seems control is passed to parent class, and the method is run in the parent scope with the parent variables. For example, this is in the Parent class:
our $VERSION = 0.11;
our $NICKNAME = "Parent Base";
sub version{ $VERSION }
sub whoami{ $NICKNAME }
sub whereami{
my $class = shift;
print "should be printing whereami right now...\n";
print "## In ",(caller(1))[3]," of ",$class->whoami," ",$class->version," in ",__PACKAGE__,"\n";
}
Each child class declares its own $VERSION and $NICKNAME, which I hoped would be accessed in place of the parent variables. But when I call whereami from the child, it gives
## Child::Method of Parent Base 0.11 in Parent.
Questions:
Is there a way around this? Some other module I should use like Moo(se)? Export all the methods instead of inheritance, which I hear shouldn't be done (polluting the namespace, not a problem here)?
Would this still be an issue using objects and object
attributes/variables? I'm trying to avoid it due to my team's
aversion to object-oriented.
Is this how inheritance usually works,
or just Perl? I thought the method would be called within the scope
of the child class, not passed to the parent.
The problem is that the method accesses the variable from the lexical scope where it was declared, i.e. the parent class. Class variables are therefore not the same thing as class attributes.
You can access the correct variable by fully qualifying its name (not possible under strict refs:
#!/usr/bin/perl
use warnings;
use strict;
{ package Parent;
our $package = 'Parent';
sub get_package {
my $class = shift;
{ no strict 'refs';
return (caller(0))[3], $class, ${"$class\::package"}
}
}
}
{ package Son;
use parent 'Parent';
our $package = 'Son';
}
print join ' ', 'Son'->get_package, "\n";
print join ' ', 'Parent'->get_package, "\n";
In Moo*, you can use Moo*X::ClassAttribute:
#!/usr/bin/perl
use warnings;
use strict;
{ package Parent;
use Moo;
use MooX::ClassAttribute;
class_has package => (is => 'ro',
default => 'Parent');
sub get_package {
my $class = shift;
return $class->package;
}
}
{ package Son;
use Moo;
use MooX::ClassAttribute;
extends 'Parent';
class_has package => (is => 'ro',
default => 'Son');
}
print 'Parent'->get_package, "\n";
print 'Son'->get_package, "\n";
Note that MooX::ClassAttribute says
Overriding class attributes and their accessors in subclasses is not yet supported.
Unlike in Moose, you can't use the class_has '+package' => (default => 'Son'); syntax for overriding.
While refactoring I'm trying to retain some backwards compatibility for a time. I'm wondering if it's possible to have a method on an object, but prevent that method from being inherited by classes that subclass it? e.g. given
package Class {
use Moose;
sub foo { 'test' };
}
my $class = Class->new;
$class->foo;
would work, but
package Extended::Class {
use Moose;
extends 'Class';
}
my $class = Extended::Class->new;
$class->foo;
would not.
I realize this probably breaks some principle or another, but I'm deprecating these interfaces as I go.
How about:
use 5.014;
package Class {
use Carp qw( croak );
use Moose;
sub foo {
my $self = shift;
croak unless __PACKAGE__ eq ref $self;
return 'test';
}
}
package Extended::Class {
use Moose;
extends 'Class';
}
package main {
my $x = Class->new;
say $x->foo;
my $y = Extended::Class->new;
say $y->foo;
}
Have you considered delegation?
package Original {
use Moose;
sub foo { 23 }
sub bar { 42 }
}
package Subclass {
use Moose;
has original => (
buidler => '_build_original',
handles => [qw( bar )],
);
sub _build_original { Original->new }
}
Of course it depends on your situation if you can use it. The subclass won't pass isa checks for the above (but you can override isa if you must). Also passing the original arguments on to the object you're extending can be annoying depending on the use case.
Since it would look for the method foo in the Extended::Class first, you could just declare one there that doesn't do anything. That way the inherited one would not be called unless you do so somewhere in your subclass.
I'm not sure if Moose alters that behaviour, though.
package Class {
use Moose;
sub foo { 'test' }
}
package Extended::Class {
use Moose;
extends 'Class';
sub foo {
# do nothing
}
}
package main {
my $x = Class->new;
my $y = Extended::Class->new;
print $x->foo;
print $y->foo;
}
I need multemethod dispatch with Moose objects. I'm doing this with Class::Multimethods::Pure. I chose this instead of MooseX::MultiMethods because it depends on MooseX::Method::Signatures which can't install on my system because it fails its tests. I don't mind if you have an alternative approach to suggest.
The following works fine with types and subtypes:
package Foo::Type;
use Moose;
package Foo::SubType;
use Moose;
extends 'Foo::Type';
package main;
use Class::Multimethods::Pure;
multi hello => ('Foo::Type') => sub {
my ( $foo ) = #_;
print $foo;
};
hello( Foo::SubType->new );
But the scenario I now need to handle is where the declared type is actually a Moose Role:
package Foo::Role;
use Moose::Role;
package Foo::Type;
use Moose;
with 'Foo::Role';
package main;
use Class::Multimethods::Pure;
multi hello => ('Foo') => sub {
my ( $foo ) = #_;
print $foo;
};
hello( Foo::Type->new );
But this can't recognise the role:
No method found for args (Foo::Type=HASH(0x22ac854))
The documentation says it can be extended in various ways, including adding Perl 6-ish roles. But it's a little sketchy for me and I'm looking for a more detailed example. Has anyone tried this?
My solution was to convert the roles to abstract base classes using MooseX::ABC. In this way, they could be recognised as a class type.
On a side note, I managed to get MooseX::MultiMethods working on another system. It does work with roles, but it can't figure out which to use if we define a multimethod that takes the class and another multimethod that takes the role. Incidentally, MooseX::ABC resolved this issue also since it gave me a hierarchical structure which the roles did not really have.
package Foo::Role;
use Moose::Role;
package Foo::Type;
use Moose;
with 'Foo::Role';
package Merger;
use Moose;
use MooseX::MultiMethods;
multi method hello (Foo::Role $foo) {
print 'Foo::Role: '.$foo;
}
multi method hello (Foo::Type $foo) {
print 'Foo::Type: '.$foo;
}
package main;
my $merger = Merger->new;
my $f = Foo::Type->new;
$merger->hello( $f );
# Ambiguous match for multi method hello: (Foo::Role $foo), (Foo::Type $foo)
# with value [ Merger{ }, Foo::Type{ } ]
Or: Is there a standard way to create subclass but make certain methods from the superclass yield a "Can't locate object method" error when called?
For example, if My::Foo inherits from My::Bar, and My::Bar has a method called dostuff, calling Foo->new->dostuff would die with the "Can't locate object method" error in some non-contrived/hackish way.
If the superclass is a Moose class you could use remove_method.
package My::Foo;
use Moose;
extends 'My::Bar';
# some code here
my $method_name = 'method_to_remove';
__PACKAGE__->meta->remove_method($method_name);
1;
This is documented in Class::MOP::Class and should work with MooseX::NonMoose but i am not sure.
You can create dummy methods in your child class that intercept the method calls and die.
package My::Foo;
our #ISA = 'My::Bar';
use Carp ();
for my $method qw(dostuff ...) {
no strict 'refs';
*$method = sub {Carp::croak "no method '$method' on '$_[0]'"};
}
You could even write a module to do this:
package No::Method;
use Carp ();
sub import {
my $class = shift;
my $caller = caller;
for my $method (#_) {
no strict 'refs';
*{"$caller\::$method"} = sub {
Carp::croak "no method '$method' on '$_[0]'"
};
}
}
And then to use it:
package My::Foo;
our #ISA = 'My::Bar';
use No::Method qw(dostuff);
This depends entirely on the way My::Bar and My::Foo are constructed. If they are your modules you may want to look into Exporter.
You can also import select functions from a class like so:
use POSIX qw{setsid};