Debian Codegraph @

lib/Dancer2/Manual/Extending.pod

raw
1 # ABSTRACT: A guide to extending Dancer2 via engines and plugins
2
3 package Dancer2::Manual::Extending;
4
5 __END__
6
7 =pod
8
9 =encoding UTF-8
10
11 =head1 NAME
12
13 Dancer2::Manual::Extending - A guide to extending Dancer2 via engines and plugins
14
15 =head1 VERSION
16
17 version 2.2.2
18
19 =head1 Name
20
21 Dancer2::Extending - How to Extend Dancer2 by Writing Your Own Engines, Handlers, and Plugins
22
23 =head1 Introduction
24
25 Dancer2 is designed to be flexible and extensible. Whether you need a
26 custom template engine, session engine, serializer, or file handler,
27 Dancer2 provides a clean API that makes it easy to extend its core
28 functionality.
29
30 In this document, we’ll cover how to write your own engines, handlers,
31 and plugins for Dancer2. The goal is to give you the tools you need to
32 build custom components that integrate seamlessly into your Dancer2
33 applications.
34
35 =head1 Writing Your Own Engine
36
37 In Dancer2, engines are used to handle various aspects of your
38 application, such as templates, sessions, serializers, and loggers. Each
39 engine follows a standard interface, making it easy to plug in new
40 implementations.
41
42 Engines can live in the Dancer2 namespace:
43
44 set serializer => 'JSON';
45 set template => 'Mason';
46
47 (these resolve to L<Dancer2::Serializer::JSON> and L<Dancer2::Template::Mason>
48 respectively)
49
50 Or you can provide the fully qualified namespace using the C<+> indicator:
51
52 set serializer => `+My::Awesome::Serializer`;
53 set template => `+My::Template::DWIM`;
54
55 The latter is similar to how L<Plack> handles this.
56
57 =head2 Writing a Template Engine
58
59 A custom template engine must implement the L<Dancer2::Core::Role::Template>
60 role. This role defines the basic methods that any template engine needs
61 to implement.
62
63 =head3 Example: Custom Template Engine
64
65 package Dancer2::Template::MyTemplateEngine;
66 use Moo;
67 with 'Dancer2::Core::Role::Template';
68
69 # Define the required methods
70 # ...
71
72 sub render {
73 my ($self, $template, $tokens) = @_;
74
75 # Your rendering logic here
76 return "<html><body>Welcome to Danceyland, $tokens->{'visitor_name'}!</body></html>";
77 }
78
79 1;
80
81 In this example, C<render> is the method responsible for processing the
82 template and returning the final output.
83
84 To use your custom engine, configure it in your C<config.yml> file:
85
86 template: "MyTemplateEngine"
87
88 =head2 Writing a Session Engine
89
90 Session engines handle storing and retrieving session data. All session
91 engines must implement the L<Dancer2::Core::Role::SessionFactory> role.
92
93 =head3 Example: Custom Session Engine
94
95 package Dancer2::Session::MySessionEngine;
96 use Moo;
97 with 'Dancer2::Core::Role::SessionFactory';
98
99 sub retrieve {
100 my ($self, $id) = @_;
101 # Fetch session data based on session ID
102 }
103
104 sub create {
105 my ($self, $data) = @_;
106 # Create a new session
107 }
108
109 sub destroy {
110 my ($self, $id) = @_;
111 # Destroy the session identified by $id
112 }
113
114 sub flush {
115 my ($self, $id, $data) = @_;
116 # Save session data
117 }
118
119 1;
120
121 This engine defines the basic methods to manage session data.
122
123 =head2 Writing a Serializer Engine
124
125 Serializer engines handle serializing and deserializing data between
126 Perl data structures and different formats like JSON, YAML, or XML.
127
128 All serializer engines must implement the L<Dancer2::Core::Role::Serializer>
129 role.
130
131 =head3 Example: Custom Serializer Engine
132
133 package Dancer2::Serializer::MySerializer;
134 use Moo;
135 with 'Dancer2::Core::Role::Serializer';
136
137 sub serialize {
138 my ($self, $content) = @_;
139 # Convert $content to a custom format
140 }
141
142 sub deserialize {
143 my ($self, $content) = @_;
144 # Convert custom format back to Perl data structure
145 }
146
147 sub content_type {
148 return 'application/custom';
149 }
150
151 1;
152
153 This engine defines the methods needed to serialize and deserialize data.
154
155 =head2 Writing a Logger Engine
156
157 Logger engines are responsible for handling log messages in your
158 application. All logger engines must implement the
159 L<Dancer2::Core::Role::Logger> role.
160
161 =head3 Example: Custom Logger Engine
162
163 package Dancer2::Logger::MyLogger;
164 use Moo;
165 with 'Dancer2::Core::Role::Logger';
166
167 sub log {
168 my ($self, $level, $message) = @_;
169 # Custom logging logic here
170 warn "[$level] $message";
171 }
172
173 1;
174
175 This logger will output log messages to C<warn>, and you can configure
176 it in your C<config.yml> file:
177
178 logger: "MyLogger"
179
180 =head1 Writing Your Own File Handler
181
182 File handlers in Dancer2 are responsible for serving static files from
183 disk. If you need custom logic for serving files (such as restricting
184 access or adding dynamic features), you can create your own file handler
185 by consuming the L<Dancer2::Core::Role::Handler> role.
186
187 =head2 Example: Custom File Handler
188
189 package Dancer2::Handler::MyFileHandler;
190 use Moo;
191 with 'Dancer2::Core::Role::Handler';
192
193 sub methods { qw(GET) }
194
195 sub regexp { '/static/:file' }
196
197 sub code {
198 return sub {
199 my $app = shift;
200 my $file = $app->request->params->{file};
201
202 # Add custom logic for serving files
203 my $file_path = "/path/to/static/files/$file";
204 if (-e $file_path) {
205 $app->send_file($file_path);
206 } else {
207 $app->send_error('File not found', 404);
208 }
209 };
210 }
211
212 sub register {
213 my ($self, $app) = @_;
214 $app->add_route(
215 method => $_,
216 regexp => $self->regexp,
217 code => $self->code,
218 ) for $self->methods;
219 }
220
221 1;
222
223 This handler will serve static files from the specified directory, but
224 it also checks if the file exists before serving it.
225
226 =head1 Writing A Dancer2 Plugin
227
228 Plugins in Dancer2 are reusable components that extend your app's
229 functionality. They are often used for tasks like authentication,
230 database management, or form validation.
231
232 All plugins must consume the L<Dancer2::Core::Role::Plugin> role.
233
234 =head2 Example: Custom Dancer2 Plugin
235
236 package Dancer2::Plugin::MyPlugin;
237 use Dancer2::Plugin;
238
239 register 'greet' => sub {
240 my ($dsl, $name) = @_;
241 return "Hello, $name! Welcome to Danceyland!";
242 };
243
244 register_plugin;
245
246 In this example, a C<greet> keyword is created, and can be called within
247 any Dancer2 route to display a greeting. To use the plugin, just include
248 it in your app:
249
250 use Dancer2::Plugin::MyPlugin;
251
252 get '/hello/:name' => sub {
253 return greet( route_parameters->get('name') );
254 };
255
256 =head1 Custom Session Storage Mechanisms
257
258 Dancer2 allows you to define your own custom session storage mechanism
259 by implementing the L<Dancer2::Core::Role::SessionFactory> role. This
260 is useful if you need to store session data in a format or storage medium
261 that isn’t supported out-of-the-box, such as a proprietary database or
262 external service.
263
264 =head2 Example: Custom Session Storage
265
266 Here’s how you can create a custom session storage engine that stores
267 session data in a simple hash in memory. In practice, you’d likely store
268 data in a more robust medium like a database or external cache.
269
270 package Dancer2::Session::MySessionStorage;
271 use Moo;
272 with 'Dancer2::Core::Role::SessionFactory';
273
274 # Simple in-memory session store (not suitable for production use)
275 my %session_store;
276
277 sub retrieve {
278 my ($self, $id) = @_;
279 return $session_store{$id};
280 }
281
282 sub create {
283 my ($self, $data) = @_;
284 my $session_id = $self->generate_session_id;
285 $session_store{$session_id} = $data;
286 return $session_id;
287 }
288
289 sub destroy {
290 my ($self, $id) = @_;
291 delete $session_store{$id};
292 }
293
294 sub flush {
295 my ($self, $id, $data) = @_;
296 $session_store{$id} = $data;
297 }
298
299 1;
300
301 =head3 Using the Custom Session Storage
302
303 To use your custom session storage mechanism, configure it in your
304 F<config.yml> file:
305
306 session: "MySessionStorage"
307
308 This simple example uses an in-memory hash to store sessions, but you
309 can adapt it to any storage medium, such as Redis, MongoDB, or a
310 relational database. Be sure to implement locking mechanisms and
311 persistence for production usage.
312
313 =head1 Custom Middleware
314
315 Middleware is code that runs before or after the core request handler in
316 Dancer2. It allows you to intercept, modify, or even short-circuit the
317 request/response cycle before it reaches your app’s route handlers or
318 after they return a response.
319
320 =head2 How Middleware Works
321
322 When a request is received, middleware runs in a predefined order:
323
324 =over 4
325
326 =item 1.
327
328 Before the app handler is executed (C<before> stage).
329
330 =item 2.
331
332 The app's route handlers process the request.
333
334 =item 3.
335
336 After the app handler processes the request and returns a response
337 (C<after> stage).
338
339 =back
340
341 Middleware gives you the ability to modify the request before it's passed
342 to the app handler, or to change the response after it has been generated.
343 You can also prevent the app handler from running altogether and return a
344 custom response directly from the middleware.
345
346 =head2 Example: Custom Middleware
347
348 Here’s an example of custom middleware that runs before and after the app
349 handler. It logs the incoming request, processes the app’s routes, and
350 then modifies the response by appending a footer message.
351
352 package Dancer2::Middleware::MyCustomMiddleware;
353 use Plack::Middleware;
354 use parent 'Plack::Middleware';
355
356 sub call {
357 my ($self, $env) = @_;
358
359 # BEFORE the app handler: Log the request method and path
360 warn "Incoming request: $env->{REQUEST_METHOD} $env->{PATH_INFO}";
361
362 # Call the app handler (if you want the app to continue processing)
363 my $res = $self->app->($env);
364
365 # AFTER the app handler: Modify the response (e.g., add a footer)
366 return sub {
367 my $respond = shift;
368 my $writer = $respond->(
369 [
370 $res->[0], # HTTP status code
371 $res->[1], # HTTP headers
372 $res->[2], # HTTP body
373 ]
374 );
375
376 # Append a footer to the response body
377 $writer->write("\n-- Thank you for visiting Danceyland!");
378 $writer->close;
379 };
380 }
381
382 1;
383
384 =head2 Using the Custom Middleware
385
386 To enable this middleware, modify your F<app.psgi> file to use it with
387 Dancer2’s built-in support for Plack middleware:
388
389 use Dancer2;
390 use MyApp;
391
392 builder {
393 enable 'Dancer2::Middleware::MyCustomMiddleware';
394 MyApp->to_app;
395 };
396
397 =head3 How Middleware Can Control the Flow
398
399 In the example above, the middleware logs the request before it reaches
400 the app and modifies the response after the app handler runs. However,
401 if you don’t want to call the app handler (for example, to short-circuit
402 the request and return a custom response), you can skip the call to
403 C<< $self->app->($env) >> and return a response directly from the
404 middleware:
405
406 sub call {
407 my ($self, $env) = @_;
408
409 # If the request matches a certain condition, bypass the app handler
410 if ($env->{PATH_INFO} =~ m{/secret}) {
411 return [403, ['Content-Type' => 'text/plain'], ["Forbidden"]];
412 }
413
414 # Otherwise, continue to the app handler
415 my $res = $self->app->($env);
416
417 # Modify the response as needed
418 ...
419 }
420
421 In this case, if the request path contains C</secret>, the middleware
422 returns a 403 Forbidden response, skipping the app handler entirely.
423
424 =head3 Order of Operations
425
426 Middleware executes in the following order:
427
428 =over 4
429
430 =item *
431
432 Any code in the C<before> stage is executed before your app processes the
433 request. You can modify or reject the request here.
434
435 =item *
436
437 Your app processes the request and generates a response.
438
439 =item *
440
441 Any code in the C<after> stage is executed after the response has been
442 generated. You can modify or append to the response here before it’s
443 sent to the client.
444
445 =back
446
447 Custom middleware provides great flexibility for pre- and post-processing
448 requests and responses in your Dancer2 app.
449
450 =head1 AUTHOR
451
452 Dancer Core Developers
453
454 =head1 COPYRIGHT AND LICENSE
455
456 This software is copyright (c) 2026 by Alexis Sukrieh.
457
458 This is free software; you can redistribute it and/or modify it under
459 the same terms as the Perl 5 programming language system itself.
460
461 =cut