in reply to Finding the interface implemented by an object
You can use Class::MOP or it's offspring Moose to do this.
First the Class::MOP version ...
This will not print "Can dump()" since Class::MOP knows that the method is not actually from your package, but has been imported from another package. To find the "interface" with Class::MOP, you have a few choices. First you can get all the locally defined methods* like this:package TestPackage; use metaclass; # this sets up your class to use Class::MOP use Data::Dump qw( dump ); my $obj = bless {}, __PACKAGE__; print 'Can dump()' if $obj->meta->has_method('dump');
This will return a list of method names suitable for doing things like $obj->meta->has_method($method_name) and $obj->meta->get_method($method_name) and other such introspection and reflection. Or, your second choice is to get all the methods this $obj supports, including inherited methods. In this case you do the following:my @methods = $obj->meta->get_method_list;
The items in @methods this time are slightly different, you get a HASH reference which contains the method name (in the name key), the name of the class in which the method lives (in the class key) and a CODE reference for the actual method (in the code key).my @methods = $obj->meta->compute_all_applicable_methods;
Now, you could also use Moose and Moose::Role to do similar things. Moose is basically syntactic sugar over the mechanisms that Class::MOP provides, so all the above examples apply here as well. With roles** and Moose::Role you can do the interface checking you are talking about. Here is an example:
Then you apply the role to your class, which checks the role "interface" at compile time.package MyFooInterface; use Moose::Role; requires 'bar';
And you can also do your checking at runtime ...package MyFoo; use Moose; with 'MyFooInterface'; sub bar { ... } # the bar method is required, the # class will fail to compile if it is # not present
For more information, see the CPAN pages for Moose or Class::MOP, or for a quicker overview you can check out one of these talks recently given on the subject:my $foo = MyFoo->new; if ($foo->does('MyFooInterface')) { ... }
Footnotes:
* Locally defined methods are those defined directly in your class, and not inherited.
** If you don't already know, a role is not unlike a mixin or the traits mentioned above, but with a little bit more of a Perl-ish twist. They are a core part of Perl 6 in fact.
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re^2: Finding the interface implemented by an object
by j1n3l0 (Friar) on Nov 28, 2007 at 14:01 UTC | |
by stvn (Monsignor) on Nov 28, 2007 at 15:19 UTC |