summaryrefslogtreecommitdiff
path: root/lib/Dancer2/Manual/Migration.pod
blob: 9663a438cc90324ee8e6b53f34e2e55a21a3c7e9 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
package Dancer2::Manual::Migration;
# ABSTRACT: Migrating from Dancer to Dancer2

use strict;
use warnings;

1;

__END__

=pod

=encoding UTF-8

=head1 NAME

Dancer2::Manual::Migration - Migrating from Dancer to Dancer2

=head1 VERSION

version 1.0.0

=head1 Migration from Dancer 1 to Dancer2

This document covers some changes that users will need to be aware of
while upgrading from L<Dancer> (version 1) to L<Dancer2>.

=head2 Launcher script

The default launcher script F<bin/app.pl> in L<Dancer> looked like this:

    #!/usr/bin/env perl
    use Dancer;
    use MyApp;
    dance;

In L<Dancer2> it is available as F<bin/app.psgi> and looks like this:

    #!/usr/bin/env perl

    use strict;
    use warnings;
    use FindBin;
    use lib "$FindBin::Bin/../lib";

    use MyApp;
    MyApp->to_app;

So you need to remove the C<use Dancer;> part, replace the C<dance;> command
by C<< MyApp->to_app; >> (where MyApp is the name of your application), and
add the following lines:

    use strict;
    use warnings;
    use FindBin;
    use lib "$FindBin::Bin/../lib";

There is a L<Dancer Advent Calendar|http://advent.perldancer.org> article
L<< covering the C<to_app> keyword|http://advent.perldancer.org/2014/9 >>
and its usage.

=head2 Configuration

You specify a different location to the directory used for serving static (public)
content by setting the C<public_dir> option. In that case, you have to set
C<static_handler> option also.

=head2 Apps

1. In L<Dancer2>, each module is a B<separate application> with its own
namespace and variables. You can set the application name in each of your
L<Dancer2> application modules. Different modules can be tied into the same
app by setting the application name to the same value.

For example, to set the appname directive explicitly:

C<MyApp>:

    package MyApp;
    use Dancer2;
    use MyApp::Admin

    hook before => sub {
        var db => 'Users';
    };

    get '/' => sub {...};

    1;

C<MyApp::Admin>:

    package MyApp::Admin;
    use Dancer2 appname => 'MyApp';

    # use a lexical prefix so we don't override it globally
    prefix '/admin' => sub {
        get '/' => sub {...};
    };

    1;

Without the appname directive, C<MyApp::Admin> would not have access
to variable C<db>. In fact, when accessing C</admin>, the before hook would
not be executed.

See L<Dancer2::Cookbook|https://metacpan.org/pod/Dancer2::Cookbook#Using-the-prefix-feature-to-split-your-application>
for details.

2. To speed up an app in Dancer2, install the recommended modules listed in the
L<Dancer2::Manual::Deployment/"Performance Improvements"> section.

=head2 Request

The request object (L<Dancer2::Core::Request>) is now deferring much of
its code to L<Plack::Request> to be consistent with the known interface
to L<PSGI> requests.

Currently the following attributes pass directly to L<Plack::Request>:

C<address>, C<remote_host>, C<protocol>, C<port>, C<method>, C<user>,
C<request_uri>, C<script_name>, C<content_length>, C<content_type>,
C<content_encoding>, C<referer>, and C<user_agent>.

If previous attributes returned I<undef> for no value beforehand, they
will return whatever L<Plack::Request> defines now, which just might be
an empty list.

For example:

    my %data = (
        referer    => request->referer,
        user_agent => request->user_agent,
    );

should be replaced by:

    my %data = (
        referer    => request->referer    || '',
        user_agent => request->user_agent || '',
    );

=head2 Plugins: plugin_setting

C<plugin_setting> returns the configuration of the plugin. It can only be
called in C<register> or C<on_plugin_import>.

=head2 Routes

L<Dancer2> requires all routes defined via a string to begin with a leading
slash C</>.

For example:

    get '0' => sub {
        return "not gonna fly";
    };

would return an error. The correct way to write this would be to use
C<get '/0'>

=head2 Route parameters

The C<params> keyword which provides merged parameters used to allow body
parameters to override route parameters. Now route parameters take
precedence over query parameters and body parameters.

We have introduced C<route_parameters> to retrieve parameter values from
the route matching. Please refer to L<Dancer2::Manual> for more
information.

=head2 Tests

Dancer2 recommends the use of L<Plack::Test>.

For example:

    use strict;
    use warnings;
    use Test::More tests => 2;
    use Plack::Test;
    use HTTP::Request::Common;

    {
        package App::Test; # or whatever you want to call it
        get '/' => sub { template 'index' };
    }

    my $test = Plack::Test->create( App::Test->to_app );
    my $res  = $test->request( GET '/' );

    ok( $res->is_success, '[GET /] Successful' );
    like( $res->content, qr{<title>Test2</title>}, 'Correct title' );

Other modules that could be used for testing are:

=over 4

=item * L<Test::TCP>

=item * L<Test::WWW::Mechanize::PSGI>

=back

=head3 Logs

The C<logger_format> in the Logger role (L<Dancer2::Core::Role::Logger>)
is now C<log_format>.

C<read_logs> can no longer be used, as with L<Dancer2::Test>. Instead,
L<Dancer2::Logger::Capture> could be used for testing, to capture all
logs to an object.

For example:

    use strict;
    use warnings;
    use Test::More import => ['!pass'];
    use Plack::Test;
    use HTTP::Request::Common;
    use Ref::Util qw<is_coderef>;

    {
        package App;
        use Dancer2;

        set log       => 'debug';
        set logger    => 'capture';

        get '/' => sub {
            debug 'this is my debug message';
            return 1;
        };
    }

    my $app = Dancer2->psgi_app;
    ok( is_coderef($app), 'Got app' );

    test_psgi $app, sub {
        my $cb = shift;

        my $res = $cb->( GET '/' );
        is $res->code, 200;

        my $trap = App->dancer_app->logger_engine->trapper;

        is_deeply $trap->read, [
            { level => 'debug', message => 'this is my debug message' }
        ];
    };

=head2 Exports: Tags

The following tags are not needed in L<Dancer2>:

 use Dancer2 qw(:syntax);
 use Dancer2 qw(:tests);
 use Dancer2 qw(:script);

The C<plackup> command should be used instead. It provides a development
server and reads the configuration options in your command line utilities.

=head2 Engines

=over 4

=item * Engines receive a logging callback

Engines now receive a logging callback named C<log_cb>. Engines can use it
to log anything in run-time, without having to worry about what logging
engine is used.

This is provided as a callback because the logger might be changed in
run-time and we want engines to be able to always reach the current one
without having a reference back to the core application object.

The logger engine doesn't have the attribute since it is the logger itself.

=item * Engines handle encoding consistently

All engines are now expected to handle encoding on their own. User code
is expected to be in internal Perl representation.

Therefore, all serializers, for example, should deserialize to the Perl
representation. Templates, in turn, encode to UTF-8 if requested by the
user, or by default.

One side-effect of this is that C<from_yaml> will call L<YAML>'s C<Load>
function with decoded input.

=back

=head3 Templating engine changes

Whereas in Dancer1, the following were equivalent for Template::Toolkit:

    template 'foo/bar'
    template '/foo/bar'

In Dancer2, when using L<Dancer2::Template::TemplateToolkit>, the version with
the leading slash will try to locate C</foo/bar> relative to your filesystem
root, not relative to your Dancer application directory.

The L<Dancer2::Template::Simple> engine is unchanged in this respect.

Whereas in Dancer1, template engines have the methods:

    $template_engine->view('foo.tt')
    $template_engine->view_exists('foo.tt')

In Dancer2, you should instead write:

    $template_engine->view_pathname('foo.tt')
    $template_engine->pathname_exists($full_path)

You may not need these unless you are writing a templating engine.

=head3 Serializers

You no longer need to implement the C<loaded> method. It is simply
unnecessary.

=head3 Sessions

Now the L<Simple|Dancer2::Session::Simple> session engine is turned on
by default, unless you specify a different one.

=head2 Configuration

=head3 C<public_dir>

You cannot set the public directory with C<setting> now. Instead you
will need to call C<config>:

    # before
    setting( 'public_dir', 'new_path/' );

    # after
    config->{'public_dir'} = 'new_path';

=head3 warnings

The C<warnings> configuration option, along with the environment variable
C<DANCER_WARNINGS>, have been removed and have no effect whatsoever.

They were added when someone requested to be able to load Dancer without
the L<warnings> pragma, which it adds, just like L<Moose>, L<Moo>, and
other modules provide.

If you want this to happen now (which you probably shouldn't be doing),
you can always control it lexically:

    use Dancer2;
    no warnings;

You can also use Dancer2 within a narrower scope:

    { use Dancer2 }
    use strict;
    # warnings are not turned on

However, having L<warnings> turned it is very recommended.

=head3 server_tokens

The configuration C<server_tokens> has been introduced in the reverse (but
more sensible, and Plack-compatible) form as C<no_server_tokens>.

C<DANCER_SERVER_TOKENS> changed to C<DANCER_NO_SERVER_TOKENS>.

=head3 engines

If you want to use Template::Toolkit instead of the built-in simple templating
engine you used to enable the following line in the config.yml file.

    template: "template_toolkit"

That was enough to get started. The start_tag and end_tag it used were the same as in
the simple template <% and %> respectively.

If you wanted to further customize the Template::Toolkit you could also enable or add
the following:

    engines:
      template_toolkit:
         encoding:  'utf8'
         start_tag: '[%'
         end_tag:   '%]'

In Dancer 2 you can also enable Template::Toolkit with the same configuration option:

    template: "template_toolkit"

But the default start_tag and end_tag are now [% and %], so if you used the default in Dancer 1
now you will have to explicitly change the start_tag and end_tag values.
The configuration also got an extra level of depth. Under the C<engine> key there is a C<template>
key and the C<template_toolkit> key comes below that. As in this example:

    engines:
      template:
        template_toolkit:
          start_tag: '<%'
          end_tag:   '%>'

In a nutshell, if you used to have

    template: "template_toolkit"

You need to replace it with

    template: "template_toolkit"
    engines:
      template:
        template_toolkit:
          start_tag: '<%'
          end_tag:   '%>'

=head4 Session engine

The session engine is configured in the C<engine> section.

=over 4

=item * C<session_name> changed to C<cookie_name>.

=item * C<session_domain> changed to C<cookie_domain>.

=item * C<session_expires> changed to C<cookie_duration>.

=item * C<session_secure> changed to C<is_secure>.

=item * C<session_is_http_only> changed to C<is_http_only>.

=back

L<Dancer2> also adds two attributes for session:

=over 4

=item * C<cookie_path>
The path of the cookie to create for storing the session key. Defaults to "/".

=item * C<session_duration>
Duration in seconds before sessions should expire, regardless of cookie
expiration. If set, then SessionFactories should use this to enforce a limit on
session validity.

=back

See L<Dancer2::Core::Role::SessionFactory> for more detailed documentation
for these options, or the particular session engine for other supported options.

  session: Simple

  engines:
    session:
      Simple:
        cookie_name: dance.set
        cookie_duration: '24 hours'
        is_secure: 1
        is_http_only: 1

=head3 Plack Middleware

In Dancer1 you could set up Plack Middleware using a C<plack_middlewares> key
in your C<config.yml> file. Under Dancer2 you will instead need to invoke
middleware using L<Plack::Builder>, as demonstrated in
L<Dancer2::Manual::Deployment>.

=head2 Keywords

=head3 Calling Keywords Explicitly

In Dancer1, keywords could be imported individually into a package:

    package MyApp;
    use Dancer qw< get post params session >;

    get '/foo' { ... };

Any keywords you did't export could be called explicitly:

    package MyApp;
    use Dancer qw< get post params session >;
    use List::Util qw< any >;

    Dancer::any sub { ... };

Dancer2's DSL is implemented differently. Keywords only exist in the namespace
of the package which C<use>s Dancer2, i.e. there is no C<Dancer2::any>, only
e.g. C<MyApp::any>.

If you only want individual keywords, you can write a shim as follows:

    package MyApp::DSL;
    use Dancer2 appname => 'MyApp';

    use Exporter qw< import >;

    our @EXPORT = qw< get post ... >

Then in other packages:

    package MyApp;

    use MyApp::DSL qw< get post >;

    MyApp::DSL::any sub { ... };

=head3 appdir

This keyword does not exist in Dancer2. However, the same information can be
found in C<< config->{'appdir'} >>.

=head3 load

This keyword is no longer required. Dancer2 loads the environment
automatically and will not reload any other environment when called with
L<load>. (It's a good thing.)

=head3 param_array

This keyword doesn't exist in Dancer2.

=head3 session

In L<Dancer> a session was created and a cookie was sent just by rendering a page
using the C<template> function. In L<Dancer2> one needs to actually set a value in
a session object using the C<session> function in order to create the session
and send the cookie.

The session keyword has multiple states:

=over 4

=item * No arguments

Without any arguments, the session keyword returns a L<Dancer2::Core::Session>
object, which has methods for L<read|Dancer2::Core::Session/read>, 
L<write|Dancer2::Core::Session/write>, and L<delete|Dancer2::Core::Session/delete>.

    my $session = session;
    $session->read($key);
    $session->write( $key => $value );
    $session->delete($key);

=item * Single argument (key)

If a single argument is provided, it is treated as the key, and it will retrieve
the value for it.

    my $value = session $key;

=item * Two arguments (key, value)

If two arguments are provided, they are treated as a key and a value, in which
case the session will assign the value to the key.

    session $key => $value;

=item * Two arguments (key, undef)

If two arguments are provided, but the second is B<undef>, the key will be
deleted from the session.

    session $key => undef;

=back

In Dancer 1 it wasn't possible to delete a key, but in Dancer2 we can finally
delete:

    # these two are equivalent
    session $key => undef;

    my $session = session;
    $session->delete($key);

You can retrieve the whole session hash with the C<data> method:

    $session->data;

To destroy a session, instead of writing:

    session->destroy

In Dancer2, we write:

    app->destroy_session if app->has_session

If you make changes to the session in an C<after> hook, your changes will
not be written to storage, because writing sessions to storage also takes
place in an (earlier) C<after> hook.

=head1 AUTHOR

Dancer Core Developers

=head1 COPYRIGHT AND LICENSE

This software is copyright (c) 2023 by Alexis Sukrieh.

This is free software; you can redistribute it and/or modify it under
the same terms as the Perl 5 programming language system itself.

=cut