| 1 |
# ABSTRACT: A guide to building web applications with Dancer2 |
| 2 |
|
| 3 |
package Dancer2::Manual; |
| 4 |
|
| 5 |
__END__ |
| 6 |
|
| 7 |
=pod |
| 8 |
|
| 9 |
=encoding UTF-8 |
| 10 |
|
| 11 |
=head1 NAME |
| 12 |
|
| 13 |
Dancer2::Manual - A guide to building web applications with Dancer2 |
| 14 |
|
| 15 |
=head1 VERSION |
| 16 |
|
| 17 |
version 2.2.2 |
| 18 |
|
| 19 |
=head1 Introduction to Dancer2: Managing Danceyland |
| 20 |
|
| 21 |
Welcome to Danceyland! As the new manager of this amazing park, you'll |
| 22 |
be maintaining and enhancing the experience for all your visitors. |
| 23 |
Imagine each attraction, food stall, and ticket booth as different |
| 24 |
locations in your web application. Let's explore how to manage these |
| 25 |
various components using Dancer2. |
| 26 |
|
| 27 |
If you're not sure if you're at the correct spot in the park, the L<documentation map|Dancer2/Documentation Index> |
| 28 |
can help you find your way. |
| 29 |
|
| 30 |
=head2 What is Dancer2? |
| 31 |
|
| 32 |
Dancer2 is a free and open-source web application framework written in |
| 33 |
Perl. It’s a complete rewrite of the original L<Dancer>, designed to be |
| 34 |
powerful and flexible, yet incredibly easy to use. |
| 35 |
|
| 36 |
With Dancer2, getting your web app up and running is a breeze. It |
| 37 |
boasts a rich ecosystem of adapters for popular template engines, |
| 38 |
session storage solutions, logging methods, serializers, and plugins. |
| 39 |
This means you can build your app your way, effortlessly. In this |
| 40 |
guide, we'll leverage those strengths to build and manage Danceyland. |
| 41 |
|
| 42 |
Before we learn the ins and outs of managing your park, make sure you |
| 43 |
head over to the L<quick start guide|Dancer2::Manual::QuickStart> and |
| 44 |
get your development machine set up with Dancer2. Once it's installed, |
| 45 |
make sure to build your park: |
| 46 |
|
| 47 |
dancer2 gen -a Danceyland |
| 48 |
|
| 49 |
=head1 Routes: Different Attractions and Facilities |
| 50 |
|
| 51 |
Core to Dancer2 is the concept of routes. Each attraction in your theme |
| 52 |
park is like a route in your web application. Visitors (users) can |
| 53 |
navigate to different attractions, just as they would visit different |
| 54 |
routes in your app. |
| 55 |
|
| 56 |
Let's show some of the rides and facilities in our park: |
| 57 |
|
| 58 |
# Defining routes for our theme park |
| 59 |
get '/' => sub { |
| 60 |
return "Welcome to Danceyland!"; |
| 61 |
}; |
| 62 |
|
| 63 |
get '/roller-coaster' => sub { |
| 64 |
return "Enjoy the thrilling roller coaster ride!"; |
| 65 |
}; |
| 66 |
|
| 67 |
post '/buy-ticket' => sub { |
| 68 |
my $ticket = body_parameters->get('ticket'); |
| 69 |
# Do something with ticket data |
| 70 |
return "You bought a $ticket ticket!"; |
| 71 |
}; |
| 72 |
|
| 73 |
=over |
| 74 |
|
| 75 |
=item The `/` route is like the main entrance to our theme park. Visitors are greeted with a welcome message. |
| 76 |
|
| 77 |
=item The `/roller-coaster` route is a thrilling ride. When visitors take this path, they get a special message. |
| 78 |
|
| 79 |
=item The `/buy-ticket` route is the ticket booth. Visitors buy their tickets here. |
| 80 |
|
| 81 |
=back |
| 82 |
|
| 83 |
=head2 New Keywords |
| 84 |
|
| 85 |
=over |
| 86 |
|
| 87 |
=item get |
| 88 |
|
| 89 |
This keyword defines a route that responds to HTTP GET requests. It |
| 90 |
takes two parameters: the route path and a subroutine that defines |
| 91 |
the response. |
| 92 |
|
| 93 |
get '/path' => sub { |
| 94 |
return "Response text"; |
| 95 |
}; |
| 96 |
|
| 97 |
Note that a route to match C<HEAD> requests is automatically created when |
| 98 |
you create a C<GET> route. |
| 99 |
|
| 100 |
=item post |
| 101 |
|
| 102 |
This keyword defines a route that responds to HTTP POST requests. It |
| 103 |
works similarly to C<get>, but is used for actions like submitting forms |
| 104 |
or buying tickets. |
| 105 |
|
| 106 |
post '/path' => sub { |
| 107 |
my $param = body_parameters->get('param'); |
| 108 |
return "You submitted: $param"; |
| 109 |
}; |
| 110 |
|
| 111 |
=back |
| 112 |
|
| 113 |
So exactly what are these HTTP requests, and what are they all about? |
| 114 |
|
| 115 |
=head2 HTTP Methods: Visitor Actions |
| 116 |
|
| 117 |
Think of HTTP methods as the different actions visitors can take in |
| 118 |
your theme park. Entering the park, buying tickets, updating ticket |
| 119 |
details, and leaving the park are all actions represented by C<GET>, |
| 120 |
C<POST>, C<PUT>, C<DEL>, C<OPTIONS>, and C<PATCH> methods respectively. |
| 121 |
|
| 122 |
Handling visitor actions in the park: |
| 123 |
|
| 124 |
# Defining HTTP methods for visitor actions |
| 125 |
get '/' => sub { |
| 126 |
return "Welcome to Danceyland!"; |
| 127 |
}; |
| 128 |
|
| 129 |
post '/buy-ticket' => sub { |
| 130 |
my $ticket = body_parameters->get('ticket'); |
| 131 |
return "You bought a $ticket ticket!"; |
| 132 |
}; |
| 133 |
|
| 134 |
put '/update-ticket' => sub { |
| 135 |
my $new_ticket = body_parameters->get('new_ticket'); |
| 136 |
return "Your ticket has been updated to $new_ticket!"; |
| 137 |
}; |
| 138 |
|
| 139 |
del '/leave-park' => sub { |
| 140 |
return "Thank you for visiting! Please come again!"; |
| 141 |
}; |
| 142 |
|
| 143 |
options '/park/info' => sub { |
| 144 |
return "Allowed methods: GET, POST, PUT"; |
| 145 |
}; |
| 146 |
|
| 147 |
patch '/profile/:id' => sub { |
| 148 |
my $user_id = route_parameters->get('id'); |
| 149 |
my $new_email = body_parameters->get('email'); |
| 150 |
return "Updated profile for user $user_id with email $new_email"; |
| 151 |
}; |
| 152 |
|
| 153 |
=over |
| 154 |
|
| 155 |
=item GET: Visitors enter the park and see a welcome message. |
| 156 |
|
| 157 |
=item POST: Visitors buy a ticket. |
| 158 |
|
| 159 |
=item PUT: Visitors update their ticket details. |
| 160 |
|
| 161 |
=item DELETE: Visitors leave the park. |
| 162 |
|
| 163 |
=item PATCH: Update part of a visitor's profile (in this case, email). |
| 164 |
|
| 165 |
=item OPTIONS: Describing the available operations on a specific route. |
| 166 |
|
| 167 |
Keep in mind, you would rarely implement this in your web application. |
| 168 |
|
| 169 |
=back |
| 170 |
|
| 171 |
These are good conventions to follow, but you can make your route |
| 172 |
handlers do whatever makes the most sense for your application. |
| 173 |
|
| 174 |
=head2 Routes, Route Definitions, and Route Handlers |
| 175 |
|
| 176 |
You may hear other Dancer developers talk about "routes", |
| 177 |
"route definitions", and "route handlers". "Route definitions" refers to |
| 178 |
the HTTP method and URL to respond to, while "route handler" is only the |
| 179 |
code implementing functionality for that definition. The two of these |
| 180 |
together make what's known as a route. |
| 181 |
|
| 182 |
get '/' => sub {...}; |
| 183 |
|
| 184 |
=over |
| 185 |
|
| 186 |
=item The verb, path, and subroutine is a route definition (AKA "route"). |
| 187 |
|
| 188 |
=item Only the subroutine reference (C<sub {...}>) is the route handler. |
| 189 |
|
| 190 |
=item The route definition I<and> the route handler collectively are the route. |
| 191 |
|
| 192 |
=back |
| 193 |
|
| 194 |
Each route requires a defintion and handler. The route needs to either return |
| 195 |
a string or Perl data structure to be rendered for the client. We'll learn |
| 196 |
more about rendering data structures later in our guide to Danceyland; for |
| 197 |
now, we're going to focus on returning strings, which will be rendered as |
| 198 |
HTML. |
| 199 |
|
| 200 |
=head3 What if we want a single park location to respond to multiple request types? |
| 201 |
|
| 202 |
Route definitions can use C<any> to match all, or a specified list of HTTP methods. |
| 203 |
|
| 204 |
The following will match any HTTP request to the path C</visitor-center>: |
| 205 |
|
| 206 |
any '/visitor-center' => sub { |
| 207 |
# Write code to do something at the visitor center! |
| 208 |
} |
| 209 |
|
| 210 |
The following will match GET or POST requests to C</visitor-center>: |
| 211 |
|
| 212 |
any ['get', 'post'] => '/visitor-center' => sub { |
| 213 |
# Write code to do something at the visitor center! |
| 214 |
}; |
| 215 |
|
| 216 |
=head2 URI Generation |
| 217 |
|
| 218 |
Dancer2 can generate URIs using the C<uri_for> and C<uri_for_route> |
| 219 |
keywords. Letting Dancer2 generate URIs helps ensure consistency, and |
| 220 |
reduces the amount of maintenance needed by making sure URIs are always |
| 221 |
up to date as the application evolves over time. |
| 222 |
|
| 223 |
=head3 uri_for |
| 224 |
|
| 225 |
The C<uri_for> keyword is used to generate a URI for a given path within |
| 226 |
your application, including query parameters. It's especially useful |
| 227 |
when you want to construct URLs dynamically inside your routes. |
| 228 |
|
| 229 |
=head4 Example: Generating a URI in Danceyland |
| 230 |
|
| 231 |
get '/ride/:name' => sub { |
| 232 |
my $ride_name = route_parameters->get('name'); |
| 233 |
return 'Enjoy the ride at ' . uri_for("/ride/$ride_name"); |
| 234 |
}; |
| 235 |
|
| 236 |
In this example, C<uri_for> generates a full URI for the ride name in |
| 237 |
Danceyland. |
| 238 |
|
| 239 |
=head3 uri_for_route |
| 240 |
|
| 241 |
The C<uri_for_route> keyword creates a URL for a named route. In |
| 242 |
Danceyland, it can be used to generate a URL to any part of the park |
| 243 |
that has a named route. |
| 244 |
|
| 245 |
For more information, see L<Dancer2::Manual::Keywords/uri_for_route>. |
| 246 |
|
| 247 |
=head3 Example 1: Basic Usage |
| 248 |
|
| 249 |
get 'films' => '/cinemaland/film-gallery' => sub { |
| 250 |
return "See the films at " . uri_for_route('films'); |
| 251 |
}; |
| 252 |
|
| 253 |
In this example, the route is named C<animals>, and C<uri_for_route> |
| 254 |
generates a URL pointing to it. |
| 255 |
|
| 256 |
=head3 Example 2: Using Route Parameters |
| 257 |
|
| 258 |
get 'ride' => '/ride/:name' => sub { |
| 259 |
my $ride_name = route_parameters->get('name'); |
| 260 |
return "Ride details: " . uri_for_route('ride', { name => $ride_name }); |
| 261 |
}; |
| 262 |
|
| 263 |
This example uses C<uri_for_route> to generate a URL that includes the |
| 264 |
named route parameter C<name>. |
| 265 |
|
| 266 |
=head3 Example 3: Including Query Parameters |
| 267 |
|
| 268 |
get 'search' => '/search' => sub { |
| 269 |
return uri_for_route('search', { q => 'roller coaster' }); |
| 270 |
}; |
| 271 |
|
| 272 |
get '/search' => sub { |
| 273 |
my $query = query_parameters->get('q'); |
| 274 |
return "Search results for: $query"; |
| 275 |
}; |
| 276 |
|
| 277 |
In this example, C<uri_for_route> generates a URL for the named route |
| 278 |
C<search> with the query parameter C<q> set to "roller coaster". |
| 279 |
|
| 280 |
=head2 Parameter Handling |
| 281 |
|
| 282 |
In Danceyland, visitors will often need to communicate with park staff. |
| 283 |
Similarly, your apps will need to take in information from application |
| 284 |
users via parameters. Dancer2 provides several methods for handling |
| 285 |
different types of parameters. |
| 286 |
|
| 287 |
=head3 Keywords for working with parameters |
| 288 |
|
| 289 |
=head4 param and params (Not Recommended) |
| 290 |
|
| 291 |
The C<param> and C<params> keywords are legacy methods to access request |
| 292 |
parameters. While still functional, they are not recommended for new |
| 293 |
applications. Instead, you should use the more specific keywords like |
| 294 |
C<route_parameters>, C<query_parameters>, and C<body_parameters> for |
| 295 |
clarity and precision. |
| 296 |
|
| 297 |
=head4 Example: Using param (Not Recommended) |
| 298 |
|
| 299 |
get '/submit' => sub { |
| 300 |
# Please use query_parameters() shown below |
| 301 |
my $name = param('name'); |
| 302 |
return "Submitted name: $name"; |
| 303 |
}; |
| 304 |
|
| 305 |
=head4 Example: Using params (Not Recommended) |
| 306 |
|
| 307 |
get '/all-params' => sub { |
| 308 |
# Pleaase use query_parameters() shown below |
| 309 |
my %all_params = params; |
| 310 |
return "All parameters: " . join(', ', %all_params); |
| 311 |
}; |
| 312 |
|
| 313 |
C<param> and C<params> are included here for completeness but are not the |
| 314 |
preferred methods for handling parameters in Danceyland. |
| 315 |
|
| 316 |
=head4 body_parameters |
| 317 |
|
| 318 |
This keyword retrieves parameters from the body of the request, typically |
| 319 |
used in POST requests. |
| 320 |
|
| 321 |
Example of C<body_parameters> with multiple values: |
| 322 |
|
| 323 |
post '/submit' => sub { |
| 324 |
my $name = body_parameters->get('name'); |
| 325 |
my $email = body_parameters->get('email'); |
| 326 |
return "Submitted name: $name, email: $email"; |
| 327 |
}; |
| 328 |
|
| 329 |
=head4 query_parameters |
| 330 |
|
| 331 |
This keyword retrieves parameters from the query string of the request |
| 332 |
URL: |
| 333 |
|
| 334 |
# Matches URL: /search?q=rides&cat=thrill |
| 335 |
get '/search' => sub { |
| 336 |
my $query = query_parameters->get('q'); |
| 337 |
my $category = query_parameters->get('cat'); |
| 338 |
return "Search query: $query in category: $category"; |
| 339 |
}; |
| 340 |
|
| 341 |
The above route would match the URL C</search?q=rides&cat=thrill>. |
| 342 |
|
| 343 |
=head4 route_parameters |
| 344 |
|
| 345 |
This keyword retrieves named parameters from the route declaration: |
| 346 |
|
| 347 |
# Matches URL: /user/123 |
| 348 |
get '/user/:id' => sub { |
| 349 |
my $user_id = route_parameters->get('id'); |
| 350 |
return "User ID: $user_id"; |
| 351 |
}; |
| 352 |
|
| 353 |
=head4 get_all |
| 354 |
|
| 355 |
This method works for all of the above parameter-fetching keywords. If |
| 356 |
you have a parameter that may contain more than one value, C<get_all> |
| 357 |
will return an array reference containing all selected values, even if |
| 358 |
there is only a single value returned. |
| 359 |
|
| 360 |
Example of C<get_all>: |
| 361 |
|
| 362 |
# Matches URL: /all-params?name=John&age=30 |
| 363 |
get '/all-params' => sub { |
| 364 |
my $params = query_parameters->get_all(); |
| 365 |
return "All query parameters: " . join(', ', %$params); |
| 366 |
}; |
| 367 |
|
| 368 |
=head3 Named Route Parameters |
| 369 |
|
| 370 |
Named route parameters allow you to capture specific segments of the URL |
| 371 |
and use them in your route handler: |
| 372 |
|
| 373 |
# Matches URL: /ride/roller-coaster |
| 374 |
get '/ride/:name' => sub { |
| 375 |
my $ride_name = route_parameters->get('name'); |
| 376 |
return "Welcome to the $ride_name ride!"; |
| 377 |
}; |
| 378 |
|
| 379 |
Named route parameters are retrieved with the L</route_parameters> |
| 380 |
keyword. |
| 381 |
|
| 382 |
=head3 Wildcard Route Parameters |
| 383 |
|
| 384 |
Wildcard route parameters allow you to capture arbitrary parts of the URL. |
| 385 |
There are two types: C<splat> and C<megasplat>. C<splat> is represented by |
| 386 |
a single asterisk (C<*>), and megaspat is represented by a double asterisk |
| 387 |
(C<**>). |
| 388 |
|
| 389 |
Examples of wildcard route parameters include: |
| 390 |
|
| 391 |
=over |
| 392 |
|
| 393 |
=item splat: Captures one segment of the URL |
| 394 |
|
| 395 |
# Matches URL: /files/document.txt |
| 396 |
get '/files/*' => sub { |
| 397 |
my ($file) = splat; |
| 398 |
return "You requested the file: $file"; |
| 399 |
}; |
| 400 |
|
| 401 |
=item megasplat: Captures multiple segments of the URL |
| 402 |
|
| 403 |
# Matches URL: /files/documents/reports/2023/summary.txt |
| 404 |
get '/files/**' => sub { |
| 405 |
my @files = splat; |
| 406 |
return "You requested the files: " . join(', ', @files); |
| 407 |
}; |
| 408 |
|
| 409 |
=back |
| 410 |
|
| 411 |
=head3 Combining named and wildcard parameters |
| 412 |
|
| 413 |
You can combine named and wildcard parameters in your routes to capture |
| 414 |
both specific and arbitrary segments of the URL. |
| 415 |
|
| 416 |
Example combining named and wildcard parameters: |
| 417 |
|
| 418 |
# Matches URL: /user/123/files/documents/reports/2023/summary.txt |
| 419 |
get '/user/:id/files/**' => sub { |
| 420 |
my $user_id = route_parameters->get('id'); |
| 421 |
my @files = splat; |
| 422 |
return "User ID: $user_id requested the files: " . join(', ', @files); |
| 423 |
}; |
| 424 |
|
| 425 |
=head3 Named parameters with type constraints |
| 426 |
|
| 427 |
Type constraints allow you to enforce specific types for named |
| 428 |
parameters, ensuring that the parameters meet certain criteria. |
| 429 |
|
| 430 |
Dancer2 natively supports named parameters with type constraints |
| 431 |
without needing to rely on external plugins. Here’s how to declare |
| 432 |
and use type constraints for named route parameters in Dancer2: |
| 433 |
|
| 434 |
use Dancer2; |
| 435 |
|
| 436 |
get '/ride/:id[Int]' => sub { |
| 437 |
my $id = route_parameters->get('id'); |
| 438 |
return "Ride ID: $id"; |
| 439 |
}; |
| 440 |
|
| 441 |
get '/guest/:name[Str]' => sub { |
| 442 |
my $name = route_parameters->get('name'); |
| 443 |
return "Guest Name: $name"; |
| 444 |
}; |
| 445 |
|
| 446 |
MyApp->to_app(); |
| 447 |
|
| 448 |
=over 4 |
| 449 |
|
| 450 |
=item * |
| 451 |
|
| 452 |
B<Int>: This constraint ensures that the C<id> parameter must be an integer. |
| 453 |
|
| 454 |
=item * |
| 455 |
|
| 456 |
B<Str>: This ensures that the C<name> parameter must be a string. |
| 457 |
|
| 458 |
=back |
| 459 |
|
| 460 |
Note: For more complex parameter types, the C<Dancer2::Plugin::ParamTypes> |
| 461 |
module provides additional constraints and validation for all parameter |
| 462 |
types. |
| 463 |
|
| 464 |
=head3 Wildcard Parameters with Type Constraints |
| 465 |
|
| 466 |
You can also enforce type constraints on wildcard parameters: |
| 467 |
|
| 468 |
# Matches URL: /images/photo.jpg |
| 469 |
get '/images/*.*[ArrayRef[Str]]' => sub { |
| 470 |
my ($filename, $extension) = splat; |
| 471 |
return "Filename: $filename, Extension: $extension"; |
| 472 |
}; |
| 473 |
|
| 474 |
# Matches URL: /documents/folder/subfolder/file.txt |
| 475 |
get '/documents/**[ArrayRef[Str]]' => sub { |
| 476 |
my @path = splat; |
| 477 |
return "Document path: " . join('/', @path); |
| 478 |
}; |
| 479 |
|
| 480 |
=head3 Regex Route Matching |
| 481 |
|
| 482 |
Regex route matching allows you to define routes using regular |
| 483 |
expressions, providing more flexibility in matching URLs: |
| 484 |
|
| 485 |
# Matches URL: /product/12345 |
| 486 |
get qr{/product/(\d+)} => sub { |
| 487 |
my ($product_id) = splat; |
| 488 |
return "Product ID: $product_id"; |
| 489 |
}; |
| 490 |
|
| 491 |
# Matches URL: /category/electronics |
| 492 |
get qr{/category/(\w+)} => sub { |
| 493 |
my ($category_name) = splat; |
| 494 |
return "Category: $category_name"; |
| 495 |
}; |
| 496 |
|
| 497 |
It is also possible to use named captures in regular expressions: |
| 498 |
|
| 499 |
# Matches URL: /product/12345 |
| 500 |
get qr{/product/(?<product_id>\d+)} => sub { |
| 501 |
my $product_id = captures->{'product_id'}; |
| 502 |
return "Product ID: $product_id"; |
| 503 |
}; |
| 504 |
|
| 505 |
=head3 Combining Examples |
| 506 |
|
| 507 |
# Matches URL: /item/42/specifications |
| 508 |
get '/item/:id[Int]/*[ArrayRef[Str]]' => sub { |
| 509 |
my $item_id = route_parameters->get('id'); |
| 510 |
my ($detail) = splat; |
| 511 |
return "Item ID: $item_id, Detail: $detail"; |
| 512 |
}; |
| 513 |
|
| 514 |
# Matches URL: /archive/2023/07/10 |
| 515 |
get qr{/archive/(\d{4})/(\d{2})/(\d{2})} => sub { |
| 516 |
my ($year, $month, $day) = splat; |
| 517 |
return "Archive for: $year-$month-$day"; |
| 518 |
}; |
| 519 |
|
| 520 |
=head2 Organizing routes and growing your app using prefix |
| 521 |
|
| 522 |
The prefix DSL keyword helps you group related routes. For example, you |
| 523 |
can organize all the routes of a given section in Danceyland with the |
| 524 |
C<prefix> keyword as such: |
| 525 |
|
| 526 |
package MyApp; |
| 527 |
use Dancer2; |
| 528 |
|
| 529 |
# Prefix for Cinemaland |
| 530 |
prefix '/cinemaland' => sub { |
| 531 |
get '/film-gallery' => sub { |
| 532 |
return "Welcome to Cinemaland! Here you can learn about famous movies."; |
| 533 |
}; |
| 534 |
|
| 535 |
get '/movie-schedule' => sub { |
| 536 |
return "Movie Schedule: 10 AM and 4 PM."; |
| 537 |
}; |
| 538 |
}; |
| 539 |
|
| 540 |
# Prefix for Actionland |
| 541 |
prefix '/actionland' => sub { |
| 542 |
get '/thrill-rides' => sub { |
| 543 |
return "Welcome to Actionland! Enjoy the thrill rides."; |
| 544 |
}; |
| 545 |
|
| 546 |
get '/roller-coaster' => sub { |
| 547 |
return "The best roller coaster in the park!"; |
| 548 |
}; |
| 549 |
}; |
| 550 |
|
| 551 |
MyApp->to_app(); |
| 552 |
|
| 553 |
This example organizes routes by grouping all cinema-related activities |
| 554 |
under C</cinemaland> and all rides under C</actionland>. |
| 555 |
|
| 556 |
=head2 Controlling the flow with forward, redirect, and pass |
| 557 |
|
| 558 |
These DSL keywords in Dancer2 allow you to manage the flow of actions |
| 559 |
within your routes. Here’s how they work in Danceyland. |
| 560 |
|
| 561 |
=head3 forward |
| 562 |
|
| 563 |
C<forward> allows you to forward the current request to another route |
| 564 |
handler, as if it were redirected, but without sending a new HTTP request. |
| 565 |
Put another way, a different route than the one requested is processed, |
| 566 |
but the address in the user's browser's bar stays the same. |
| 567 |
|
| 568 |
=head4 Example |
| 569 |
|
| 570 |
get '/guest-services' => sub { |
| 571 |
forward '/info'; # Forwards to /info |
| 572 |
}; |
| 573 |
|
| 574 |
get '/info' => sub { |
| 575 |
return "Welcome to Guest Services. How can we help you today?"; |
| 576 |
}; |
| 577 |
|
| 578 |
In this example, when a visitor goes to C</guest-services>, they are |
| 579 |
forwarded to the C</info> route internally, however, the vistor's browser |
| 580 |
still shows they are in C</guest-services>. |
| 581 |
|
| 582 |
=head3 redirect |
| 583 |
|
| 584 |
C<redirect> sends an HTTP redirect to the client, instructing their |
| 585 |
browser to make a new request to a different URL. At the end of the |
| 586 |
request, the user's browser will show a different URL than the one |
| 587 |
they originally navigated to. |
| 588 |
|
| 589 |
=head4 Example |
| 590 |
|
| 591 |
get '/old-roller-coaster' => sub { |
| 592 |
redirect '/new-roller-coaster'; |
| 593 |
}; |
| 594 |
|
| 595 |
get '/new-roller-coaster' => sub { |
| 596 |
return "Welcome to the new and improved roller coaster!"; |
| 597 |
}; |
| 598 |
|
| 599 |
When a visitor requests C</old-roller-coaster>, they are redirected to |
| 600 |
C</new-roller-coaster>. The browser's URL will now show C</new-roller-coaster>. |
| 601 |
|
| 602 |
=head3 pass |
| 603 |
|
| 604 |
C<pass> tells Dancer2 to skip the current route and continue looking for |
| 605 |
the next matching route. |
| 606 |
|
| 607 |
=head4 Example |
| 608 |
|
| 609 |
get '/vip-area' => sub { |
| 610 |
if (!session('is_vip')) { |
| 611 |
pass; # Skip to the next matching route if the user is not VIP |
| 612 |
} |
| 613 |
return "Welcome to the VIP area!"; |
| 614 |
}; |
| 615 |
|
| 616 |
get '/vip-area' => sub { |
| 617 |
return "Access Denied. This area is for VIPs only."; |
| 618 |
}; |
| 619 |
|
| 620 |
In this example, if the session doesn’t indicate the user is a VIP, the |
| 621 |
request will skip to the next matching route, which denies access. |
| 622 |
|
| 623 |
=head1 Templates: Displaying Information, and More! |
| 624 |
|
| 625 |
Templates in a web application help present information in a structured |
| 626 |
and visually appealing way, much like maps, schedules, and banners in a |
| 627 |
theme park. |
| 628 |
|
| 629 |
=head2 Why do we use templates? |
| 630 |
|
| 631 |
Templates help separate your display logic from your programming logic. |
| 632 |
The same code that sends JSON to satisfy an API quest could also be used |
| 633 |
to display an HTML page containing park information to a user. If the |
| 634 |
code needed to display HTML is intertwined with the code to gather the |
| 635 |
data needed, the code necessary to just produce JSON becomes unnecessarily |
| 636 |
complicated. Templates take the HTML out of your Perl code. |
| 637 |
|
| 638 |
=head2 Views |
| 639 |
|
| 640 |
In Dancer2, "views" refer to the template files that define the structure |
| 641 |
of the content presented to the users. Views are typically HTML files |
| 642 |
with embedded placeholders that are dynamically filled with data when |
| 643 |
rendered. |
| 644 |
|
| 645 |
=head3 How Views Work |
| 646 |
|
| 647 |
Suppose you have a template file called C<views/ride.tt>: |
| 648 |
|
| 649 |
<h1><% ride_name %> Ride</h1> |
| 650 |
<p>Enjoy the thrilling <% ride_name %> ride at Danceyland!</p> |
| 651 |
|
| 652 |
You can use this view in your route handler: |
| 653 |
|
| 654 |
get '/ride/:name' => sub { |
| 655 |
my $ride_name = route_parameters->get('name'); |
| 656 |
template 'ride' => { ride_name => $ride_name }; |
| 657 |
}; |
| 658 |
|
| 659 |
=head3 Example: Displaying a welcome message on a pretty banner |
| 660 |
|
| 661 |
get '/' => sub { |
| 662 |
template 'welcome', { message => "Welcome to Danceyland!" }; |
| 663 |
}; |
| 664 |
|
| 665 |
In this example, the C</> route uses a template to display a welcome message. |
| 666 |
|
| 667 |
=head3 Example: Displaying the park map |
| 668 |
|
| 669 |
get '/map' => sub { |
| 670 |
template 'map', { attractions => \@attractions }; |
| 671 |
}; |
| 672 |
|
| 673 |
=head3 Example: Using templates to display various information |
| 674 |
|
| 675 |
get '/info' => sub { |
| 676 |
template 'info', { |
| 677 |
title => "Park Information", |
| 678 |
content => "Here you can find all the information about Danceyland.", |
| 679 |
hours => "Open from 10 AM to 8 PM", |
| 680 |
contact => "Call us at 123-456-7890", |
| 681 |
}; |
| 682 |
}; |
| 683 |
|
| 684 |
=over 4 |
| 685 |
|
| 686 |
=item * |
| 687 |
|
| 688 |
The C</> route uses a template to display a welcome message. |
| 689 |
|
| 690 |
=item * |
| 691 |
|
| 692 |
The C</map> route uses a template to display the park's map. |
| 693 |
|
| 694 |
=item * |
| 695 |
|
| 696 |
The C</info> route uses a template to display various pieces of information about the park. |
| 697 |
|
| 698 |
=back |
| 699 |
|
| 700 |
=head2 New Keywords |
| 701 |
|
| 702 |
=head3 template |
| 703 |
|
| 704 |
The C<template> keyword renders a template file with the provided data. |
| 705 |
It takes two parameters: the template name and a hash reference of the |
| 706 |
data to pass to the template. |
| 707 |
|
| 708 |
template 'template_name', { key1 => 'value1', key2 => 'value2' }; |
| 709 |
|
| 710 |
=head2 Layouts |
| 711 |
|
| 712 |
Layouts in Dancer2 allow you to wrap views with a common structure, such |
| 713 |
as a header, footer, or navigation bar, that remains consistent across |
| 714 |
Danceyland. A layout is just another template that wraps around your page |
| 715 |
content; it allows you to maintain a consistent look and feel across |
| 716 |
multiple pages while rendering the dynamic content of each page within |
| 717 |
the layout. |
| 718 |
|
| 719 |
=head3 Example: Implementing Layouts in Danceyland |
| 720 |
|
| 721 |
Consider Danceyland having a consistent navigation bar across all sections |
| 722 |
of the site. You can use a layout for this. |
| 723 |
|
| 724 |
# views/layouts/main.tt |
| 725 |
<!DOCTYPE html> |
| 726 |
<html lang="en"> |
| 727 |
<head> |
| 728 |
<meta charset="UTF-8"> |
| 729 |
<title>Danceyland</title> |
| 730 |
</head> |
| 731 |
<body> |
| 732 |
<header> |
| 733 |
<h1>Welcome to Danceyland</h1> |
| 734 |
<nav> |
| 735 |
<a href="/">Home</a> |
| 736 |
<a href="/cinemaland/film-gallery">Cinemaland</a> |
| 737 |
<a href="/actionland/thrill-rides">Actionland</a> |
| 738 |
</nav> |
| 739 |
</header> |
| 740 |
|
| 741 |
<section> |
| 742 |
<% content %> <!-- This is where the view content gets inserted --> |
| 743 |
</section> |
| 744 |
|
| 745 |
<footer> |
| 746 |
<p>© 2024 Danceyland</p> |
| 747 |
</footer> |
| 748 |
</body> |
| 749 |
</html> |
| 750 |
|
| 751 |
C<content> is a special variable for layouts; it is replaced by the |
| 752 |
output from the C<template> keyword. |
| 753 |
|
| 754 |
=head4 Route Implementation Using the Layout |
| 755 |
|
| 756 |
If you have a separate layouts for park employees and park guests, you |
| 757 |
can explicitly choose which layout should be used to wrap page content: |
| 758 |
|
| 759 |
get '/food-court/burger-stand' => sub { |
| 760 |
template items => { |
| 761 |
foods => \@foods, |
| 762 |
drinks => \@drinks, |
| 763 |
}, { layout => 'main' }; |
| 764 |
}; |
| 765 |
|
| 766 |
get '/cinemaland/change-film-reels' => sub { |
| 767 |
template films => { films => \@films }, { layout => 'employee' }; |
| 768 |
}; |
| 769 |
|
| 770 |
get '/actionland/thrill-rides' => sub { |
| 771 |
template rides => { rides => \@rides }, { layout => 'visitor' }; |
| 772 |
}; |
| 773 |
|
| 774 |
In this example: |
| 775 |
|
| 776 |
=over 4 |
| 777 |
|
| 778 |
=item * |
| 779 |
|
| 780 |
Employees and guests both choose from the same menu, so in the food court, |
| 781 |
they should be presented with the same standard page elements and options. |
| 782 |
|
| 783 |
=item * |
| 784 |
|
| 785 |
Guests of Cinemaland aren't required to change the film reels between |
| 786 |
showings, but park employees are. By specifying a layout of C<employee.tt>, |
| 787 |
they will get a special look and set of options appropriate to park |
| 788 |
workers. The route renders a template (C<films.tt>) within that layout. |
| 789 |
|
| 790 |
=item * |
| 791 |
|
| 792 |
Park visitors interact with rides differently than employees. By |
| 793 |
displaying the C<rides.tt> template within the C<visitor.tt> layout, we |
| 794 |
can help guests board and get off rides with consistent messaging and |
| 795 |
instructions. |
| 796 |
|
| 797 |
=back |
| 798 |
|
| 799 |
This helps maintain consistency across different pages in Danceyland by |
| 800 |
reusing the layout and changing only the dynamic content for each route. |
| 801 |
|
| 802 |
=head3 Default Layout |
| 803 |
|
| 804 |
When no layout is explicitly specified in a route, Dancer2 will use the |
| 805 |
C<main> layout as the default: |
| 806 |
|
| 807 |
get '/home' => sub { |
| 808 |
template 'homepage'; |
| 809 |
}; |
| 810 |
|
| 811 |
In this case, Dancer2 renders C<homepage.tt> within the default layout |
| 812 |
C<main.tt>. |
| 813 |
|
| 814 |
=head3 Disabling Layouts |
| 815 |
|
| 816 |
If you want to render a view without a layout, you can pass |
| 817 |
C<< { layout => undef } >> to the C<template> keyword: |
| 818 |
|
| 819 |
get '/payment-options' => sub { |
| 820 |
template 'payment-options', { }, { layout => undef }; |
| 821 |
}; |
| 822 |
|
| 823 |
This route renders the C<payment-options.tt> template without using the |
| 824 |
default or any specified layout. |
| 825 |
|
| 826 |
=head4 When should I use a layout, and when shouldn't I? |
| 827 |
|
| 828 |
There are three different ways to return data from a Dancer2 app: |
| 829 |
|
| 830 |
=over |
| 831 |
|
| 832 |
=item * |
| 833 |
|
| 834 |
Returning HTML content that represents the entire content of the page |
| 835 |
(and allowing the browser to render it) |
| 836 |
|
| 837 |
=item * |
| 838 |
|
| 839 |
HTML content for only a portion of the page (using JS to insert that HTML |
| 840 |
dynamically in the page, and the browser then takes over rendering it) |
| 841 |
|
| 842 |
=item * |
| 843 |
|
| 844 |
JSON/XML/etc. content that the JS decides what to do with, possibly |
| 845 |
rendering some front-end template and updating the DOM nodes |
| 846 |
|
| 847 |
=back |
| 848 |
|
| 849 |
For option 1, you would use a layout to ensure a full HTML page is |
| 850 |
returned. For option 2, you would disable the layout. In option 3, |
| 851 |
you would serialize a data structure returned from a route. |
| 852 |
|
| 853 |
The benefit of returning a part of a HTML page (option 2) is when: |
| 854 |
|
| 855 |
=over |
| 856 |
|
| 857 |
=item * |
| 858 |
|
| 859 |
You don't want to render the entire page in the backend |
| 860 |
|
| 861 |
=item * |
| 862 |
|
| 863 |
You don't want to fetch all the data for the entire page (imagine menus, |
| 864 |
headers, etc.) |
| 865 |
|
| 866 |
=item * |
| 867 |
|
| 868 |
You prefer to inject the HTML directly to an element, reducing front-end |
| 869 |
complexity |
| 870 |
|
| 871 |
=back |
| 872 |
|
| 873 |
If you are building interfaces with toolkits like L<htmx|https://htmx.org/> or |
| 874 |
L<Turbo|https://turbo.hotwired.dev/>, it's important to only return |
| 875 |
a partial page. |
| 876 |
|
| 877 |
=head2 Default template variables |
| 878 |
|
| 879 |
=over |
| 880 |
|
| 881 |
=item perl_version |
| 882 |
|
| 883 |
The version of Perl that's running Danceyland. This aligns with Perl's |
| 884 |
special C<$^V> variable. |
| 885 |
|
| 886 |
=item dancer_version |
| 887 |
|
| 888 |
The current version of Dancer2. Similar to C<< Dancer2->VERSION >>. |
| 889 |
|
| 890 |
=item settings |
| 891 |
|
| 892 |
This is a hash containing the configuration of Danceyland. |
| 893 |
|
| 894 |
=item request |
| 895 |
|
| 896 |
This represents the user's current request. Calling C<request> returns |
| 897 |
a L<Dancer2::Core::Request> object. |
| 898 |
|
| 899 |
=item params |
| 900 |
|
| 901 |
C<params> provides a hash reference of all parameters passed to Danceyland. |
| 902 |
|
| 903 |
=item vars |
| 904 |
|
| 905 |
This is the list of variables for this request. It is the same thing you |
| 906 |
would get if you used the C<vars> keyword in the application itself. We'll |
| 907 |
learn more about C<vars> in the L</Configuration> section. |
| 908 |
|
| 909 |
=item session |
| 910 |
|
| 911 |
This variable contains all information in the user's session, should one |
| 912 |
exist. We'll talk more about sessions in the next section. |
| 913 |
|
| 914 |
=back |
| 915 |
|
| 916 |
=head2 Configuring the Template Engine |
| 917 |
|
| 918 |
You can configure the template engine in Dancer2 to customize aspects |
| 919 |
such as the open and closing tags used for placeholders. |
| 920 |
|
| 921 |
=head3 Changing Open and Closing Tags |
| 922 |
|
| 923 |
In your configuration file (e.g., C<config.yml>), you can set the |
| 924 |
C<start_tag> and C<stop_tag> options: |
| 925 |
|
| 926 |
template: "template_toolkit" |
| 927 |
engines: |
| 928 |
template: |
| 929 |
template_toolkit: |
| 930 |
start_tag: '[%' |
| 931 |
stop_tag: '%]' |
| 932 |
|
| 933 |
Dancer2 defaults placeholder tags to C<< <% %> >>. The above configuration |
| 934 |
restores the Template toolkit defaults of C<< [% %] >>. Your template |
| 935 |
variables will now look like this: |
| 936 |
|
| 937 |
<h1>[% title %]</h1> |
| 938 |
<p>Welcome to Danceyland!</p> |
| 939 |
|
| 940 |
Most template engines support this functionality, but some (such as |
| 941 |
L<Dancer2::Template::Tiny>) do not. |
| 942 |
|
| 943 |
=head2 Encoding in Templates |
| 944 |
|
| 945 |
Dancer2 supports encoding for templates to ensure that the content is |
| 946 |
correctly displayed, especially when dealing with non-ASCII characters: |
| 947 |
|
| 948 |
template: "template_toolkit" |
| 949 |
engines: |
| 950 |
template: |
| 951 |
template_toolkit: |
| 952 |
encoding: 'utf-8' |
| 953 |
|
| 954 |
This configuration ensures that the templates are processed using UTF-8 |
| 955 |
encoding. This is particularly important if your templates contain |
| 956 |
special characters, such as international text or symbols. |
| 957 |
|
| 958 |
=head3 New Keywords |
| 959 |
|
| 960 |
=over |
| 961 |
|
| 962 |
=item * engine |
| 963 |
|
| 964 |
At the heart of every attraction in Danceyland lies a powerful engine that |
| 965 |
brings it to life. Similarly, in Dancer2, the C<engine> keyword provides |
| 966 |
access to the current engine object, whether it's the template engine |
| 967 |
rendering the views or the logger keeping track of events: |
| 968 |
|
| 969 |
my $template_engine = engine 'template'; |
| 970 |
|
| 971 |
=back |
| 972 |
|
| 973 |
=head2 Comparison of Supported Template Engines |
| 974 |
|
| 975 |
Dancer2 supports various template engines to give you flexibility in how |
| 976 |
you render views. Here's a brief comparison of the available engines: |
| 977 |
|
| 978 |
=over 4 |
| 979 |
|
| 980 |
=item Dancer2::Template::TemplateToolkit (L<Template> Toolkit, TT) |
| 981 |
|
| 982 |
A powerful and flexible templating system with extensive features like |
| 983 |
loops, conditions, macros, and plugins. Suitable for complex templating |
| 984 |
needs. |
| 985 |
|
| 986 |
=item Dancer2::Template::Mason (L<Mason>) |
| 987 |
|
| 988 |
A component-based templating system that allows embedding Perl code |
| 989 |
within templates. Ideal for complex web applications that require |
| 990 |
reusable components. |
| 991 |
|
| 992 |
=item Dancer2::Template::Xslate (L<Xslate>) |
| 993 |
|
| 994 |
A high-performance templating engine that offers a mix of syntax styles. |
| 995 |
Great for applications requiring speed and flexibility. |
| 996 |
|
| 997 |
=item Dancer2::Template::TemplateFlute (L<Flute>) |
| 998 |
|
| 999 |
A template engine focused on separating logic from presentation. |
| 1000 |
Templates contain no logic and are designer-friendly. |
| 1001 |
|
| 1002 |
=item Dancer2::Template::Tiny (L<Template::Tiny>) |
| 1003 |
|
| 1004 |
A minimalistic template engine with limited features. Suitable for small |
| 1005 |
projects or when you need a simple, lightweight option. |
| 1006 |
|
| 1007 |
=item Dancer2::Template::Simple |
| 1008 |
|
| 1009 |
A basic and straightforward templating engine. Not recommended unless you |
| 1010 |
are migrating applications from Dancer 1 built with L<Dancer::Template::Simple>. |
| 1011 |
|
| 1012 |
=item Dancer2::Template::Mustache (L<Mustache:https://mustache.github.io/>, L<Dancer2::Template::Mustache>) |
| 1013 |
|
| 1014 |
A logic-less template engine with a strong emphasis on separation of |
| 1015 |
logic and presentation. Great for consistent rendering across different |
| 1016 |
languages and platforms. |
| 1017 |
|
| 1018 |
=item Dancer2::Template::Handlebars (L<Handlebars|>, L<Text::Handlebars>) |
| 1019 |
|
| 1020 |
An extension of Mustache with additional features like helpers and more |
| 1021 |
expressive templates. Ideal for complex templates that still maintain a |
| 1022 |
clean and readable structure. |
| 1023 |
|
| 1024 |
=item B<Dancer2::Template::Haml> (L<HAML|https://haml.info/>, L<Text::Haml>) |
| 1025 |
|
| 1026 |
A clean and concise templating system that uses indentation to define |
| 1027 |
HTML elements. Perfect for those who prefer a more human-readable |
| 1028 |
approach to HTML templating. |
| 1029 |
|
| 1030 |
=back |
| 1031 |
|
| 1032 |
Choose a template engine based on the complexity and requirements of your |
| 1033 |
Danceyland application. |
| 1034 |
|
| 1035 |
=head1 Sessions: Multi-Day Passes |
| 1036 |
|
| 1037 |
Sessions are like multi-day or season passes for visitors. They allow |
| 1038 |
visitors to return to the park multiple times without having to buy a |
| 1039 |
new ticket each time. |
| 1040 |
|
| 1041 |
=head2 The importance of state |
| 1042 |
|
| 1043 |
HTTP and HTTPS are stateless protocols, meaning each request from a |
| 1044 |
client to a server is independent. The server processes each request |
| 1045 |
and responds, but it doesn’t remember past interactions. Therefore, each |
| 1046 |
new request must include all necessary information, as the server doesn’t |
| 1047 |
retain any “state” between requests — this is something developers must |
| 1048 |
implement if needed. |
| 1049 |
|
| 1050 |
This lack of memory between requests is why web frameworks use B<session |
| 1051 |
management>. Sessions allow servers to remember users' actions across |
| 1052 |
multiple requests, creating a sense of continuity, or "state." To do |
| 1053 |
this, web frameworks often rely on B<cookies> — small pieces of data stored |
| 1054 |
in the browser. When a client connects, the server assigns a unique |
| 1055 |
session ID stored in a cookie, which the browser sends with each request. |
| 1056 |
This session ID allows the server to "remember" the user's previous |
| 1057 |
interactions, making it possible to build personalized and seamless web |
| 1058 |
experiences. |
| 1059 |
|
| 1060 |
The following section explains how to manage sessions with Dancer2. |
| 1061 |
|
| 1062 |
=head2 Managing visitor sessions |
| 1063 |
|
| 1064 |
To create or update a session, use the C<session> keyword. Sessions store |
| 1065 |
data across multiple requests using a unique session ID. |
| 1066 |
|
| 1067 |
set session => 'Simple'; |
| 1068 |
|
| 1069 |
get '/login' => sub { |
| 1070 |
session user => 'John Doe'; |
| 1071 |
return "Welcome back, John Doe!"; |
| 1072 |
}; |
| 1073 |
|
| 1074 |
get '/profile' => sub { |
| 1075 |
my $user = session('user'); |
| 1076 |
return "User profile for: $user"; |
| 1077 |
}; |
| 1078 |
|
| 1079 |
=over 4 |
| 1080 |
|
| 1081 |
=item * |
| 1082 |
|
| 1083 |
A session stores the user information once they log in. |
| 1084 |
|
| 1085 |
=item * |
| 1086 |
|
| 1087 |
The C</login> route initiates a session for the user. |
| 1088 |
|
| 1089 |
=item * |
| 1090 |
|
| 1091 |
The C</profile> route retrieves the user information from the session. |
| 1092 |
|
| 1093 |
=back |
| 1094 |
|
| 1095 |
=head3 New Keywords |
| 1096 |
|
| 1097 |
=over 4 |
| 1098 |
|
| 1099 |
=item set |
| 1100 |
|
| 1101 |
This keyword is used to configure settings for your application, like setting the session engine: |
| 1102 |
|
| 1103 |
set session => 'Simple'; |
| 1104 |
|
| 1105 |
=item session |
| 1106 |
|
| 1107 |
This keyword is used to store and retrieve session data: |
| 1108 |
|
| 1109 |
session user => 'John Doe'; # Store data |
| 1110 |
my $user_1 = session('user'); # Retrieve data |
| 1111 |
my $user_2 = session->read('user'); # Also retrieves data |
| 1112 |
|
| 1113 |
=back |
| 1114 |
|
| 1115 |
=head3 Changing the Session ID |
| 1116 |
|
| 1117 |
For security reasons, you might want to change the session ID, especially |
| 1118 |
after a user logs in. This can help prevent L<session fixation attacks|https://owasp.org/www-community/attacks/Session_fixation>. |
| 1119 |
|
| 1120 |
get '/secure-login' => sub { |
| 1121 |
my $username = body_parameters->get( 'username' ); |
| 1122 |
session user => $username; |
| 1123 |
app->change_session_id; # Change the session ID |
| 1124 |
return "Welcome back, $username!"; |
| 1125 |
}; |
| 1126 |
|
| 1127 |
=head3 Destroying Sessions |
| 1128 |
|
| 1129 |
To log the user out and destroy the session, use the C<< app->destroy_session >>. |
| 1130 |
|
| 1131 |
get '/logout' => sub { |
| 1132 |
app->destroy_session; |
| 1133 |
return "You have been logged out."; |
| 1134 |
}; |
| 1135 |
|
| 1136 |
=head2 Configuring the Session Engine |
| 1137 |
|
| 1138 |
Dancer2 supports various session engines that determine how and where |
| 1139 |
session data is stored. You can configure the session engine in the |
| 1140 |
C<config.yml> file: |
| 1141 |
|
| 1142 |
session: "Simple" |
| 1143 |
session_options: |
| 1144 |
cookie_name: "danceyland_session" |
| 1145 |
expires: 3600 |
| 1146 |
|
| 1147 |
This configuration uses the C<Simple> session engine, storing session |
| 1148 |
data in memory, and sets the session to expire in one hour. |
| 1149 |
|
| 1150 |
=head2 Session Storage Backends |
| 1151 |
|
| 1152 |
Dancer2 supports multiple session storage backends, allowing you to |
| 1153 |
choose how and where to store session data. |
| 1154 |
|
| 1155 |
=over 4 |
| 1156 |
|
| 1157 |
=item Dancer2::Session::Simple |
| 1158 |
|
| 1159 |
Stores session data in memory. Suitable for development and testing but |
| 1160 |
not recommended for production due to its non-persistent nature. |
| 1161 |
|
| 1162 |
=item Dancer2::Session::YAML |
| 1163 |
|
| 1164 |
Stores session data in a YAML file. It's useful for development and |
| 1165 |
debugging, but not well suited for production. |
| 1166 |
|
| 1167 |
=item Dancer2::Session::JSON |
| 1168 |
|
| 1169 |
Stores session data in a JSON file. Similar restrictions to the YAML |
| 1170 |
session engine. |
| 1171 |
|
| 1172 |
=item Dancer2::Session::Cookie |
| 1173 |
|
| 1174 |
Stores session data within the user's browser as a cookie. Data is not |
| 1175 |
stored server-side. Good for lightweight sessions. |
| 1176 |
|
| 1177 |
=item Dancer2::Session::PSGI |
| 1178 |
|
| 1179 |
Leverages PSGI's built-in session management. Useful if you want to |
| 1180 |
delegate session handling to the PSGI server, or if you are sharing |
| 1181 |
session data with non-Dancer2 applications. |
| 1182 |
|
| 1183 |
=item Dancer2::Session::DBI |
| 1184 |
|
| 1185 |
Stores session data in a database using L<DBI>. Ideal for larger |
| 1186 |
applications that require a robust and scalable storage solution. |
| 1187 |
|
| 1188 |
=item Dancer2::Session::Redis |
| 1189 |
|
| 1190 |
Stores session data in a Redis database. Suitable for high-performance, |
| 1191 |
distributed, and scalable session storage. |
| 1192 |
|
| 1193 |
=item Dancer2::Session::Sereal |
| 1194 |
|
| 1195 |
Uses Sereal for fast, compact session serialization. Suitable for |
| 1196 |
high-performance applications requiring efficient serialization. |
| 1197 |
|
| 1198 |
=item Dancer2::Session::CHI |
| 1199 |
|
| 1200 |
Uses the L<CHI> caching framework for session storage. Flexible and |
| 1201 |
supports various caching backends like memory, file, and databases. |
| 1202 |
|
| 1203 |
=item Dancer2::Session::Memcached |
| 1204 |
|
| 1205 |
Stores session data in a Memcached server. Suitable for distributed |
| 1206 |
environments requiring quick access to session data. |
| 1207 |
|
| 1208 |
=item Dancer2::Session::MongoDB |
| 1209 |
|
| 1210 |
Stores session data in a MongoDB database. Ideal for applications |
| 1211 |
requiring a NoSQL storage solution. |
| 1212 |
|
| 1213 |
=back |
| 1214 |
|
| 1215 |
Choose a session backend based on the complexity and storage needs of |
| 1216 |
your Danceyland application. |
| 1217 |
|
| 1218 |
=head1 Cookies |
| 1219 |
|
| 1220 |
Cookies are small pieces of data stored on the client's browser, not just |
| 1221 |
goodies available for purchase in Danceyland. They are often used to keep |
| 1222 |
track of session information and user preferences. |
| 1223 |
|
| 1224 |
Sessions in Dancer2 use cookies to store the session ID on the client's |
| 1225 |
browser. |
| 1226 |
|
| 1227 |
=head2 Setting and Updating Cookies |
| 1228 |
|
| 1229 |
You can set a cookie using the C<cookie> keyword. To update a cookie, |
| 1230 |
simply set it again with a new value: |
| 1231 |
|
| 1232 |
get '/set-cookie' => sub { |
| 1233 |
cookie 'visitor' => 'regular'; |
| 1234 |
return "Cookie has been set!"; |
| 1235 |
}; |
| 1236 |
|
| 1237 |
This route sets a cookie named C<visitor> with the value C<regular>. |
| 1238 |
|
| 1239 |
=head2 Retrieving Cookies |
| 1240 |
|
| 1241 |
To retrieve a cookie, use the C<cookie> keyword with the cookie's name: |
| 1242 |
|
| 1243 |
get '/get-cookie' => sub { |
| 1244 |
my $visitor_type = cookie('visitor'); |
| 1245 |
return "Visitor type: $visitor_type"; |
| 1246 |
}; |
| 1247 |
|
| 1248 |
This route retrieves the value of the C<visitor> cookie. |
| 1249 |
|
| 1250 |
To retrieve all cookies, use the C<cookies> keyword: |
| 1251 |
|
| 1252 |
get '/check-cookies' => sub { |
| 1253 |
my $cookies = cookies; |
| 1254 |
for my $name ( keys $cookies->%* ) { |
| 1255 |
debug "You have a cookie named $name"; |
| 1256 |
# Do other stuff... |
| 1257 |
} |
| 1258 |
} |
| 1259 |
|
| 1260 |
=head2 Multiple Values Per Cookie |
| 1261 |
|
| 1262 |
Cookie values can be multi-valued. C<cookie('name')> returns the first value |
| 1263 |
in scalar context and all values in list context. |
| 1264 |
|
| 1265 |
my $visitor = cookie('visitor'); # single value |
| 1266 |
my @visitors = cookie('visitor'); # multiple values (list context) |
| 1267 |
|
| 1268 |
However, you can also call the methods C<value> (for either scalar/list |
| 1269 |
contexts), or C<values> for list only context: |
| 1270 |
|
| 1271 |
my $cookie = cookies->{'name'}; |
| 1272 |
my $visitor = $cookie->value(); |
| 1273 |
my @visitors = $cookies->values(); |
| 1274 |
|
| 1275 |
# this also works, similar to the DSL keyword 'cookie' |
| 1276 |
my @visitors = $cookie->value(); |
| 1277 |
|
| 1278 |
=head2 Deleting Cookies |
| 1279 |
|
| 1280 |
To delete a cookie, set it with an expiration time in the past: |
| 1281 |
|
| 1282 |
get '/delete-cookie' => sub { |
| 1283 |
cookie 'visitor' => 'expired', expires => '-1d'; |
| 1284 |
return "Cookie has been deleted."; |
| 1285 |
}; |
| 1286 |
|
| 1287 |
This route deletes the C<visitor> cookie by setting its expiration date |
| 1288 |
to a past date. |
| 1289 |
|
| 1290 |
=head1 Error Handling: Managing Ride Breakdowns and Other Park Issues |
| 1291 |
|
| 1292 |
Just like managing ride breakdowns or out-of-stock concessions in a theme |
| 1293 |
park, error handling in a web application involves dealing with unexpected |
| 1294 |
issues gracefully. |
| 1295 |
|
| 1296 |
=head2 Why should we fail gracefully? |
| 1297 |
|
| 1298 |
Regardless if a problem is one we can control or not, not handling a problem |
| 1299 |
|
| 1300 |
Whether or not a problem is one we can predict, handing errors in a poor |
| 1301 |
or disruptive way can really ruin a visitor's day at the park. It may not |
| 1302 |
be as rude as the pretzel vendor that yells at you for not leaving a tip, |
| 1303 |
but it can certainly sour a vistor for future visits. |
| 1304 |
|
| 1305 |
Errors happen. Handling errors in a predictable, friendly manner can make |
| 1306 |
all the difference. Give visitors a friendly message that explains what |
| 1307 |
went wrong, and if you can still provide them with some limited park |
| 1308 |
functionality, then do so. |
| 1309 |
|
| 1310 |
=head3 500 - the error of last resort |
| 1311 |
|
| 1312 |
When a 500 error occurs, either it means the park operators didn't think |
| 1313 |
to check for a particular error, or something absolutely unpredictable |
| 1314 |
happened (a gust of wind knocked a tree branch across a park walkway). |
| 1315 |
|
| 1316 |
When issuing a 500 error, try not to give away too much information (such |
| 1317 |
as a stack trace) so as to not give a potential attacker too much |
| 1318 |
information. |
| 1319 |
|
| 1320 |
Try to catch as many things as you can. Sending a 500 error isn't the |
| 1321 |
end of park operations, but they should show up sparingly, at worst. |
| 1322 |
|
| 1323 |
=head3 Handling Errors When a Ride is Closed |
| 1324 |
|
| 1325 |
get '/roller-coaster' => sub { |
| 1326 |
status 'service_unavailable'; |
| 1327 |
return "Sorry, the roller coaster is currently closed for maintenance."; |
| 1328 |
}; |
| 1329 |
|
| 1330 |
This route catches the request to the roller coaster when it's closed |
| 1331 |
and returns a friendly error message. |
| 1332 |
|
| 1333 |
=head2 Error Pages |
| 1334 |
|
| 1335 |
You can define custom error pages to provide a friendly message to your |
| 1336 |
users when something goes wrong. |
| 1337 |
|
| 1338 |
To create a custom error page, place a template in the C<views> directory |
| 1339 |
named after the error code, like C<views/404.tt>: |
| 1340 |
|
| 1341 |
<h1>Oops! Page Not Found</h1> |
| 1342 |
<p>The page you are looking for does not exist in Danceyland.</p> |
| 1343 |
|
| 1344 |
This custom page will be displayed whenever a 404 error occurs. |
| 1345 |
|
| 1346 |
=head2 New Keywords |
| 1347 |
|
| 1348 |
=over 4 |
| 1349 |
|
| 1350 |
=item status |
| 1351 |
|
| 1352 |
Status sets the HTTP status code that is returned by response from |
| 1353 |
Dancer2. It can be specified as either a number (C<status 404>), or |
| 1354 |
its lower-case name (C<status 'not_found'>). |
| 1355 |
|
| 1356 |
=item halt |
| 1357 |
|
| 1358 |
The C<halt> keyword immediately stops the processing of the current route |
| 1359 |
and sends a response back to the client: |
| 1360 |
|
| 1361 |
get '/restricted' => sub { |
| 1362 |
halt "Access denied!" unless session('is_admin'); |
| 1363 |
return "Welcome to the restricted area."; |
| 1364 |
}; |
| 1365 |
|
| 1366 |
In this example, if the visitor is not an admin, C<halt> stops execution |
| 1367 |
and returns C<Access denied!>. |
| 1368 |
|
| 1369 |
=item send_error |
| 1370 |
|
| 1371 |
The C<send_error> keyword sends an error response with a specific status |
| 1372 |
code: |
| 1373 |
|
| 1374 |
get '/data' => sub { |
| 1375 |
my $data = fetch_data(); |
| 1376 |
send_error "Data not found", 404 unless $data; |
| 1377 |
return $data; |
| 1378 |
}; |
| 1379 |
|
| 1380 |
This example sends a 404 error response if the data is not found. |
| 1381 |
|
| 1382 |
=back |
| 1383 |
|
| 1384 |
=head1 Static Files and File Uploads |
| 1385 |
|
| 1386 |
In Danceyland, we don't just offer thrilling rides; we also serve files! |
| 1387 |
Whether you’re providing a downloadable park map or processing guest |
| 1388 |
photo uploads, Dancer2 has you covered. |
| 1389 |
|
| 1390 |
=head2 Serving Static Files from Dancer2 |
| 1391 |
|
| 1392 |
Sometimes you want to make certain information (in the form of files) |
| 1393 |
available to visitors without asking them to stand in line. Dancer2 makes |
| 1394 |
serving static files easy. |
| 1395 |
|
| 1396 |
=head3 From a Directory |
| 1397 |
|
| 1398 |
By default, Dancer2 serves static files from the C<public> directory in |
| 1399 |
your app. Just place your files (like images or PDFs) in the C<public> |
| 1400 |
folder, and they’ll be accessible at C</static/path>: |
| 1401 |
|
| 1402 |
# Access the file public/images/logo.png via |
| 1403 |
http://danceyland.local/static/images/logo.png |
| 1404 |
|
| 1405 |
=head3 Sending Static Files from a Route Handler |
| 1406 |
|
| 1407 |
You can also serve static files programmatically from a route handler |
| 1408 |
using C<send_file>: |
| 1409 |
|
| 1410 |
get '/download-map' => sub { |
| 1411 |
send_file 'park-map.pdf', content_type => 'application/pdf'; |
| 1412 |
}; |
| 1413 |
|
| 1414 |
Using C<send_file> immediately exits the current route. |
| 1415 |
|
| 1416 |
=head3 When Might You Not Want to Serve Static Files? |
| 1417 |
|
| 1418 |
While serving static files is convenient, there are times when you may |
| 1419 |
not want to do it directly: |
| 1420 |
|
| 1421 |
=over 4 |
| 1422 |
|
| 1423 |
=item * |
| 1424 |
|
| 1425 |
You want to offload static content delivery to a CDN (Content Delivery |
| 1426 |
Network) for performance. |
| 1427 |
|
| 1428 |
=item * |
| 1429 |
|
| 1430 |
You need fine-grained access control on your files. |
| 1431 |
|
| 1432 |
=item * |
| 1433 |
|
| 1434 |
Your static content is large or frequently changing, and you'd prefer a |
| 1435 |
more scalable solution. |
| 1436 |
|
| 1437 |
=back |
| 1438 |
|
| 1439 |
=head3 How to Disable Static File Serving |
| 1440 |
|
| 1441 |
If you'd prefer not to serve static files from your Dancer2 app, you can |
| 1442 |
disable it in your C<config.yml> file: |
| 1443 |
|
| 1444 |
static: 0 |
| 1445 |
|
| 1446 |
Now, all file requests will be routed through your handlers or passed |
| 1447 |
to another service. |
| 1448 |
|
| 1449 |
=head2 Using C<send_file> to Deliver Files from Memory |
| 1450 |
|
| 1451 |
You’re not limited to files on disk! You can use C<send_file> to deliver |
| 1452 |
files created or stored in memory: |
| 1453 |
|
| 1454 |
get '/dynamic-file' => sub { |
| 1455 |
my $data = "This is a dynamically generated file."; |
| 1456 |
return send_file(\$data, content_type => 'text/plain', filename => 'dynamic.txt'); |
| 1457 |
}; |
| 1458 |
|
| 1459 |
In this example, we generate a file on-the-fly and send it back to the user. |
| 1460 |
|
| 1461 |
=head2 Handling File Uploads |
| 1462 |
|
| 1463 |
If guests are submitting photos or other files at Danceyland, you'll |
| 1464 |
need to handle file uploads. Dancer2 makes it easy with the C<upload> keyword: |
| 1465 |
|
| 1466 |
post '/upload-photo' => sub { |
| 1467 |
my $upload = upload('photo'); |
| 1468 |
return "No file uploaded" unless $upload; |
| 1469 |
|
| 1470 |
my $filename = $upload->filename; |
| 1471 |
my $filehandle = $upload->file_handle; |
| 1472 |
open my $out, '>', "/uploads/$filename" or die "Failed to open: $!"; |
| 1473 |
while (<$filehandle>) { |
| 1474 |
print $out $_; |
| 1475 |
} |
| 1476 |
close $out; |
| 1477 |
|
| 1478 |
return "Uploaded $filename successfully!"; |
| 1479 |
}; |
| 1480 |
|
| 1481 |
=head2 Working with Paths and Directories |
| 1482 |
|
| 1483 |
Dancer2 provides keywords for navigating paths and directories, similar |
| 1484 |
to navigating Danceyland. |
| 1485 |
|
| 1486 |
=head3 path |
| 1487 |
|
| 1488 |
Navigating through Danceyland requires clear paths and an understanding |
| 1489 |
of the surroundings. In Dancer2, the C<path> keyword allows you to |
| 1490 |
create a path from several different directories: |
| 1491 |
use Dancer2; |
| 1492 |
|
| 1493 |
get '/attraction/:name' => sub { |
| 1494 |
my $current_path = path( '/the', 'road', 'less', 'traveled' ); |
| 1495 |
return "You're visiting: $current_path"; |
| 1496 |
}; |
| 1497 |
|
| 1498 |
=head3 dirname |
| 1499 |
|
| 1500 |
Given a path through Danceyland, like above, C<dirname> will tell you the |
| 1501 |
directory you are located in: |
| 1502 |
|
| 1503 |
use Dancer2; |
| 1504 |
|
| 1505 |
get '/resource' => sub { |
| 1506 |
my $file_path = '/path/to/danceyland/config.yml'; |
| 1507 |
my $directory = dirname($file_path); |
| 1508 |
return "Config file is located in: $directory"; |
| 1509 |
}; |
| 1510 |
|
| 1511 |
=head2 Keywords Covered |
| 1512 |
|
| 1513 |
=over |
| 1514 |
|
| 1515 |
=item send_file |
| 1516 |
|
| 1517 |
Used to send a file, either from disk or memory, to the client. |
| 1518 |
|
| 1519 |
=item upload |
| 1520 |
|
| 1521 |
Used to retrieve an uploaded file. |
| 1522 |
|
| 1523 |
=back |
| 1524 |
|
| 1525 |
=head1 Configuration, Startup, Initialization, Versioning |
| 1526 |
|
| 1527 |
Danceyland needs its rides and attractions to work just right, and so |
| 1528 |
does your Dancer2 app. Configuration is key to ensuring your app runs |
| 1529 |
smoothly in every environment. |
| 1530 |
|
| 1531 |
=head2 How Do Environments Help Us Configure Our Applications? |
| 1532 |
|
| 1533 |
Dancer2 uses environments (such as C<development> or C<production>) to |
| 1534 |
customize configuration depending on where the app is running. This |
| 1535 |
allows you to tweak things like logging, error reporting, or even |
| 1536 |
database connections, based on your environment. |
| 1537 |
|
| 1538 |
environments: |
| 1539 |
development: |
| 1540 |
logger: "console" |
| 1541 |
show_errors: 1 |
| 1542 |
production: |
| 1543 |
logger: "file" |
| 1544 |
show_errors: 0 |
| 1545 |
|
| 1546 |
All of your applications will use F<config.yml>, which is the base |
| 1547 |
configuration across B<all> of your application's environments. It is |
| 1548 |
here where you will configure such things as your template engine and |
| 1549 |
other extensions/settomgs that do not change across environments. |
| 1550 |
|
| 1551 |
=head2 Using Environment-Specific Config Files |
| 1552 |
|
| 1553 |
You can create environment-specific config files, like C<production.yml> |
| 1554 |
and C<development.yml>, in the F<environments> directory. Dancer2 will |
| 1555 |
load the environment-specific file after the main config, applying those |
| 1556 |
settings last. |
| 1557 |
|
| 1558 |
You are not limited to the environment names used; different projects and |
| 1559 |
companies will have different requirements and different environments. |
| 1560 |
|
| 1561 |
Applications are not limited to YAML-based configuration files. Dancer2 |
| 1562 |
supports config files in any format supported by L<Config::Any>, including |
| 1563 |
JSON and Apache-style configs. |
| 1564 |
|
| 1565 |
=head2 Config File Resolution Order |
| 1566 |
|
| 1567 |
Dancer2 resolves configuration in the following order: |
| 1568 |
|
| 1569 |
=over 4 |
| 1570 |
|
| 1571 |
=item * |
| 1572 |
|
| 1573 |
C<config.yml> |
| 1574 |
|
| 1575 |
=item * |
| 1576 |
|
| 1577 |
Environment-specific config (e.g., C<environments/development.yml>) |
| 1578 |
|
| 1579 |
=item * |
| 1580 |
|
| 1581 |
Settings in the environment or explicitly set during runtime (using the |
| 1582 |
C<set> keyword) |
| 1583 |
|
| 1584 |
=back |
| 1585 |
|
| 1586 |
=head2 Accessing Configuration Information |
| 1587 |
|
| 1588 |
You can access configuration values in your app using the C<config> keyword. |
| 1589 |
|
| 1590 |
Example: |
| 1591 |
|
| 1592 |
get '/info' => sub { |
| 1593 |
my $app_name = config->{'appname'}; |
| 1594 |
return "Welcome to $app_name!"; |
| 1595 |
}; |
| 1596 |
|
| 1597 |
=head2 Using C<set> Explicitly |
| 1598 |
|
| 1599 |
You can explicitly set configuration values using the C<set> keyword. |
| 1600 |
|
| 1601 |
Example: |
| 1602 |
|
| 1603 |
set session => 'Simple'; |
| 1604 |
set logger => 'console'; |
| 1605 |
|
| 1606 |
=head2 Plugin Configuration |
| 1607 |
|
| 1608 |
You can configure plugins in your C<config.yml> file under the C<plugins> section. |
| 1609 |
|
| 1610 |
Example: |
| 1611 |
|
| 1612 |
plugins: |
| 1613 |
Database: |
| 1614 |
driver: 'SQLite' |
| 1615 |
database: 'danceyland.db' |
| 1616 |
|
| 1617 |
=head2 Startup and Initialization |
| 1618 |
|
| 1619 |
Some keywords can help prepare Danceyland to start operations in the morning, |
| 1620 |
while others offer you insider access to critical areas of the park. Let's |
| 1621 |
take a look at what some of these are, |
| 1622 |
|
| 1623 |
=head3 Accessing the Application Object |
| 1624 |
|
| 1625 |
Sometimes, you really have to get your hands dirty and go behind the scenes |
| 1626 |
of things at Danceyland. The C<app> keyword gives you access to the |
| 1627 |
application object (of type L<Dancer2::Core::App>) to change configuration |
| 1628 |
or perform certain functions. Another keyword, C<dancer_app>, also lets you |
| 1629 |
access the application object. |
| 1630 |
|
| 1631 |
=head3 Running Code at Startup |
| 1632 |
|
| 1633 |
The C<prepare_app> keyword takes a coderef that will be run once at the |
| 1634 |
start of your application. If there is any one-time setup that needs to |
| 1635 |
be performed (like starting up another service, connecting to a service, |
| 1636 |
initializing a cache, etc.), C<prepare_app> will give you a place to do |
| 1637 |
this. |
| 1638 |
|
| 1639 |
For example: |
| 1640 |
|
| 1641 |
prepare_app { |
| 1642 |
debug "Starting our morning prep work"; |
| 1643 |
$rides->power_on(); |
| 1644 |
$vendors->prep_food(); |
| 1645 |
debug "Open for business!"; |
| 1646 |
}; |
| 1647 |
|
| 1648 |
=head3 Starting the Application |
| 1649 |
|
| 1650 |
The traditional way of kicking things off at Danceyland was to, well, dance! |
| 1651 |
|
| 1652 |
use Dancer2; |
| 1653 |
|
| 1654 |
get '/' => sub { |
| 1655 |
return 'Welcome to Danceyland!'; |
| 1656 |
}; |
| 1657 |
|
| 1658 |
dance; |
| 1659 |
|
| 1660 |
As time passed and things changed, dancing wasn't always the right way |
| 1661 |
to start the day. C<to_app> became tbe better and preferred way to start |
| 1662 |
our Dancer2 applications. C<psgi_app> may also be used. |
| 1663 |
|
| 1664 |
=head3 Versioning and Compatibility |
| 1665 |
|
| 1666 |
As Danceyland introduces new attractions, it's essential to ensure they |
| 1667 |
align with the park's current standards. In the realm of Dancer2, you can |
| 1668 |
use C<dancer_version> to retrieve the full version number of your framework, |
| 1669 |
aiding in maintaining compatibility and leveraging the latest features: |
| 1670 |
|
| 1671 |
use Dancer2; |
| 1672 |
return "Running on Dancer2 version " . dancer_version; |
| 1673 |
|
| 1674 |
C<dancer_major_version> provides the major version of Dancer2, helping in |
| 1675 |
ensuring compatibility with plugins or external components: |
| 1676 |
|
| 1677 |
use Dancer2; |
| 1678 |
return "Running on Dancer2 major version " . dancer_major_version; |
| 1679 |
|
| 1680 |
=head2 New Keywords |
| 1681 |
|
| 1682 |
=over 4 |
| 1683 |
|
| 1684 |
=item app |
| 1685 |
|
| 1686 |
Returns the application object. App object is a L<Dancer2::Core::App>. |
| 1687 |
|
| 1688 |
=item config |
| 1689 |
|
| 1690 |
Retrieves configuration values. |
| 1691 |
|
| 1692 |
=item dance |
| 1693 |
|
| 1694 |
Starts the application. Not recommended. |
| 1695 |
|
| 1696 |
=item dancer_app |
| 1697 |
|
| 1698 |
Returns the application object. Synonym for C<app>. |
| 1699 |
|
| 1700 |
=item dancer_major_version |
| 1701 |
|
| 1702 |
Returns the major version of Dancer2. |
| 1703 |
|
| 1704 |
=item dancer_version |
| 1705 |
|
| 1706 |
Returns the full version number of Dancer2. |
| 1707 |
|
| 1708 |
=item prepare_app |
| 1709 |
|
| 1710 |
Runs a coderef at the start of your application only. |
| 1711 |
|
| 1712 |
=item psgi_app |
| 1713 |
|
| 1714 |
Synonym for C<to_app>. |
| 1715 |
|
| 1716 |
=item set |
| 1717 |
|
| 1718 |
Explicitly sets configuration options. |
| 1719 |
|
| 1720 |
=item setting |
| 1721 |
|
| 1722 |
Returns the value of the specified config setting. |
| 1723 |
|
| 1724 |
=item to_app |
| 1725 |
|
| 1726 |
Returns a coderef to your application, to be started by a Plack server. |
| 1727 |
|
| 1728 |
=item var |
| 1729 |
|
| 1730 |
Set and retrieve a temporary named value within your application. |
| 1731 |
|
| 1732 |
=item vars |
| 1733 |
|
| 1734 |
Returns a hashref or all temporary variables/values in your application. |
| 1735 |
|
| 1736 |
=back |
| 1737 |
|
| 1738 |
=head1 Logging |
| 1739 |
|
| 1740 |
Just like monitoring the lines for the roller coasters, logging helps |
| 1741 |
you keep track of what’s happening in your Dancer2 app. |
| 1742 |
|
| 1743 |
=head2 Why Should We Log? |
| 1744 |
|
| 1745 |
Logging is important for tracking errors, performance, and overall |
| 1746 |
activity in your app. It helps you understand what’s going right (or |
| 1747 |
wrong) in Danceyland. |
| 1748 |
|
| 1749 |
=head3 What Types of Things Might We Want to Log? |
| 1750 |
|
| 1751 |
=over 4 |
| 1752 |
|
| 1753 |
=item * |
| 1754 |
|
| 1755 |
Errors (e.g., a ride breaking down) |
| 1756 |
|
| 1757 |
=item * |
| 1758 |
|
| 1759 |
Important events (e.g., a new guest registering) |
| 1760 |
|
| 1761 |
=item * |
| 1762 |
|
| 1763 |
Debug information (e.g., the details of a request) |
| 1764 |
|
| 1765 |
=back |
| 1766 |
|
| 1767 |
=head2 Configuring Logging in Your Dancer2 App |
| 1768 |
|
| 1769 |
You can configure logging in your C<config.yml> file: |
| 1770 |
|
| 1771 |
logger: "console" |
| 1772 |
log: "debug" |
| 1773 |
|
| 1774 |
This configuration sends logs to the console and logs all messages at |
| 1775 |
the C<debug> level or higher. |
| 1776 |
|
| 1777 |
=head2 Logging Your Own Messages |
| 1778 |
|
| 1779 |
You can log your own messages using the logging keywords: |
| 1780 |
|
| 1781 |
debug "This is a debug message."; |
| 1782 |
info "A new user has registered."; |
| 1783 |
warning "The ride is slowing down!"; |
| 1784 |
error "The roller coaster broke down!"; |
| 1785 |
|
| 1786 |
=head2 Link to Extending Section |
| 1787 |
|
| 1788 |
For more information on extending the logger or creating custom loggers, |
| 1789 |
refer to the Extending section. |
| 1790 |
|
| 1791 |
=head2 Keywords Covered |
| 1792 |
|
| 1793 |
=over 4 |
| 1794 |
|
| 1795 |
=item debug |
| 1796 |
|
| 1797 |
Logs a debug-level message. |
| 1798 |
|
| 1799 |
=item info |
| 1800 |
|
| 1801 |
Logs an info-level message. |
| 1802 |
|
| 1803 |
=item warning |
| 1804 |
|
| 1805 |
Logs a warning-level message. |
| 1806 |
|
| 1807 |
=item error |
| 1808 |
|
| 1809 |
Logs an error-level message. |
| 1810 |
|
| 1811 |
=item log |
| 1812 |
|
| 1813 |
Logs a message at the specified log level: |
| 1814 |
|
| 1815 |
log( debug => 'This is a debug message' ); |
| 1816 |
|
| 1817 |
=back |
| 1818 |
|
| 1819 |
=head1 Testing |
| 1820 |
|
| 1821 |
Testing is essential to ensure that Danceyland's attractions are safe |
| 1822 |
and fun — and the same goes for your Dancer2 app. |
| 1823 |
|
| 1824 |
=head2 Why Test? |
| 1825 |
|
| 1826 |
Testing helps you find bugs before your guests (users) do. It ensures |
| 1827 |
that your app behaves as expected, even when things get complicated. Tests |
| 1828 |
help ensure that you don't accidentally break existing functionality when |
| 1829 |
making changes to your application. |
| 1830 |
|
| 1831 |
=head2 Example: Using C<Plack::Test> |
| 1832 |
|
| 1833 |
C<Plack::Test> allows you to test your app’s behavior without spinning up |
| 1834 |
a web server: |
| 1835 |
|
| 1836 |
use Plack::Test; |
| 1837 |
use HTTP::Request::Common; |
| 1838 |
use MyApp; |
| 1839 |
|
| 1840 |
test_psgi app => MyApp->to_app, client => sub { |
| 1841 |
my $cb = shift; |
| 1842 |
my $res = $cb->(GET "/"); |
| 1843 |
like $res->content, qr/Welcome to Danceyland/, "Home page works!"; |
| 1844 |
}; |
| 1845 |
|
| 1846 |
=head2 Example: Using C<Test::WWW::Mechanize::PSGI> |
| 1847 |
|
| 1848 |
C<Test::WWW::Mechanize::PSGI> provides a more user-friendly interface |
| 1849 |
for testing your app, making it easier to simulate interactions: |
| 1850 |
|
| 1851 |
use Test::WWW::Mechanize::PSGI; |
| 1852 |
use MyApp; |
| 1853 |
|
| 1854 |
my $mech = Test::WWW::Mechanize::PSGI->new( app => MyApp->to_app ); |
| 1855 |
$mech->get_ok('/'); |
| 1856 |
$mech->content_contains('Welcome to Danceyland'); |
| 1857 |
|
| 1858 |
=head2 More Information |
| 1859 |
|
| 1860 |
For more in-depth coverage of testing in Dancer2, check out L<Dancer2::Manual::Testing>. |
| 1861 |
|
| 1862 |
=head1 Plugins |
| 1863 |
|
| 1864 |
Danceyland is full of exciting rides and attractions, but sometimes you |
| 1865 |
need to add something extra—a little popcorn stand or a souvenir shop. |
| 1866 |
That’s where plugins come in! |
| 1867 |
|
| 1868 |
=head2 What Are Plugins? |
| 1869 |
|
| 1870 |
Plugins in Dancer2 are reusable modules that extend your app's |
| 1871 |
functionality. Whether it's connecting to a database, handling |
| 1872 |
authentication, or integrating with third-party services, plugins make |
| 1873 |
it easy to add features to your Dancer2 app without reinventing the |
| 1874 |
wheel. |
| 1875 |
|
| 1876 |
=head2 Why Do We Need Plugins? |
| 1877 |
|
| 1878 |
Plugins allow you to add functionality without having to reinvent the |
| 1879 |
wheel. Need authentication? Validation? Plugins are there to help you |
| 1880 |
focus on building the fun stuff, while they handle the heavy lifting. |
| 1881 |
|
| 1882 |
Examples: |
| 1883 |
|
| 1884 |
=over 4 |
| 1885 |
|
| 1886 |
=item Dancer2::Plugin::Auth::Tiny |
| 1887 |
|
| 1888 |
L<Dancer2::Plugin::Auth::Tiny> provides a simple and easy way to protect |
| 1889 |
your routes with minimal authentication logic. For example, you can |
| 1890 |
restrict access to certain routes with this plugin. |
| 1891 |
|
| 1892 |
=item Dancer2::Plugin::DataTransposeValidator |
| 1893 |
|
| 1894 |
L<Dancer2::Plugin::DataTransposeValidator> allows you to validate |
| 1895 |
incoming data using L<Data::Transpose>, giving you flexibility when |
| 1896 |
handling forms and other user inputs. |
| 1897 |
|
| 1898 |
=back |
| 1899 |
|
| 1900 |
=head2 How to Write a Plugin? |
| 1901 |
|
| 1902 |
Writing a plugin for Dancer2 is as simple as creating a module that hooks |
| 1903 |
into the Dancer2 app lifecycle. It’s a fun ride! For detailed guidance on |
| 1904 |
writing plugins, refer to L<Dancer2::Manual::Extending>. |
| 1905 |
|
| 1906 |
=head1 Complete Guide to Keywords |
| 1907 |
|
| 1908 |
Danceyland has its own lingo that makes it easy to construct and |
| 1909 |
interact with your park, and with other developers working on the park. |
| 1910 |
Dancer2 provides you with a DSL (Domain-Specific Language) which makes |
| 1911 |
it easy to implement, maintain, and extend your applications. You've |
| 1912 |
already learned many of these keywords, but there are additional ones |
| 1913 |
that provide even greater functionality. |
| 1914 |
|
| 1915 |
See L<the keyword guide|Dancer2::Manual::Keywords> for a complete list of |
| 1916 |
keywords provided by Dancer2. |
| 1917 |
|
| 1918 |
=head1 Advanced Topics |
| 1919 |
|
| 1920 |
Danceyland isn’t just for beginners—there’s always more to explore. Here |
| 1921 |
are some advanced features of Dancer2 that will take your app to the |
| 1922 |
next level. |
| 1923 |
|
| 1924 |
=head2 Composing an App with C<appname> |
| 1925 |
|
| 1926 |
In a theme park as vast as Danceyland, sometimes you need different |
| 1927 |
sections, like the Magical Kingdom or Actionland. Similarly, Dancer2 |
| 1928 |
allows you to build separate applications, but unite them together under |
| 1929 |
a single name using the C<appname> keyword, so each section can have its |
| 1930 |
own unique routing and logic. |
| 1931 |
|
| 1932 |
=head3 Example: Composing multiple apps with C<appname> into one app |
| 1933 |
|
| 1934 |
Using C<appname>, you can compose different apps within one big web app. |
| 1935 |
Each package can have its own Perl namespace but uses the same Dancer2 |
| 1936 |
namespace, so the routes are all available in the one application. |
| 1937 |
|
| 1938 |
# In file MagicApp.pm |
| 1939 |
package MagicApp; |
| 1940 |
use Dancer2 appname => 'MainApp'; |
| 1941 |
|
| 1942 |
get '/wand-shop' => sub { |
| 1943 |
return "Welcome to the Wand Shop in the Magic Kingdom!"; |
| 1944 |
}; |
| 1945 |
|
| 1946 |
# In file ActionApp.pm |
| 1947 |
package ActionApp; |
| 1948 |
use Dancer2 appname => 'MainApp'; |
| 1949 |
|
| 1950 |
get '/thrill-rides' => sub { |
| 1951 |
return "Ready for the thrill rides in Actionland?"; |
| 1952 |
}; |
| 1953 |
|
| 1954 |
# in MainApp.pm |
| 1955 |
package MainApp; |
| 1956 |
use Dancer2; |
| 1957 |
use MagicApp; |
| 1958 |
use ActionApp; |
| 1959 |
|
| 1960 |
# In the handler |
| 1961 |
use MainApp; |
| 1962 |
MainApp->to_app(); |
| 1963 |
|
| 1964 |
In this example, the C<MagicApp> package defines routes for the Magical |
| 1965 |
Kingdom, and the C<ActionApp> package defines routes for Actionland - |
| 1966 |
both using C<< appname => 'MainApp' >>. |
| 1967 |
|
| 1968 |
=head2 Manually Adjusting MIME settings |
| 1969 |
|
| 1970 |
In Danceyland, each attraction offers a unique experience, much like how |
| 1971 |
different content types are handled in your application. The C<mime> |
| 1972 |
keyword provides access to your applicaion's MIME processing object, |
| 1973 |
L<Dancer2::Core::MIME>: |
| 1974 |
|
| 1975 |
use Dancer2; |
| 1976 |
|
| 1977 |
get '/file/:name' => sub { |
| 1978 |
my $filename = route_parameters->get('name'); |
| 1979 |
my $file_path = "/path/to/files/$filename"; |
| 1980 |
my $content_type = mime->for_file($filename); |
| 1981 |
send_file($file_path, content_type => $content_type); |
| 1982 |
}; |
| 1983 |
|
| 1984 |
=head2 Adding Additional Response Headers |
| 1985 |
|
| 1986 |
In Danceyland, enhancing visitor experience often involves adding new |
| 1987 |
signposts without replacing existing ones. Similarly, in Dancer2, the |
| 1988 |
C<push_response_header> keyword allows you to add new values to an |
| 1989 |
existing response header without overwriting its current content. This |
| 1990 |
is particularly useful for headers like C<Set-Cookie>, where multiple |
| 1991 |
values might be necessary: |
| 1992 |
|
| 1993 |
use Dancer2; |
| 1994 |
|
| 1995 |
get '/set_cookies' => sub { |
| 1996 |
push_response_header 'Set-Cookie' => 'user=alice'; |
| 1997 |
push_response_header 'Set-Cookie' => 'theme=light'; |
| 1998 |
return "Cookies have been set."; |
| 1999 |
}; |
| 2000 |
|
| 2001 |
In this example, two cookies are added to the response without overwriting |
| 2002 |
each other. |
| 2003 |
|
| 2004 |
=head2 Automatic Serializing and Deserializing Data |
| 2005 |
|
| 2006 |
In Danceyland, sometimes we need to provide data to our visitors in |
| 2007 |
different formats, like JSON, YAML, or XML. Dancer2 makes serializing |
| 2008 |
data a breeze. You can even configure Dancer2 to automatically serialize |
| 2009 |
your responses based on the content type requested by the client. |
| 2010 |
|
| 2011 |
=head3 Example: Serializing JSON for output |
| 2012 |
|
| 2013 |
set serializer => 'JSON'; |
| 2014 |
|
| 2015 |
get '/ride-info' => sub { |
| 2016 |
return { name => 'Roller Coaster', status => 'Open' }; |
| 2017 |
}; |
| 2018 |
|
| 2019 |
With this setup, the response will automatically be serialized to JSON |
| 2020 |
when requested. |
| 2021 |
|
| 2022 |
=head3 Example: Deserializing JSON from input |
| 2023 |
|
| 2024 |
Dancer2 can also deserialize incoming requests automatically when a |
| 2025 |
serializer is enabled. If the client sends JSON data, it will be |
| 2026 |
automatically parsed. |
| 2027 |
|
| 2028 |
post '/update-ride' => sub { |
| 2029 |
my $data = request->data; # Automatically deserialized JSON input |
| 2030 |
return "Ride updated: " . $data->{name}; |
| 2031 |
}; |
| 2032 |
|
| 2033 |
Here, the incoming request body is JSON, and Dancer2 deserializes it |
| 2034 |
into a Perl data structure that you can access through C<< request->data >>. |
| 2035 |
|
| 2036 |
=head2 Manual Serializing and Deserializing |
| 2037 |
|
| 2038 |
Dancer2 also provides manual serialization methods for specific use cases |
| 2039 |
where automatic serialization isn't enough, or can't be used. |
| 2040 |
|
| 2041 |
=head3 C<send_as> |
| 2042 |
|
| 2043 |
C<send_as> allows you to manually serialize your response in a specific |
| 2044 |
format like JSON or YAML. This is useful when you need explicit control |
| 2045 |
over the response format: |
| 2046 |
|
| 2047 |
get '/info' => sub { |
| 2048 |
return send_as JSON => { name => 'Danceyland', status => 'open' }; |
| 2049 |
}; |
| 2050 |
|
| 2051 |
Here, C<send_as> explicitly returns the response as JSON. |
| 2052 |
|
| 2053 |
=head3 C<encode_json> |
| 2054 |
|
| 2055 |
In managing Danceyland, park data comes and goes in various formats. Dancer2 |
| 2056 |
provides tools to handle these formats efficiently. The C<encode_json> |
| 2057 |
keyword allows you to serialize a Perl data structure into a JSON string: |
| 2058 |
|
| 2059 |
use Dancer2; |
| 2060 |
|
| 2061 |
get '/data' => sub { |
| 2062 |
my $data = { attraction => 'Roller Coaster', status => 'open' }; |
| 2063 |
return encode_json($data); |
| 2064 |
}; |
| 2065 |
|
| 2066 |
C<encode_json> expects character data and returns UTF-8 encoded bytes. |
| 2067 |
|
| 2068 |
Since you are manually serializing the response data, the serialization |
| 2069 |
hooks provided by Dancer2 are not called. See L</Hooks> for more information. |
| 2070 |
|
| 2071 |
=head3 C<to_json> |
| 2072 |
|
| 2073 |
C<to_json> converts a Perl data structure to a JSON string. It's useful |
| 2074 |
when you want to manually prepare JSON data before sending it: |
| 2075 |
|
| 2076 |
my $json_string = to_json({ name => 'Danceyland', status => 'open' }); |
| 2077 |
|
| 2078 |
You likely want to use C<encode_json> instead. Both return UTF-8 encoded |
| 2079 |
bytes, but C<encode_json> makes the intent explicit. |
| 2080 |
|
| 2081 |
=head3 C<decode_json> |
| 2082 |
|
| 2083 |
You can decode incoming JSON payloads from the client with the C<decode_json> |
| 2084 |
keyword; it deserializes a JSON string into a Perl data structure: |
| 2085 |
|
| 2086 |
use Dancer2; |
| 2087 |
|
| 2088 |
post '/update' => sub { |
| 2089 |
my $json_data = request->body; |
| 2090 |
my $data = decode_json($json_data); |
| 2091 |
# Now, do something with it... |
| 2092 |
}; |
| 2093 |
|
| 2094 |
Since you are manually deserializing the incoming JSON, the serialization |
| 2095 |
hooks will not run. |
| 2096 |
|
| 2097 |
=head3 C<from_json> |
| 2098 |
|
| 2099 |
C<from_json> also decodes JSON to a Perl data structure. The input is |
| 2100 |
expected to be UTF-8 encoded bytes. |
| 2101 |
|
| 2102 |
=head3 C<to_yaml> |
| 2103 |
|
| 2104 |
C<to_yaml> takes a Perl datastructure and converts it to a YAML string. |
| 2105 |
|
| 2106 |
=head3 C<from_yaml> |
| 2107 |
|
| 2108 |
Similarly, C<from_yaml> lets you deserialize a YAML string into a Perl |
| 2109 |
data structure: |
| 2110 |
|
| 2111 |
use Dancer2; |
| 2112 |
|
| 2113 |
get '/config' => sub { |
| 2114 |
my $yaml_data = request->body; |
| 2115 |
my $data = from_yaml($yaml_data); |
| 2116 |
# Now, do something with $data... |
| 2117 |
}; |
| 2118 |
|
| 2119 |
=head2 Hooks |
| 2120 |
|
| 2121 |
Hooks are like special backstage passes at Danceyland. They give you |
| 2122 |
special access by allowing you to execute code at specific points in the |
| 2123 |
request/response cycle. You can use them to modify requests, responses, |
| 2124 |
or even add your own logic before or after routes are processed. |
| 2125 |
|
| 2126 |
=head3 Using Hooks with C<vars> |
| 2127 |
|
| 2128 |
Sometimes you want to share information across routes. You can use hooks |
| 2129 |
to store data using C<vars>, making it available for later routes: |
| 2130 |
|
| 2131 |
hook before => sub { |
| 2132 |
my $request = request; |
| 2133 |
vars->{visitor_id} = "VIP-" . $request->address; |
| 2134 |
}; |
| 2135 |
|
| 2136 |
get '/vip-area' => sub { |
| 2137 |
return "Welcome, " . vars->{visitor_id} . "!"; |
| 2138 |
}; |
| 2139 |
|
| 2140 |
In this example, we store the visitor’s ID (based on their IP address) |
| 2141 |
in the C<vars> keyword during the C<before> hook. That value is later |
| 2142 |
used in the C</vip-area> route to personalize the response. |
| 2143 |
|
| 2144 |
=head3 Request Hooks |
| 2145 |
|
| 2146 |
At the ticket booth just inside the entrance of Danceyland, the friendly |
| 2147 |
gatekeeper scans every visitor's pass and gives them a sticker as they pass |
| 2148 |
into the park: |
| 2149 |
|
| 2150 |
hook before => sub { |
| 2151 |
var sticker => 1; |
| 2152 |
}; |
| 2153 |
|
| 2154 |
The C<before> hook runs before any other code just before each request is |
| 2155 |
handled. In this example, we set a var, C<sticker>, that can be used later |
| 2156 |
in the request. |
| 2157 |
|
| 2158 |
As each visitor leaves, a park employee stamps each person's hand so they |
| 2159 |
can be readmitted later in the day: |
| 2160 |
|
| 2161 |
hook after => sub { |
| 2162 |
my $user = var user; |
| 2163 |
$user->stamp_hand; |
| 2164 |
}; |
| 2165 |
|
| 2166 |
For this example, An object representing a user was stored in a var earlier |
| 2167 |
in the request. On the user's way out (via the C<after> hook), their hand |
| 2168 |
gets stamped, and could be checked the next time the user enters the park |
| 2169 |
to skip buying another ticket. |
| 2170 |
|
| 2171 |
=head3 Template Hooks |
| 2172 |
|
| 2173 |
At Danceyland’s Caricature Corner, the brilliant artist B<Picasso McGlitterpants> |
| 2174 |
creates a sketch of every guest who stops by. The caricature goes through |
| 2175 |
several phases before it’s ready to hang on your wall: |
| 2176 |
|
| 2177 |
=over |
| 2178 |
|
| 2179 |
=item * Before the sketch is drawn: Picasso sharpens their pencils |
| 2180 |
|
| 2181 |
=item * While drawing: the artist sneaks in little embellishments |
| 2182 |
|
| 2183 |
=item * When the sketch is done: Picasso proudly signs their masterpiece |
| 2184 |
|
| 2185 |
=item * Before handing it to you: the park staff pops it into a fancy frame |
| 2186 |
|
| 2187 |
=back |
| 2188 |
|
| 2189 |
Before the sketching starts, Picasso ensures all the materials are in order: |
| 2190 |
|
| 2191 |
hook before_template_render => sub { |
| 2192 |
my $tokens = shift; |
| 2193 |
|
| 2194 |
# Picasso McGlitterpants sharpens their pencils and sets up the |
| 2195 |
# paper before drawing begins. |
| 2196 |
$tokens->{materials_ready} = 1; |
| 2197 |
}; |
| 2198 |
|
| 2199 |
Template hooks allow you to manipulate data before or after a view |
| 2200 |
(i.e., template) is rendered. C<materials_ready> is added as a template |
| 2201 |
token before the view gets rendered. That token is made available in the |
| 2202 |
template as C<[% materials_ready %]>. |
| 2203 |
|
| 2204 |
When the sketch is finished, Picasso adds their signature (with extra glitter, |
| 2205 |
of course) to make sure the caricature is authentic: |
| 2206 |
|
| 2207 |
hook after_template_render => sub { |
| 2208 |
my $content = shift; |
| 2209 |
$$content .= "\n\n-- Signed by Picasso McGlitterpants 🎨✨"; |
| 2210 |
}; |
| 2211 |
|
| 2212 |
This happens after the view/template is rendered, but before it is shown |
| 2213 |
to the user. |
| 2214 |
|
| 2215 |
Before the sketch is mounted, the artist sprinkles it with sparkles, making |
| 2216 |
sure the presentation twinkles with Danceyland charm: |
| 2217 |
|
| 2218 |
hook before_layout_render => sub { |
| 2219 |
my ($tokens, $content) = @_; |
| 2220 |
|
| 2221 |
$tokens->{special_effects} = 'sparkles'; |
| 2222 |
}; |
| 2223 |
|
| 2224 |
Layout hooks apply after views are rendered, when the layout is going |
| 2225 |
to be applied. The C<before_layout_render> hook is run prior to the layout |
| 2226 |
being applied. It's a useful place to check for things such as whether or |
| 2227 |
not is authorized to view select content. |
| 2228 |
|
| 2229 |
At the very end, just before the guest receives their caricature, the staff pops |
| 2230 |
it into a silvery frame so it’s ready to hang at home: |
| 2231 |
|
| 2232 |
hook after_layout_render => sub { |
| 2233 |
my $content = shift; |
| 2234 |
|
| 2235 |
$$content = '<div class="silver-frame">' . $$content . "</div>"; |
| 2236 |
}; |
| 2237 |
|
| 2238 |
The C<after_layout_render> hook is the last chance to alter content before |
| 2239 |
being sent to the browser. |
| 2240 |
|
| 2241 |
=head3 Error Handling Hooks |
| 2242 |
|
| 2243 |
Even in Danceyland, sometimes the roller coaster gets stuck at the top, or |
| 2244 |
the cotton candy machine makes a little too much fluff. That’s when our |
| 2245 |
friendly park attendants step in! |
| 2246 |
|
| 2247 |
Error hooks let you step in whenever something goes wrong in an application. |
| 2248 |
Just like Danceyland staff rushing over with a smile and a toolkit, your |
| 2249 |
error hook can log what happened, show a helpful message, or gently guide |
| 2250 |
the guest to the right exit. |
| 2251 |
|
| 2252 |
hook on_route_exception => sub { |
| 2253 |
my ($error) = @_; |
| 2254 |
warning "Picasso McGlitterpants spilled glitter on the server: $error"; |
| 2255 |
}; |
| 2256 |
|
| 2257 |
Or you can catch a general error and provide your own response: |
| 2258 |
|
| 2259 |
hook before_error => sub { |
| 2260 |
my ($error) = @_; |
| 2261 |
$error->message("Oops! One of the rides jammed. " . |
| 2262 |
"Please enjoy a free churro while we fix it."); |
| 2263 |
}; |
| 2264 |
|
| 2265 |
Other error hooks include: |
| 2266 |
|
| 2267 |
=over |
| 2268 |
|
| 2269 |
=item * init_error |
| 2270 |
|
| 2271 |
This runs right after a new L<Dancer2::Core::Error> object is built. The new |
| 2272 |
error object is passed to the hook as an argument. |
| 2273 |
|
| 2274 |
=item * after_error |
| 2275 |
|
| 2276 |
This hook is called right after error is thrown, and receives a |
| 2277 |
L<Dancer2::Core::Response> object as an argument. |
| 2278 |
|
| 2279 |
=item * on_hook_exception |
| 2280 |
|
| 2281 |
This hook is special, and is only called when an exception is caught in |
| 2282 |
another hook, just before logging it and rethrowing it higher. |
| 2283 |
|
| 2284 |
This hook receives as arguments: |
| 2285 |
|
| 2286 |
=over |
| 2287 |
|
| 2288 |
=item * A L<Dancer2::Core::App> object |
| 2289 |
|
| 2290 |
=item * The error string |
| 2291 |
|
| 2292 |
=item * The name of the hook where the exception occurred |
| 2293 |
|
| 2294 |
The hook name is the full hook name (e.g. C<core.app.route_exception>). |
| 2295 |
|
| 2296 |
=back |
| 2297 |
|
| 2298 |
If the function provided to C<on_hook_exception> causes an exception itself, then |
| 2299 |
this will be ignored (thus preventing a potentially recursive situation). |
| 2300 |
However, it is still possible for the function to set a custom response and |
| 2301 |
halt it (and optionally die), thus providing a method to render custom content |
| 2302 |
in the event of an exception in a hook: |
| 2303 |
|
| 2304 |
hook on_hook_exception => sub { |
| 2305 |
my ($app, $error, $hook_name) = @_; |
| 2306 |
$app->response->content("Oh noes! The popcorn machine " . |
| 2307 |
"overheated and overflowed!"); |
| 2308 |
$app->response->halt; |
| 2309 |
}; |
| 2310 |
|
| 2311 |
=back |
| 2312 |
|
| 2313 |
Think of error hooks as the ever-present Danceyland helpers: they |
| 2314 |
make sure that when a mishap occurs, guests are cared for and can |
| 2315 |
keep smiling on their way to the next attraction. |
| 2316 |
|
| 2317 |
=head3 File Rendering Hooks |
| 2318 |
|
| 2319 |
File rendering hooks are triggered when static files are served: |
| 2320 |
|
| 2321 |
hook before_file_render => sub { |
| 2322 |
my $file_path = shift; |
| 2323 |
debug "Starting to serve file: $file_path"; |
| 2324 |
}; |
| 2325 |
|
| 2326 |
hook after_file_render => sub { |
| 2327 |
my $response = shift; |
| 2328 |
debug "Finished serving file."; |
| 2329 |
}; |
| 2330 |
|
| 2331 |
=head3 Logging Hooks |
| 2332 |
|
| 2333 |
Logging hooks can be used to give additional information or context to |
| 2334 |
Danceyland maintenance workers when something breaks down, or to ride |
| 2335 |
operators to help ensure smooth operation of rides: |
| 2336 |
|
| 2337 |
hook 'engine.logger.before' => sub { |
| 2338 |
my ( $logger, $level, @messages ) = @_; |
| 2339 |
push @messages, 'Request ID: ' . vars->{request_id}; |
| 2340 |
}; |
| 2341 |
|
| 2342 |
hook 'engine.logger.after' => sub { |
| 2343 |
my ( $logger, $level, @messages ) = @_; |
| 2344 |
if( $level eq 'error' ) { |
| 2345 |
# Add code to send an email here |
| 2346 |
} |
| 2347 |
}; |
| 2348 |
|
| 2349 |
These hooks are useful when you want to prepend or append information to |
| 2350 |
a log message, write messages out in a specific format, or take additional |
| 2351 |
action based on message severity. |
| 2352 |
|
| 2353 |
=head3 Serializer Hooks |
| 2354 |
|
| 2355 |
Every great visit to Danceyland ends with a souvenir! Serializer hooks |
| 2356 |
are the way Danceyland decides how to wrap up your experience before |
| 2357 |
sending you home. Maybe you get your caricature rolled up in a tube, |
| 2358 |
maybe it’s slipped into a glossy folder, or maybe Picasso McGlitterpants |
| 2359 |
mails it to you as a postcard. |
| 2360 |
|
| 2361 |
That’s what serializers do: they take the "thing" (your response) |
| 2362 |
and package it in the right format (JSON, YAML, plain text, etc.) |
| 2363 |
so you can carry it with you outside the park. |
| 2364 |
|
| 2365 |
For example: |
| 2366 |
|
| 2367 |
set serializer => 'JSON'; |
| 2368 |
|
| 2369 |
Now, every souvenir is neatly wrapped in shiny JSON paper. |
| 2370 |
|
| 2371 |
And if you want a custom wrapper, you can hook into the |
| 2372 |
serializer process yourself: |
| 2373 |
|
| 2374 |
hook before_serializer => sub { |
| 2375 |
my ($content) = @_; |
| 2376 |
debug "Preparing to wrap up: $content"; |
| 2377 |
}; |
| 2378 |
|
| 2379 |
hook after_serializer => sub { |
| 2380 |
my ($serialized) = @_; |
| 2381 |
debug "Souvenir has been wrapped: $serialized"; |
| 2382 |
}; |
| 2383 |
|
| 2384 |
So whenever you see serializer hooks, think of the Danceyland |
| 2385 |
souvenir shop — the place that makes sure you don’t just have |
| 2386 |
a memory, but also a neatly wrapped keepsake to take home. |
| 2387 |
|
| 2388 |
=head2 Handlers |
| 2389 |
|
| 2390 |
Handlers are the rides that keep Danceyland running. Dancer2 provides |
| 2391 |
several built-in handlers to manage files, pages, and routes. You can |
| 2392 |
also create your own handlers to extend the park’s offerings. |
| 2393 |
|
| 2394 |
=head2 File Handler |
| 2395 |
|
| 2396 |
The L<Dancer2::Handler::File> component is used to serve static files, |
| 2397 |
like images and stylesheets, from the C<public> directory. It comes with |
| 2398 |
two hooks; see the L</Hooks> section for more information. |
| 2399 |
|
| 2400 |
=head2 Auto Page Handler |
| 2401 |
|
| 2402 |
When a template matches a request, the L<Dancer2::Handler::AutoPage> |
| 2403 |
component is used. It automatically renders a template if one exists for |
| 2404 |
the requested path. |
| 2405 |
|
| 2406 |
If someone visits C</about> and there is a template called C<about.tt>, |
| 2407 |
the auto page handler will automatically render that template. |
| 2408 |
|
| 2409 |
=head2 Writing Your Own Handlers |
| 2410 |
|
| 2411 |
You can create your own handler by consuming the L<Dancer2::Core::Role::Handler> |
| 2412 |
role. This allows you to define your own logic for processing routes: |
| 2413 |
|
| 2414 |
package MyHandler; |
| 2415 |
use Moo; |
| 2416 |
with 'Dancer2::Core::Role::Handler'; |
| 2417 |
|
| 2418 |
sub methods { qw(GET) } |
| 2419 |
|
| 2420 |
sub regexp { '/custom/:page' } |
| 2421 |
|
| 2422 |
sub code { |
| 2423 |
return sub { |
| 2424 |
my $app = shift; |
| 2425 |
my $page = $app->request->params->{page}; |
| 2426 |
return "You requested the custom page: $page"; |
| 2427 |
}; |
| 2428 |
} |
| 2429 |
|
| 2430 |
sub register { |
| 2431 |
my ($self, $app) = @_; |
| 2432 |
$app->add_route( |
| 2433 |
method => $_, |
| 2434 |
regexp => $self->regexp, |
| 2435 |
code => $self->code, |
| 2436 |
) for $self->methods; |
| 2437 |
} |
| 2438 |
|
| 2439 |
=head2 Middleware |
| 2440 |
|
| 2441 |
Middleware in Dancer2 is like the behind-the-scenes magic at Danceyland, |
| 2442 |
like security or cleaning staff at Danceyland. It handles tasks between |
| 2443 |
the request and response cycles, allowing you to modify or inspect the |
| 2444 |
request/response without changing your app code. |
| 2445 |
|
| 2446 |
You can easily add middleware using Plack, Dancer2’s underlying engine. |
| 2447 |
|
| 2448 |
=head2 Why Use Middleware Instead of App Logic? |
| 2449 |
|
| 2450 |
You could, in theory, implement directly in your code everything that a |
| 2451 |
middleware does. So why use middlewares? Middlewares allow you to modify |
| 2452 |
the request/response cycle without changing your app’s core code. It’s |
| 2453 |
useful for: |
| 2454 |
|
| 2455 |
=over 4 |
| 2456 |
|
| 2457 |
=item * |
| 2458 |
|
| 2459 |
Managing sessions and cookies. |
| 2460 |
|
| 2461 |
=item * |
| 2462 |
|
| 2463 |
Handling authentication. |
| 2464 |
|
| 2465 |
=item * |
| 2466 |
|
| 2467 |
Compressing responses or managing headers. |
| 2468 |
|
| 2469 |
=back |
| 2470 |
|
| 2471 |
Middleware operates in-between the client’s request and the app’s |
| 2472 |
response, providing flexibility and reducing duplication in your |
| 2473 |
application logic. |
| 2474 |
|
| 2475 |
Additionally, you can use middlewares across different code-bases. Given |
| 2476 |
best practices, they would not be tied to a particular web application. |
| 2477 |
|
| 2478 |
=head3 Adding Middlewares |
| 2479 |
|
| 2480 |
builder { |
| 2481 |
enable 'Session'; |
| 2482 |
enable 'Static', path => qr{^/(images|css)/}, root => './public'; |
| 2483 |
app; |
| 2484 |
}; |
| 2485 |
|
| 2486 |
This example uses Plack middleware to manage sessions and serve static files. |
| 2487 |
|
| 2488 |
=head2 Asynchronous Programming |
| 2489 |
|
| 2490 |
In Danceyland, we never want our visitors to wait in line! Sometimes, a |
| 2491 |
task can take a long time, like fetching data from an external service. |
| 2492 |
Asynchronous programming allows you to handle these tasks in the |
| 2493 |
background, keeping your app responsive. |
| 2494 |
|
| 2495 |
Dancer2 supports asynchronous programming to help you manage I/O-bound |
| 2496 |
operations more efficiently. |
| 2497 |
|
| 2498 |
=head2 Why Choose Async Over Blocking? |
| 2499 |
|
| 2500 |
With async programming, you can handle long-running tasks without |
| 2501 |
blocking the rest of your app. This is useful for: |
| 2502 |
|
| 2503 |
=over 4 |
| 2504 |
|
| 2505 |
=item * |
| 2506 |
|
| 2507 |
Fetching data from an external API. |
| 2508 |
|
| 2509 |
=item * |
| 2510 |
|
| 2511 |
Handling large uploads or downloads. |
| 2512 |
|
| 2513 |
=item * |
| 2514 |
|
| 2515 |
Sending notifications or emails. |
| 2516 |
|
| 2517 |
=back |
| 2518 |
|
| 2519 |
=head2 Choosing the Right PSGI Server |
| 2520 |
|
| 2521 |
To use asynchronous programming in Dancer2, your app must be running on |
| 2522 |
a PSGI server that supports event loops, like L<Twiggy>. Such servers can |
| 2523 |
handle async tasks, unlike traditional PSGI servers that utilize forking |
| 2524 |
to handle multiple parallel tasks. |
| 2525 |
|
| 2526 |
=head2 Sending Content Asynchronously |
| 2527 |
|
| 2528 |
Dancer2 provides keywords for implementing asynchronous code. |
| 2529 |
|
| 2530 |
=head3 content |
| 2531 |
|
| 2532 |
The C<content> keyword sets the response content from within a delayed |
| 2533 |
response. |
| 2534 |
|
| 2535 |
=head3 delayed |
| 2536 |
|
| 2537 |
Some events at Danceyland, like the grand parade, are worth watching but |
| 2538 |
take some time to complete. Similarly, Dancer2 offers the C<delayed> keyword |
| 2539 |
to initiate an asynchronous response, allowing you to deliver long-running |
| 2540 |
results, or handling long-running operations. |
| 2541 |
|
| 2542 |
=head2 done |
| 2543 |
|
| 2544 |
Once everything is set, you can use C<done> to finalize and send the |
| 2545 |
response to the visitor. |
| 2546 |
|
| 2547 |
=head2 flush |
| 2548 |
|
| 2549 |
To send parts of the response incrementally, C<flush> allows streaming |
| 2550 |
content to the client in a delayed response without closing the connection. |
| 2551 |
|
| 2552 |
=head2 Example: Asynchronous HTTP Request |
| 2553 |
|
| 2554 |
Here’s how you can fetch data asynchronously in Dancer2. Instead of |
| 2555 |
waiting for a response, the request runs in the background and delivers |
| 2556 |
the result when it’s ready: |
| 2557 |
|
| 2558 |
use Dancer2; |
| 2559 |
use Future::HTTP; |
| 2560 |
|
| 2561 |
get '/fetch-ride-status' => sub { |
| 2562 |
delayed { |
| 2563 |
content 'The grand parade is starting!'; |
| 2564 |
flush; |
| 2565 |
|
| 2566 |
http_get('http://parade-status.com/api/v1/floats')->then( sub { |
| 2567 |
my ($body, $headers) = @_; |
| 2568 |
content $body; |
| 2569 |
flush; |
| 2570 |
}); |
| 2571 |
|
| 2572 |
content 'The grand parade is finished!'; |
| 2573 |
done; |
| 2574 |
}; |
| 2575 |
}; |
| 2576 |
|
| 2577 |
In this example, we fetch the status of a ride asynchronously using |
| 2578 |
C<http_get>. The C<delayed> keyword defers the response until the |
| 2579 |
background request completes. The C<$resume> callback is used to send |
| 2580 |
the content back to the visitor once the request finishes. |
| 2581 |
|
| 2582 |
For a deeper dive, check out these fantastic articles on async programming |
| 2583 |
in Dancer2: L<https://advent.perldancer.org/2020/22> and |
| 2584 |
L<https://advent.perldancer.org/2020/23>. |
| 2585 |
|
| 2586 |
=head1 AUTHOR |
| 2587 |
|
| 2588 |
Dancer Core Developers |
| 2589 |
|
| 2590 |
=head1 COPYRIGHT AND LICENSE |
| 2591 |
|
| 2592 |
This software is copyright (c) 2026 by Alexis Sukrieh. |
| 2593 |
|
| 2594 |
This is free software; you can redistribute it and/or modify it under |
| 2595 |
the same terms as the Perl 5 programming language system itself. |
| 2596 |
|
| 2597 |
=cut |