Debian Codegraph @

lib/Dancer2/Manual/Migration.pod

raw
1 package Dancer2::Manual::Migration;
2 # ABSTRACT: Migrating from Dancer to Dancer2
3
4 use strict;
5 use warnings;
6
7 1;
8
9 __END__
10
11 =pod
12
13 =encoding UTF-8
14
15 =head1 NAME
16
17 Dancer2::Manual::Migration - Migrating from Dancer to Dancer2
18
19 =head1 VERSION
20
21 version 2.2.2
22
23 =head1 Migration from Dancer 1 to Dancer2
24
25 This document covers some changes that users will need to be aware of
26 while upgrading from L<Dancer> (version 1) to L<Dancer2>.
27
28 =head2 Launcher script
29
30 The default launcher script F<bin/app.pl> in L<Dancer> looked like this:
31
32 #!/usr/bin/env perl
33 use Dancer;
34 use MyApp;
35 dance;
36
37 In L<Dancer2> it is available as F<bin/app.psgi> and looks like this:
38
39 #!/usr/bin/env perl
40
41 use strict;
42 use warnings;
43 use FindBin;
44 use lib "$FindBin::Bin/../lib";
45
46 use MyApp;
47 MyApp->to_app;
48
49 So you need to remove the C<use Dancer;> part, replace the C<dance;> command
50 by C<< MyApp->to_app; >> (where MyApp is the name of your application), and
51 add the following lines:
52
53 use strict;
54 use warnings;
55 use FindBin;
56 use lib "$FindBin::Bin/../lib";
57
58 There is a L<Dancer Advent Calendar|http://advent.perldancer.org> article
59 L<< covering the C<to_app> keyword|http://advent.perldancer.org/2014/9 >>
60 and its usage.
61
62 =head2 Configuration
63
64 You specify a different location to the directory used for serving static (public)
65 content by setting the C<public_dir> option. In that case, you have to set
66 C<static_handler> option also.
67
68 =head2 Apps
69
70 1. In L<Dancer2>, each module is a B<separate application> with its own
71 namespace and variables. You can set the application name in each of your
72 L<Dancer2> application modules. Different modules can be tied into the same
73 app by setting the application name to the same value.
74
75 For example, to set the appname directive explicitly:
76
77 C<MyApp>:
78
79 package MyApp;
80 use Dancer2;
81 use MyApp::Admin
82
83 hook before => sub {
84 var db => 'Users';
85 };
86
87 get '/' => sub {...};
88
89 1;
90
91 C<MyApp::Admin>:
92
93 package MyApp::Admin;
94 use Dancer2 appname => 'MyApp';
95
96 # use a lexical prefix so we don't override it globally
97 prefix '/admin' => sub {
98 get '/' => sub {...};
99 };
100
101 1;
102
103 Without the appname directive, C<MyApp::Admin> would not have access
104 to variable C<db>. In fact, when accessing C</admin>, the before hook would
105 not be executed.
106
107 See L<Dancer2::Cookbook|https://metacpan.org/pod/Dancer2::Cookbook#Using-the-prefix-feature-to-split-your-application>
108 for details.
109
110 2. To speed up an app in Dancer2, install the recommended modules listed in the
111 L<Dancer2::Manual::Deployment/"Performance Improvements"> section.
112
113 =head2 Request
114
115 The request object (L<Dancer2::Core::Request>) is now deferring much of
116 its code to L<Plack::Request> to be consistent with the known interface
117 to L<PSGI> requests.
118
119 Currently the following attributes pass directly to L<Plack::Request>:
120
121 C<address>, C<remote_host>, C<protocol>, C<port>, C<method>, C<user>,
122 C<request_uri>, C<script_name>, C<content_length>, C<content_type>,
123 C<content_encoding>, C<referer>, and C<user_agent>.
124
125 If previous attributes returned I<undef> for no value beforehand, they
126 will return whatever L<Plack::Request> defines now, which just might be
127 an empty list.
128
129 For example:
130
131 my %data = (
132 referer => request->referer,
133 user_agent => request->user_agent,
134 );
135
136 should be replaced by:
137
138 my %data = (
139 referer => request->referer || '',
140 user_agent => request->user_agent || '',
141 );
142
143 =head2 Plugins: plugin_setting
144
145 C<plugin_setting> returns the configuration of the plugin. It can only be
146 called in C<register> or C<on_plugin_import>.
147
148 =head2 Routes
149
150 L<Dancer2> requires all routes defined via a string to begin with a leading
151 slash C</>.
152
153 For example:
154
155 get '0' => sub {
156 return "not gonna fly";
157 };
158
159 would return an error. The correct way to write this would be to use
160 C<get '/0'>
161
162 =head2 Route parameters
163
164 The C<params> keyword which provides merged parameters used to allow body
165 parameters to override route parameters. Now route parameters take
166 precedence over query parameters and body parameters.
167
168 We have introduced C<route_parameters> to retrieve parameter values from
169 the route matching. Please refer to L<Dancer2::Manual> for more
170 information.
171
172 =head2 Tests
173
174 Dancer2 recommends the use of L<Plack::Test>.
175
176 For example:
177
178 use strict;
179 use warnings;
180 use Test::More tests => 2;
181 use Plack::Test;
182 use HTTP::Request::Common;
183
184 {
185 package App::Test; # or whatever you want to call it
186 get '/' => sub { template 'index' };
187 }
188
189 my $test = Plack::Test->create( App::Test->to_app );
190 my $res = $test->request( GET '/' );
191
192 ok( $res->is_success, '[GET /] Successful' );
193 like( $res->content, qr{<title>Test2</title>}, 'Correct title' );
194
195 Other modules that could be used for testing are:
196
197 =over 4
198
199 =item * L<Test::TCP>
200
201 =item * L<Test::WWW::Mechanize::PSGI>
202
203 =back
204
205 =head3 Logs
206
207 The C<logger_format> in the Logger role (L<Dancer2::Core::Role::Logger>)
208 is now C<log_format>.
209
210 C<read_logs> can no longer be used, as with L<Dancer2::Test>. Instead,
211 L<Dancer2::Logger::Capture> could be used for testing, to capture all
212 logs to an object.
213
214 For example:
215
216 use strict;
217 use warnings;
218 use Test::More import => ['!pass'];
219 use Plack::Test;
220 use HTTP::Request::Common;
221 use Ref::Util qw<is_coderef>;
222
223 {
224 package App;
225 use Dancer2;
226
227 set log => 'debug';
228 set logger => 'capture';
229
230 get '/' => sub {
231 debug 'this is my debug message';
232 return 1;
233 };
234 }
235
236 my $app = Dancer2->psgi_app;
237 ok( is_coderef($app), 'Got app' );
238
239 test_psgi $app, sub {
240 my $cb = shift;
241
242 my $res = $cb->( GET '/' );
243 is $res->code, 200;
244
245 my $trap = App->dancer_app->logger_engine->trapper;
246
247 is_deeply $trap->read, [
248 { level => 'debug', message => 'this is my debug message' }
249 ];
250 };
251
252 =head2 Exports: Tags
253
254 The following tags are not needed in L<Dancer2>:
255
256 use Dancer2 qw(:syntax);
257 use Dancer2 qw(:tests);
258 use Dancer2 qw(:script);
259
260 The C<plackup> command should be used instead. It provides a development
261 server and reads the configuration options in your command line utilities.
262
263 =head2 Engines
264
265 =over 4
266
267 =item * Engines receive a logging callback
268
269 Engines now receive a logging callback named C<log_cb>. Engines can use it
270 to log anything in run-time, without having to worry about what logging
271 engine is used.
272
273 This is provided as a callback because the logger might be changed in
274 run-time and we want engines to be able to always reach the current one
275 without having a reference back to the core application object.
276
277 The logger engine doesn't have the attribute since it is the logger itself.
278
279 =item * Engines handle encoding consistently
280
281 All engines are now expected to handle encoding on their own. User code
282 is expected to be in internal Perl representation.
283
284 Therefore, all serializers, for example, should deserialize to the Perl
285 representation. Templates, in turn, encode to UTF-8 if requested by the
286 user, or by default.
287
288 One side-effect of this is that C<from_yaml> will call L<YAML>'s C<Load>
289 function with decoded input.
290
291 =back
292
293 =head3 Templating engine changes
294
295 If you are migrating from Dancer1 and are using an application based
296 on L<Dancer::Template::Simple>, the L<Dancer2::Template::Simple> engine is
297 no longer part of the core Dancer2 distribution. It is available to
298 install as a separate distribution from CPAN.
299
300 In Dancer1, the following were equivalent for Template::Toolkit:
301
302 template 'foo/bar'
303 template '/foo/bar'
304
305 In Dancer2, when using L<Dancer2::Template::TemplateToolkit>, the version with
306 the leading slash will try to locate C</foo/bar> relative to your filesystem
307 root, not relative to your Dancer application directory.
308
309 The L<Dancer2::Template::Simple> engine is unchanged in this respect.
310
311 Whereas in Dancer1, template engines have the methods:
312
313 $template_engine->view('foo.tt')
314 $template_engine->view_exists('foo.tt')
315
316 In Dancer2, you should instead write:
317
318 $template_engine->view_pathname('foo.tt')
319 $template_engine->pathname_exists($full_path)
320
321 You may not need these unless you are writing a templating engine.
322
323 =head3 Serializers
324
325 You no longer need to implement the C<loaded> method. It is simply
326 unnecessary.
327
328 =head3 Sessions
329
330 Now the L<Simple|Dancer2::Session::Simple> session engine is turned on
331 by default, unless you specify a different one.
332
333 =head2 Configuration
334
335 =head3 C<public_dir>
336
337 You cannot set the public directory with C<setting> now. Instead you
338 will need to call C<config>:
339
340 # before
341 setting( 'public_dir', 'new_path/' );
342
343 # after
344 config->{'public_dir'} = 'new_path';
345
346 =head3 confdir
347
348 You cannot set the configuration directory (C<confdir>) with C<setting>
349 now. You can use an environment variable, however:
350
351 export DANCER_CONFDIR=$PROJECT_ROOT/etc
352
353 =head3 warnings
354
355 The C<warnings> configuration option, along with the environment variable
356 C<DANCER_WARNINGS>, have been removed and have no effect whatsoever.
357
358 They were added when someone requested to be able to load Dancer without
359 the L<warnings> pragma, which it adds, just like L<Moose>, L<Moo>, and
360 other modules provide.
361
362 If you want this to happen now (which you probably shouldn't be doing),
363 you can always control it lexically:
364
365 use Dancer2;
366 no warnings;
367
368 You can also use Dancer2 within a narrower scope:
369
370 { use Dancer2 }
371 use strict;
372 # warnings are not turned on
373
374 However, having L<warnings> turned it is very recommended.
375
376 =head3 server_tokens
377
378 The configuration C<server_tokens> has been introduced in the reverse (but
379 more sensible, and Plack-compatible) form as C<no_server_tokens>.
380
381 C<DANCER_SERVER_TOKENS> changed to C<DANCER_NO_SERVER_TOKENS>.
382
383 =head3 engines
384
385 If you want to use Template::Toolkit instead of the built-in simple templating
386 engine you used to enable the following line in the config.yml file.
387
388 template: "template_toolkit"
389
390 That was enough to get started. The start_tag and end_tag it used were the same as in
391 the simple template <% and %> respectively.
392
393 If you wanted to further customize the Template::Toolkit you could also enable or add
394 the following:
395
396 engines:
397 template_toolkit:
398 encoding: 'utf8'
399 start_tag: '[%'
400 end_tag: '%]'
401
402 In Dancer 2 you can also enable Template::Toolkit with the same configuration option:
403
404 template: "template_toolkit"
405
406 But the default start_tag and end_tag are now [% and %], so if you used the default in Dancer 1
407 now you will have to explicitly change the start_tag and end_tag values.
408 The configuration also got an extra level of depth. Under the C<engine> key there is a C<template>
409 key and the C<template_toolkit> key comes below that. As in this example:
410
411 engines:
412 template:
413 template_toolkit:
414 start_tag: '<%'
415 end_tag: '%>'
416
417 In a nutshell, if you used to have
418
419 template: "template_toolkit"
420
421 You need to replace it with
422
423 template: "template_toolkit"
424 engines:
425 template:
426 template_toolkit:
427 start_tag: '<%'
428 end_tag: '%>'
429
430 =head4 Session engine
431
432 The session engine is configured in the C<engine> section.
433
434 =over 4
435
436 =item * C<session_name> changed to C<cookie_name>.
437
438 =item * C<session_domain> changed to C<cookie_domain>.
439
440 =item * C<session_expires> changed to C<cookie_duration>.
441
442 =item * C<session_secure> changed to C<is_secure>.
443
444 =item * C<session_is_http_only> changed to C<is_http_only>.
445
446 =back
447
448 L<Dancer2> also adds two attributes for session:
449
450 =over 4
451
452 =item * C<cookie_path>
453 The path of the cookie to create for storing the session key. Defaults to "/".
454
455 =item * C<session_duration>
456 Duration in seconds before sessions should expire, regardless of cookie
457 expiration. If set, then SessionFactories should use this to enforce a limit on
458 session validity.
459
460 =back
461
462 See L<Dancer2::Core::Role::SessionFactory> for more detailed documentation
463 for these options, or the particular session engine for other supported options.
464
465 session: Simple
466
467 engines:
468 session:
469 Simple:
470 cookie_name: dance.set
471 cookie_duration: '24 hours'
472 is_secure: 1
473 is_http_only: 1
474
475 =head3 Plack Middleware
476
477 In Dancer1 you could set up Plack Middleware using a C<plack_middlewares> key
478 in your C<config.yml> file. Under Dancer2 you will instead need to invoke
479 middleware using L<Plack::Builder>, as demonstrated in
480 L<Dancer2::Manual::Deployment>.
481
482 =head2 Keywords
483
484 =head3 Calling Keywords Explicitly
485
486 In Dancer1, keywords could be imported individually into a package:
487
488 package MyApp;
489 use Dancer qw< get post params session >;
490
491 get '/foo' { ... };
492
493 Any keywords you did't export could be called explicitly:
494
495 package MyApp;
496 use Dancer qw< get post params session >;
497 use List::Util qw< any >;
498
499 Dancer::any sub { ... };
500
501 Dancer2's DSL is implemented differently. Keywords only exist in the namespace
502 of the package which C<use>s Dancer2, i.e. there is no C<Dancer2::any>, only
503 e.g. C<MyApp::any>.
504
505 If you only want individual keywords, you can write a shim as follows:
506
507 package MyApp::DSL;
508 use Dancer2 appname => 'MyApp';
509
510 use Exporter qw< import >;
511
512 our @EXPORT = qw< get post ... >
513
514 Then in other packages:
515
516 package MyApp;
517
518 use MyApp::DSL qw< get post >;
519
520 MyApp::DSL::any sub { ... };
521
522 =head3 appdir
523
524 This keyword does not exist in Dancer2. However, the same information can be
525 found in C<< config->{'appdir'} >>.
526
527 =head3 load
528
529 This keyword is no longer required. Dancer2 loads the environment
530 automatically and will not reload any other environment when called with
531 L<load>. (It's a good thing.)
532
533 =head3 param_array
534
535 This keyword doesn't exist in Dancer2.
536
537 =head3 session
538
539 In L<Dancer> a session was created and a cookie was sent just by rendering a page
540 using the C<template> function. In L<Dancer2> one needs to actually set a value in
541 a session object using the C<session> function in order to create the session
542 and send the cookie.
543
544 The session keyword has multiple states:
545
546 =over 4
547
548 =item * No arguments
549
550 Without any arguments, the session keyword returns a L<Dancer2::Core::Session>
551 object, which has methods for L<read|Dancer2::Core::Session/read>,
552 L<write|Dancer2::Core::Session/write>, and L<delete|Dancer2::Core::Session/delete>.
553
554 my $session = session;
555 $session->read($key);
556 $session->write( $key => $value );
557 $session->delete($key);
558
559 =item * Single argument (key)
560
561 If a single argument is provided, it is treated as the key, and it will retrieve
562 the value for it.
563
564 my $value = session $key;
565
566 =item * Two arguments (key, value)
567
568 If two arguments are provided, they are treated as a key and a value, in which
569 case the session will assign the value to the key.
570
571 session $key => $value;
572
573 =item * Two arguments (key, undef)
574
575 If two arguments are provided, but the second is B<undef>, the key will be
576 deleted from the session.
577
578 session $key => undef;
579
580 =back
581
582 In Dancer 1 it wasn't possible to delete a key, but in Dancer2 we can finally
583 delete:
584
585 # these two are equivalent
586 session $key => undef;
587
588 my $session = session;
589 $session->delete($key);
590
591 You can retrieve the whole session hash with the C<data> method:
592
593 $session->data;
594
595 To destroy a session, instead of writing:
596
597 session->destroy
598
599 In Dancer2, we write:
600
601 app->destroy_session if app->has_session
602
603 If you make changes to the session in an C<after> hook, your changes will
604 not be written to storage, because writing sessions to storage also takes
605 place in an (earlier) C<after> hook.
606
607 =head2 Hooks
608
609 The following Dancer 1 hooks have been renamed in Dancer2:
610
611 =over 4
612
613 =item * C<before_error_init> changed to C<init_error>.
614
615 =item * C<before_error_render> changed to C<before_error>.
616
617 =item * C<after_error_render> changed to C<after_error>.
618
619 =back
620
621 The original names are still supported, but you should change these to
622 new versions during your migration as the aliases may be removed in a
623 newer version of Dancer2.
624
625 =head1 AUTHOR
626
627 Dancer Core Developers
628
629 =head1 COPYRIGHT AND LICENSE
630
631 This software is copyright (c) 2026 by Alexis Sukrieh.
632
633 This is free software; you can redistribute it and/or modify it under
634 the same terms as the Perl 5 programming language system itself.
635
636 =cut