I use Class::Meta. I'm considering making it a way of life... Thanks!
I've extended it a bit with a Constructor that calls _initialize when
it's done. I've also created a MethodCheckParameter class which
creates the actual method (like a constructor with create=>1). That
method validates the paramters passed in and creates and instance of a
special dynamically built class::meta to hold those parametets. It
uses goto to make the final call which is nice because "caller" still
works as expected.
Unfortunately, I had to fork Meta.pm as opposed to extend it because
the add_method sub did not add the method to
$classes->{<package>}->{build_meth_ord}. I filed a CR with
bugs-class-meta@cpan.org (#11689) about this.
It works like this:
#!/usr/bin/perl -w
use strict;
package myclass;
use TKC::Meta;
use TKC::Meta::ConstructorInitialize;
use TKC::Meta::MethodCheckParameters;
use Class::Meta::Types::String qw(semi-affordance);
BEGIN {
my $cm = TKC::Meta->new(constructor_class => "TKC::Meta::ConstructorInitialize",
method_class => "TKC::Meta::MethodCheckParameters",
);
$cm->add_constructor(name=>"new", create=>1);
my $meth = $cm->add_method(name=>"mymeth");
$meth->add_parameter(name=>'parameter', type=>'string');
$cm->build();
}
sub _initialize {
my ($this) = @_;
print "INITIALIZE for: ",$this,"\n";
}
sub _mymeth {
my ($this, $params) = @_;
print "THIS : ",$this, "\n";
print "PARAMS : ",$params, "\n";
print "CALLER : ",join(", ",caller), "\n";
print "PARAMETER: ",$params->parameter, "\n";
}
1;
When called by a little program in mytest.pl:
#!/usr/bin/perl -w
use strict;
use myclass;
my $c = myclass->new();
$c->mymeth(parameter=> "this is a string");
exit(0);
You get the following output:
# perl mytest.pl
INITIALIZE for: myclass=HASH(0x80f606c)
THIS : myclass=HASH(0x80f606c)
PARAMS : myclass::mymeth_parameters=HASH(0x81008a4)
CALLER : main, mytest.pl, 6
PARAMETER: this is a string