1Mojo::DynamicMethods(3)User Contributed Perl DocumentatioMnojo::DynamicMethods(3)
2
3
4

NAME

6       Mojo::DynamicMethods - Fast dynamic method dispatch
7

SYNOPSIS

9         package MyClass;
10         use Mojo::Base -base, -signatures;
11
12         use Mojo::DynamicMethods -dispatch;
13
14         sub BUILD_DYNAMIC ($class, $method, $dyn_methods) {
15           return sub {...};
16         }
17
18         sub add_helper ($self, $name, $cb) {
19           Mojo::DynamicMethods::register 'MyClass', $self, $name, $cb;
20         }
21
22         package main;
23
24         # Generate methods dynamically (and hide them from "$obj->can(...)")
25         my $obj = MyClass->new;
26         $obj->add_helper(foo => sub { warn 'Hello Helper!' });
27         $obj->foo;
28

DESCRIPTION

30       Mojo::DynamicMethods provides dynamic method dispatch for per-object
31       helper methods without requiring use of "AUTOLOAD".
32
33       To opt your class into dynamic dispatch simply pass the "-dispatch"
34       flag.
35
36         use Mojo::DynamicMethods -dispatch;
37
38       And then implement a "BUILD_DYNAMIC" method in your class, making sure
39       that the key you use to lookup methods in $dyn_methods is the same
40       thing you pass as $ref to "register".
41
42         sub BUILD_DYNAMIC ($class, $method, $dyn_methods) {
43           return sub ($self, @args) {
44             my $dynamic = $dyn_methods->{$self}{$method};
45             return $self->$dynamic(@args) if $dynamic;
46             my $package = ref $self;
47             croak qq{Can't locate object method "$method" via package "$package"};
48           };
49         }
50
51       Note that this module will summon Cthulhu, use it at your own risk!
52

FUNCTIONS

54       Mojo::DynamicMethods implements the following functions.
55
56   register
57         Mojo::DynamicMethods::register $class, $ref, $name, $cb;
58
59       Registers the method $name as eligible for dynamic dispatch for $class,
60       and sets $cb to be looked up for $name by reference $ref in a dynamic
61       method constructed by "BUILD_DYNAMIC".
62

SEE ALSO

64       Mojolicious, Mojolicious::Guides, <https://mojolicious.org>.
65
66
67
68perl v5.34.0                      2021-07-22           Mojo::DynamicMethods(3)
Impressum