blib/lib/CGI/Alternatives.pm untested

filter: Statementstmt 0.0% 0 / 7 Branchbran n/a Conditioncond n/a MC/DCmcdc n/a Subroutinesub 0.0% 0 / 2 Podpod n/a totaltotal 0.0% 0 / 9 CC 1 SCAR 6.9
CC
1
Cov
0%
BEGIN
2.0
BEGIN
2.0
CRAP 2.0
1 package CGI::Alternatives;
2  
3 use strict;
4 use warnings;
5  
6 our $VERSION = '0.19';
7  
8 1;
9  
10 =head1 NAME
11  
12 CGI::Alternatives - Documentation for alternative solutions to CGI.pm
13  
14 =for html
15 <a href='https://travis-ci.org/leejo/cgi-alternatives?branch=master'><img src='https://travis-ci.org/leejo/cgi-alternatives.svg?branch=master' alt='Build Status' /></a>
16 <a href='https://coveralls.io/r/leejo/cgi-alternatives?branch=master'><img src='https://coveralls.io/repos/leejo/cgi-alternatives/badge.png?branch=master' alt='Coverage Status' /></a>
17  
18 =head1 VERSION
19  
20 0.19
21  
22 =head1 DESCRIPTION
23  
24 This module doesn't do anything, it exists solely to document alternatives
25 to the L<CGI>.pm module.
26  
27 =head1 BUT WHY?
28  
29 CGI.pm hasn't been considered good practice for many years, and there have
30 been alternatives available for web development in perl for a long time.
31 Despite this there are still some perl developers that will recommend the
32 use of CGI.pm for web development and prototyping. The two main arguments
33 for the use of CGI.pm, often given by those developers, are no longer true:
34  
35 1) "CGI.pm is a core module so you don't have install anything extra." This
36 is now incorrect as perl 5.22 has been released and no longer ships with it:
37  
38 http://perl5.git.perl.org/perl.git/commitdiff/e9fa5a80
39  
40 If you are doing any serious web development you are going to have to use
41 external dependencies, DBI is not in the core for example.
42  
43 2) "CGI.pm scripts are shorter and simpler than alternative implementations."
44 Again, not true and the following examples will show that.
45  
46 =head1 NOTE ABOUT THE EXAMPLES
47  
48 All of the following are functionally identical. They display a very simple
49 form with one text input box. When the form is submit it is redisplayed with
50 the original input displayed below the input box.
51  
52 This example may be trivial, but that is the point. The frameworks shown here
53 feature a great deal of functionality for dealing with other parts of your
54 application and dealing with that in a maintainable way, with full separation
55 of concerns and easy testing.
56  
57 All the examples are commented, where i feel it is necessary to highlight the
58 differences between the implementations, however i do not explain the details
59 of the frameworks - i would be duplicating the framework's docs if i did that,
60 so have a look at the links provided and investigate further.
61  
62 All of the examples in this documentation can be found within the examples/
63 directory within this distribution. If you want to run them you will need to
64 install the necessary CPAN modules, these are not included as dependencies in
65 this distribution.
66  
67 =head1 RAW CGI.pm EXAMPLES
68  
69 This is the base script that will be re-implemented using the other frameworks
70  
71 There are two versions - one that uses the HTML generation functions of CGI.pm
72 and one that uses Template Toolkit. This is where we get into the first issue
73 with CGI.pm - poor separation of concerns. CGI.pm (and cgi-lib.pl) existed years
74 before template engines were available in perl. As a consequence, to make the
75 generation of html easier, functions were added to output HTML direct from
76 scripts themselves. In doing this you immediately increase the maintenance
77 burden as any changes required to the HTML need to be done within the scripts.
78 You can't just hand a template to the web-designers and allow them to work their
79 magic. Don't mix the business logic and the presentation layer. Just don't.
80  
81 =head2 CGI.pm With Inline HTML Functions
82  
83 A simple example with form using the html generation functions of CGI.pm. Please
84 don't use these functions, i am merely showing them here for comparison reasons.
85  
86 #!/usr/bin/env perl
87  
88 # most CGI.pm scripts i encounter don't use strict or warnings.
89 # please don't omit these, you are asking for a world of pain
90 # somewhere down the line if you choose to develop sans strict
91 use strict;
92 use warnings;
93  
94 use CGI qw/ -utf8 /;
95  
96 my $cgi = CGI->new;
97 my $res = $cgi->param( 'user_input' );
98 my $out = $cgi->header(
99 -type => 'text/html',
100 -charset => 'utf-8',
101 );
102  
103 # html output functions. at best this is a lesson in obfuscation
104 # at worst it is an unmaintainable nightmare (and i'm using
105 # relatively clean perl code and a very very simple example here)
106 $out .= $cgi->start_html( "An Example Form" );
107  
108 $out .= $cgi->start_form(
109 -method => "post",
110 -action => "/example_form",
111 );
112  
113 $out .= $cgi->p(
114 "Say something: ",
115 $cgi->textfield( -name => 'user_input' ),
116 $cgi->br,
117 ( $res ? ( $cgi->br, "You wrote: $res" ) : () ),
118 $cgi->br,
119 $cgi->br,
120 $cgi->submit,
121 );
122  
123 $out .= $cgi->end_form;
124 $out .= $cgi->end_html;
125  
126 print $out;
127  
128 If you really want to continue using the HTML generation functionality of CGI.pm
129 then you should take a look at L<HTML::Tiny> instead, which may give you a migration
130 path away from CGI.pm's html generation functions; i strongly encourage you to
131 move towards template driven page generation for anything involving markup as
132 it will make porting your app to other frameworks much easier in the long run.
133  
134 =head2 CGI.pm Using Template Toolkit
135  
136 I'm including this example to show that it is easy to move the html
137 generation out of the raw CGI.pm script and into a template for better
138 separation of concerns.
139  
140 #!/usr/bin/env perl
141  
142 # most CGI.pm scripts i encounter don't use strict or warnings.
143 # please don't omit these, you are asking for a world of pain
144 # somewhere down the line if you choose to develop sans strict
145 use strict;
146 use warnings;
147  
148 use FindBin qw/ $Script $Bin /;
149 use Template;
150 use CGI qw/ -utf8 /;
151  
152 # necessary objects
153 my $cgi = CGI->new;
154 my $tt = Template->new({
155 INCLUDE_PATH => "$Bin/templates",
156 });
157  
158 # the user input
159 my $res = $cgi->param( 'user_input' );
160  
161 # we're using TT but we *still* need to print the Content-Type header
162 # we can't put that in the template because we need it to be reusable
163 # by the various other frameworks
164 my $out = $cgi->header(
165 -type => 'text/html',
166 -charset => 'utf-8',
167 );
168  
169 # TT will append the output to the passed referenced SCALAR
170 $tt->process(
171 "example_form.html.tt",
172 {
173 result => $res,
174 },
175 \$out,
176 ) or die $tt->error;
177  
178 print $out;
179  
180 =head2 The Template File
181  
182 Here's a key point - this template file will be re-used by B<all> the following
183 framework examples with absolutely no modifications. We can move between the
184 frameworks without having to do any porting of the HTML because it has been
185 divorced from the controller code. What did i say? Separation of concerns: win.
186  
187 <html>
188 <meta charset="utf-8">
189 <head>An Example Form</head>
190 <body>
191 <form action="/example_form" method="post">
192 <p>
193 Say something: <input name="user_input" type="text" /><br />
194 [% IF result %]
195 <br />You wrote: [% result %]
196 [% END %]
197 <br />
198 <br />
199 <input type="submit" />
200 </p>
201 </from>
202 </body>
203 </html>
204  
205 One important point to make is the action is /example_form, so the CGI.pm
206 scripts above would have to be called example_form or the webserver would
207 have to be setup to redirect routes to /example_form to whatever the cgi
208 script is called (cgi.pl and cgi_tt.pl in the examples/ directory)
209  
210 Note that I have used L<Template::Toolkit> here, another excellent template
211 engine is L<Text::Xslate>. I would B<avoid> L<Mason>(2) and L<HTML::Template>.
212 Please don't write your own template engine. If you want to completely split
213 out your html and still have some sort of templating system there are modules
214 to do that, such as L<HTML::Zoom>.
215  
216 =head1 Mojolicious
217  
218 CPAN: L<http://metacpan.org/release/Mojolicious>
219  
220 Repo: L<http://github.com/kraih/mojo>
221  
222 Home: L<http://mojolicio.us/>
223  
224 Mojolicious is a feature rich modern web framework, with no non-core
225 dependencies. It is incredibly easy to get a web app up and running with
226 Mojolicious.
227  
228 =head2 Mojolicious Lite App
229  
230 Note that we are using the TtRenderer plugin here, as by default Mojolicious
231 uses its own .ep format
232  
233 #!/usr/bin/env perl
234  
235 # automatically enables "strict", "warnings", "utf8" and perl 5.10 features
236 use Mojolicious::Lite;
237 use Mojolicious::Plugin::TtRenderer;
238  
239 # automatically render *.html.tt templates
240 plugin 'tt_renderer';
241  
242 any '/example_form' => sub {
243 my ( $self ) = @_;
244 $self->stash(
245 result => $self->param( 'user_input' )
246 );
247 };
248  
249 app->start;
250  
251 To run this script (and all the following Mojolicious examples):
252  
253 morbo examples/mojolicious_lite.pl
254  
255 That makes the page available at http://*:3000/example_form
256  
257 =head2 Mojolicious Full App
258  
259 #!/usr/bin/env perl
260  
261 # in reality this would be in a separate file
262 package ExampleApp;
263  
264 # automatically enables "strict", "warnings", "utf8" and perl 5.10 features
265 use Mojo::Base qw( Mojolicious );
266  
267 sub startup {
268 my ( $self ) = @_;
269  
270 $self->plugin( 'tt_renderer' );
271  
272 $self->routes->any('/example_form')
273 ->to('ExampleController#example_form');
274 }
275  
276 # in reality this would be in a separate file
277 package ExampleApp::ExampleController;
278  
279 use Mojo::Base 'Mojolicious::Controller';
280  
281 sub example_form {
282 my ( $self ) = @_;
283  
284 $self->stash(
285 result => $self->param( 'user_input' )
286 );
287  
288 $self->render( 'example_form' );
289 }
290  
291 # in reality this would be in a separate file
292 package main;
293  
294 use strict;
295 use warnings;
296  
297 use Mojolicious::Commands;
298  
299 Mojolicious::Commands->start_app( 'ExampleApp' );
300  
301 This is a "full fat" version of the app in Mojolicious, as stated in the
302 comments you would split the packages out into separate files in the real
303 thing. Run using:
304  
305 morbo examples/mojolicious.pl
306  
307 =head2 Mojolicious Lite App Wrapping The CGI.pm Script(s)
308  
309 #!/usr/bin/env perl
310  
311 # automatically enables "strict", "warnings", "utf8" and Perl 5.10 features
312 use Mojolicious::Lite;
313 use Mojolicious::Plugin::CGI;
314 use FindBin qw/$Bin/;
315  
316 plugin CGI => [ '/example_form' => "examples/cgi_tt.pl" ];
317  
318 app->start;
319  
320 This is an interesting example - we can wrap the existing CGI.pm scripts with
321 Mojolicious and then add new routes to the Mojolicious app - this gives us a
322 migration path. There is one thing to consider - if you are serving your cgi
323 scripts using a persistent webserver (e.g. mod_perl) then you will see a hit
324 in the performance because Mojolicious::Plugin::CGI will exec the cgi script
325 for each request. Run using:
326  
327 morbo examples/mojolicious_lite_plugin_cgi.pl
328  
329 =head1 Dancer2
330  
331 CPAN: L<https://metacpan.org/release/Dancer2>
332  
333 Repo: L<https://github.com/PerlDancer/Dancer2>
334  
335 Home: L<http://perldancer.org/>
336  
337 L<Dancer2> is a rewrite of L<Dancer>, they share a lot in common but
338 i would recommend L<Dancer2> as it solved some issues with L<Dancer>
339  
340 #!/usr/bin/env perl
341  
342 # automatically enables strict and warnings
343 use Dancer2;
344
345 any [ 'get','post' ] => '/example_form' => sub {
346  
347 template 'example_form.html.tt', {
348 'result' => params->{'user_input'}
349 };
350 };
351
352 start;
353  
354 Honestly that's just beautiful. The above example can be run with:
355  
356 perl examples/dancer2.pl
357  
358 That makes the page available at http://*:3000/example_form
359  
360 =head1 Catalyst
361  
362 CPAN: L<https://metacpan.org/release/Catalyst-Runtime>
363  
364 Repo: L<git://git.shadowcat.co.uk/catagits/Catalyst-Runtime.git>
365  
366 Home: L<http://www.catalystframework.org/>
367  
368 Catalyst is one of the older web frameworks in perl, but is still very popular,
369 actively maintained, and feature rich. It has a heavier dependency list than
370 the above frameworks, but this should not be taken as a negative point.
371  
372 Catalyst is slightly more involved in that you have to set up your entire app
373 as the first step, this involved running:
374  
375 catalyst.pl example_form
376  
377 Which will create the various directories and scripts for building/running your
378 app. You then need to add the necessary controllers, views, and templates. This
379 has all been done automatically through the use of the helper scripts that come
380 with Catalyst. The important bit, the actual example code, is just this in the
381 examples/example_form/lib/example_form/Controller/Root.pm controller:
382  
383 package example_form::Controller::Root;
384  
385 # automatically enables strict and warnings
386 use Moose;
387 use namespace::autoclean;
388  
389 BEGIN { extends 'Catalyst::Controller' }
390  
391 __PACKAGE__->config(namespace => '');
392  
393 sub example_form : Local {
394  
395 my ( $self,$c ) = @_;
396  
397 $c->stash(
398 template => 'example_form.html.tt',
399 result => $c->req->params->{user_input},
400 );
401 }
402  
403 sub end : ActionClass('RenderView') {}
404  
405 __PACKAGE__->meta->make_immutable;
406  
407 1;
408  
409 Then running the server:
410  
411 perl examples/example_form/script/example_form_server.pl
412  
413 Again makes the page available at http://*:3000/example_form
414  
415 =head1 PSGI/Plack
416  
417 Raw Plack is lower-level than Mojolicious so the code will be more verbose,
418 but Plack is probably a closer match to CGI.pm in terms of the things you're
419 having to handle.
420  
421 L<http://metacpan.org/release/PSGI>
422  
423 L<http://metacpan.org/release/Plack>
424  
425 L<http://plackperl.org/>
426  
427 PSGI is an interface between Perl web applications and web servers, and Plack
428 is a Perl module and toolkit that contains PSGI middleware, helpers and
429 adapters to web servers.
430  
431 Plack is a collection of building blocks to create web applications, ranging from
432 quick & easy scripts, to the foundations of building larger frameworks.
433  
434 =head2 Plack As A Persistent Process
435  
436 #!/usr/bin/env perl
437  
438 use strict;
439 use warnings;
440 use feature qw/ state /;
441  
442 use FindBin qw/ $Bin /;
443 use Template;
444 use Plack::Request;
445 use Plack::Response;
446  
447 my $app = sub {
448 my $req = Plack::Request->new( shift );
449 my $res = Plack::Response->new( 200 );
450  
451 state $tt = Template->new({
452 INCLUDE_PATH => "$Bin/templates",
453 });
454  
455 my $out;
456  
457 $tt->process(
458 "example_form.html.tt",
459 {
460 result => $req->parameters->{'user_input'},
461 },
462 \$out,
463 ) or die $tt->error;
464  
465 $res->headers([ 'Content-Type' => 'text/html' ]);
466 $res->body( $out );
467 $res->finalize;
468 };
469  
470 To run this script:
471  
472 plackup examples/plack_psgi.pl
473  
474 That makes the script (the "app") available at http://*:5000
475  
476 =head2 Plack As A Run On Demand CGI Script
477  
478 If your CGI script only runs once in a while, and doesn't need to be persistent,
479 then you can use Plack the same way and not have to worry about deployment
480 concerns such has having to restart a process. To do so requires adding:
481  
482 use Plack::Handler::CGI;
483 Plack::Handler::CGI->new->run($app);
484  
485 to the end of the script. This will allow it to be exec'd correctly by the
486 upfront webserver and to behave like a standalone CGI script
487  
488 =head1 Others
489  
490 The three (four) examples above are the "big three", currently very popular
491 with great communities and support. There are other frameworks available:
492  
493 L<https://metacpan.org/search?q=web+frameworks>
494  
495 =head1 Dependency Handling
496  
497 This is a whole other topic, but given CGI.pm is no longer in the perl core
498 you would have to install it anyway. It would be a good idea to do this the
499 right way from beginning. I'm not going to this in detail here, there are
500 many many good sources of information on the web. Here are some links to get
501 you started:
502  
503 Managing perl:
504  
505 L<https://github.com/tokuhirom/plenv>
506  
507 L<http://perlbrew.pl/>
508  
509 Managing perl modules:
510  
511 L<https://metacpan.org/release/App-cpanminus>
512  
513 L<https://metacpan.org/release/Carton>
514  
515 L<https://metacpan.org/pod/Pinto>
516  
517 L<https://stratopan.com/>
518  
519 L<https://metacpan.org/release/local-lib>
520  
521 =head1 BUT I DON'T WANT TO USE A FRAMEWORK
522  
523 Then take a look at L<CGI::Tiny>, specifically L<https://metacpan.org/pod/CGI::Tiny#COMPARISON-TO-CGI.PM>
524  
525 =head1 SEE ALSO
526  
527 L<Task::Kensho> - A Glimpse at an Enlightened Perl
528  
529 =head1 AUTHOR INFORMATION
530  
531 Lee Johnson - C<leejo@cpan.org> (LEEJO)
532  
533 This library is free software; you can redistribute it and/or modify it under
534 the same terms as Perl itself. If you would like to contribute documentation
535 please raise an issue / pull request:
536  
537 https://github.com/leejo/cgi-alternatives
538  
539 =cut