Loading the needed packages on demand in perl - perl

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($_);
}

Related

How to we dynamically create missing attributes in Moo or Moose?

We have a sample code like below. Is it possible to to capture all missing attributes invoked in package FooBar and create it dynamically? This is something like PHP's __call.
test.pl
package Person;
use feature qw(say);
use Moo;
has name => (is => "ro");
my $p = Person->new(name => "John");
say $p->name;
# The missing attribute method will be dynamically created when
# invoked even it's not declared in Person.
say $p->lalala;
$ perl test.pl
John
Can't locate object method "lalala" via package "Test" at test.pl line 13.
It's possible using AUTOLOAD and metaprogramming, the question remains Why.
There might be nicer ways using parameterized roles, but I just wanted to quickly show how to do it. I would reject such code in a review (I'd expect at least a comment explaining why autoloading is needed).
#!/usr/bin/perl
use warnings;
use strict;
use feature qw{ say };
{ package MyObj;
use Moose;
sub AUTOLOAD {
my ($self) = #_;
( my $method = our $AUTOLOAD ) =~ s/.*:://;
(ref $self)->meta->add_attribute($method, is => 'rw');
goto &$method
}
}
say 'MyObj'->can('lalala'); # No, it can't.
my $o = 'MyObj'->new;
$o->lalala(12); # Attribute created.
say $o->lalala; # 12.
Update: Previously, my code was more complex, as it replied to #simbabque's comment to the question: it showed how to add the attribute to an instance, not the whole class.

How to add a new syntax feature for perl?

I want to add a new feature for Perl language, in order to type less $self->.
For example, Translate:
use Moo;
has a_attr => (is=>'rw');
sub XXX {
print $self->a_attr;
}
To:
use Moo;
use MyFeatureModule;
has a_attr => (is=>'rw');
sub XXX {
print _a_attr;
}
How-to?
This doesn't require any changes to Perl's syntax, only to its semantics. Luckily, that's not too hard.
What you want can be achieved by providing an AUTOLOAD sub for your package, which will kick in automatically whenever you call a sub that hasn't been defined yet (i.e. _a_attr in your example). This AUTOLOAD method can then use Devel::Caller to grab $_[0] (i.e. $self) from its caller, inject it onto #_ and then goto the original method.
use v5.14;
use strictures;
package Foo {
use Moo;
has xyzzy => (is => 'ro', default => 42);
sub sayit {
say _xyzzy();
}
sub AUTOLOAD {
require Devel::Caller;
my ($invocant) = Devel::Caller::caller_args(1);
unshift #_, $invocant;
my ($method) = (our $AUTOLOAD =~ /::_(\w+)\z/)
or die "Method not found!";
my $coderef = $invocant->can($method)
or die "Method not found!";
goto $coderef;
};
}
my $obj = Foo->new;
$obj->sayit;
Is this a good idea? Well, I certainly wouldn't do it. As well as introducing an unnecessary level of slow-down to your code, and breaking inheritance, it is likely to confuse anybody who has to maintain your code after you. (And that might be your future self if you take a break from the project, and come back to it in 6 months.)

How to override a sub in a Moose::Role?

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

How to extend Class::Multimethods::Pure to recognise Moose Roles?

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{ } ]

How can I share variables between a base class and subclass in Perl?

I have a base class like this:
package MyClass;
use vars qw/$ME list of vars/;
use Exporter;
#ISA = qw/Exporter/;
#EXPORT_OK = qw/ many variables & functions/;
%EXPORT_TAGS = (all => \#EXPORT_OK );
sub my_method {
}
sub other_methods etc {
}
--- more code---
I want to subclass MyClass, but only for one method.
package MySubclass;
use MyClass;
use vars qw/#ISA/;
#ISA = 'MyClass';
sub my_method {
--- new method
}
And I want to call this MySubclass like I would the original MyClass, and still have access to all of the variables and functions from Exporter. However I am having problems getting the Exporter variables from the original class, MyClass, to export correctly. Do I need to run Exporter again inside the subclass? That seems redundant and unclear.
Example file:
#!/usr/bin/perl
use MySubclass qw/$ME/;
-- rest of code
But I get compile errors when I try to import the $ME variable. Any suggestions?
You should access everything through methods. Forget about passing variables around.
You're getting a syntax error because you have a syntax error:
use MySubclass /$ME/; # syntax error - that's the match operator
You want a list there:
use MySubclass qw/$ME/;
However, don't do that. Provide access to these data through methods. Since you'll inherit the methods, you don't need (and shouldn't use) Exporter:
package MyClass;
BEGIN {
my $ME;
sub get_me { $ME }
sub set_me { $ME = shift }
}
Now your subclass is just:
package MySubclass;
use parent( MyClass );
sub my_method { ... }
There are various modules that can automatically handle the accessor details for you if you have many variables you need to share.
In general, OO Perl and Exporter are normally kept separate instead of mixing them together. This is one of the reasons why.
Like brian said, you'll have a much easier time getting this to work in the first place and with extending it further in the future if you take all the crap you're exporting, turn it into class properties/methods, and get rid of Exporter completely. The simple fact that the way you want to do it requires you to import and re-export everything should be a big, flashing clue that there's probably a better way to do it (i.e., a way that doesn't involve Exporter).
You're not actually inheriting MySubclass from MyClass at all -- MySubClass is a user of MyClass. What you're doing is overriding a bit of behaviour from MyClass, but you will only confuse yourself if you think of this as inheritance, because it isn't (for example: where is your constructor?) I couldn't figure out what you were trying to do until I ignored everything the code was doing and just read your description of what you want to have happen.
Okay, so you have a class which imports some symbols - some functions, and some variables:
package MyClass;
use strict;
use warnings;
use Exporter 'import'; # gives you Exporter's import() method directly
our #EXPORT_OK = qw/ many variables & functions/;
our %EXPORT_TAGS = (all => \#EXPORT_OK );
our ($ME, $list, $of, $vars);
sub my_func {
}
sub other_func {
}
1;
and then you come along and write a class which imports everything from MyClass, imports it all back out again, but swaps out one function for another one:
package MyBetterclass;
use strict;
use warnings;
use Exporter 'import'; # gives you Exporter's import() method directly
our #EXPORT_OK = qw/ many variables & functions /;
our %EXPORT_TAGS = (all => \#EXPORT_OK );
use MyClass ':all';
sub my_func {
# new definition
}
1;
That's it! Note that I enabled strict checking and warnings, and changed the names of the "methods" that are actually functions.
Additionally, I did not use use vars (the documentation says it's obsolete, so that's a big red flag if you still want to use it without understanding its mechanics).
# use setters and getters the Perl's way
#
# ---------------------------------------
# return a field's value
# ---------------------------------------
sub get {
my $self = shift;
my $name = shift;
return $self->{ $name };
} #eof sub get
#
# ---------------------------------------
# set a field's value
# ---------------------------------------
sub set {
my $self = shift;
my $name = shift;
my $value = shift;
$self->{ $name } = $value;
}
#eof sub set
#
# ---------------------------------------
# return the fields of this obj instance
# ---------------------------------------
sub dumpFields {
my $self = shift;
my $strFields = ();
foreach my $key ( keys %$self ) {
$strFields .= "$key = $self->{$key}\n";
}
return $strFields;
} #eof sub dumpFields