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

DESCRIPTION

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

FUNCTIONS

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

SEE ALSO

68       Mojolicious, Mojolicious::Guides, <https://mojolicious.org>.
69
70
71
72perl v5.32.0                      2020-07-28           Mojo::DynamicMethods(3)
Impressum