Debian Codegraph @

lib/Dancer2/Core/Hook.pm

raw
1 package Dancer2::Core::Hook;
2 # ABSTRACT: Manipulate hooks with Dancer2
3 $Dancer2::Core::Hook::VERSION = '2.2.2';
4 use Moo;
5 use Dancer2::Core::Types;
6 use Carp;
7 use Sub::Util qw/ set_subname subname /;
8
9 has name => (
10 is => 'rw',
11 isa => Str,
12 required => 1,
13 coerce => sub {
14 my ($hook_name) = @_;
15
16 # XXX at the moment, we have a filer position named "before_template".
17 # this one is renamed "before_template_render", so we need to alias it.
18 # maybe we need to deprecate 'before_template' to enforce the use
19 # of 'hook before_template_render => sub {}' ?
20 $hook_name = 'before_template_render'
21 if $hook_name eq 'before_template';
22 return $hook_name;
23 },
24 );
25
26 has code => (
27 is => 'ro',
28 isa => CodeRef,
29 required => 1,
30 coerce => sub {
31 my ($hook) = @_;
32 set_subname subname($hook) => sub {
33 my $res = eval { $hook->(@_) };
34 croak "Hook error: $@" if $@;
35 return $res;
36 };
37 },
38 );
39
40 1;
41
42 __END__
43
44 =pod
45
46 =encoding UTF-8
47
48 =head1 NAME
49
50 Dancer2::Core::Hook - Manipulate hooks with Dancer2
51
52 =head1 VERSION
53
54 version 2.2.2
55
56 =head1 SYNOPSIS
57
58 # inside a plugin
59 use Dancer2::Core::Hook;
60 Dancer2::Core::Hook->register_hooks_name(qw/before_auth after_auth/);
61
62 =head1 METHODS
63
64 =head2 register_hook ($hook_name, $code)
65
66 hook 'before' => sub {...};
67
68 Attaches a hook at some point.
69
70 =head2 register_hooks_name
71
72 Add a new hook name, so application developers can insert some code at this point.
73
74 package My::Dancer2::Plugin;
75 Dancer2::Core::Hook->instance->register_hooks_name(qw/before_auth after_auth/);
76
77 =head2 execute_hook
78
79 Execute a hook
80
81 =head2 get_hooks_for
82
83 Returns the list of coderef registered for a given position
84
85 =head2 hook_is_registered
86
87 Test if a hook with this name has already been registered.
88
89 =head1 AUTHOR
90
91 Dancer Core Developers
92
93 =head1 COPYRIGHT AND LICENSE
94
95 This software is copyright (c) 2026 by Alexis Sukrieh.
96
97 This is free software; you can redistribute it and/or modify it under
98 the same terms as the Perl 5 programming language system itself.
99
100 =cut