light Cookbook work
[catagits/Catalyst-Runtime.git] / lib / Catalyst / Manual / Cookbook.pod
1
2 =head1 NAME
3
4 Catalyst::Manual::Cookbook - Cooking with Catalyst
5
6 =head1 DESCRIPTION
7
8 Yummy code like your mum used to bake!
9
10 =head1 RECIPES
11
12 =head2 Force debug screen
13
14 You can force Catalyst to display the debug screen at the end of the
15 request by placing a C<die()> call in the C<end> action.
16
17      sub end : Private {
18          my ( $self, $c ) = @_;
19          die "forced debug";
20      }
21
22 If you're tired of removing and adding this all the time, you can add a
23 condition in the C<end> action. For example:
24
25     sub end : Private {  
26         my ( $self, $c ) = @_;  
27         die "forced debug" if $c->req->params->{dump_info};  
28     }  
29
30 Then just add to your query string C<&dump_info=1> (or if there's no
31 query string for the request, add C<?dump_info=1> to the end of the URL)
32 to force debug output. This feature is included in
33 L<Catalyst::Action::RenderView> (formerly
34 L<Catalyst::Plugin::DefaultEnd>).
35
36
37 =head2 Disable statistics
38
39 Just add this line to your application class if you don't want those nifty
40 statistics in your debug messages.
41
42     sub Catalyst::Log::info { }
43
44 =head2 Enable debug status in the environment
45
46 Normally you enable the debugging info by adding the C<-Debug> flag to
47 your C<use Catalyst> statement. However, you can also enable it using
48 environment variable, so you can (for example) get debug info without
49 modifying your application scripts. Just set C<CATALYST_DEBUG> or
50 C<E<lt>MYAPPE<gt>_DEBUG> to a true value.
51
52 =head2 File uploads
53
54 =head3 Single file upload with Catalyst
55
56 To implement uploads in Catalyst, you need to have a HTML form similar to
57 this:
58
59     <form action="/upload" method="post" enctype="multipart/form-data">
60       <input type="hidden" name="form_submit" value="yes">
61       <input type="file" name="my_file">
62       <input type="submit" value="Send">
63     </form>
64
65 It's very important not to forget C<enctype="multipart/form-data"> in
66 the form.
67
68 Catalyst Controller module 'upload' action:
69
70     sub upload : Global {
71         my ($self, $c) = @_;
72
73         if ( $c->request->parameters->{form_submit} eq 'yes' ) {
74
75             if ( my $upload = $c->request->upload('my_file') ) {
76
77                 my $filename = $upload->filename;
78                 my $target   = "/tmp/upload/$filename";
79
80                 unless ( $upload->link_to($target) || $upload->copy_to($target) ) {
81                     die( "Failed to copy '$filename' to '$target': $!" );
82                 }
83             }
84         }
85
86         $c->stash->{template} = 'file_upload.html';
87     }
88
89 =head3 Multiple file upload with Catalyst
90
91 Code for uploading multiple files from one form needs a few changes:
92
93 The form should have this basic structure:
94
95     <form action="/upload" method="post" enctype="multipart/form-data">
96       <input type="hidden" name="form_submit" value="yes">
97       <input type="file" name="file1" size="50"><br>
98       <input type="file" name="file2" size="50"><br>
99       <input type="file" name="file3" size="50"><br>
100       <input type="submit" value="Send">
101     </form>
102
103 And in the controller:
104
105     sub upload : Local {
106         my ($self, $c) = @_;
107
108         if ( $c->request->parameters->{form_submit} eq 'yes' ) {
109
110             for my $field ( $c->req->upload ) {
111
112                 my $upload   = $c->req->upload($field);
113                 my $filename = $upload->filename;
114                 my $target   = "/tmp/upload/$filename";
115
116                 unless ( $upload->link_to($target) || $upload->copy_to($target) ) {
117                     die( "Failed to copy '$filename' to '$target': $!" );
118                 }
119             }
120         }
121
122         $c->stash->{template} = 'file_upload.html';
123     }
124
125 C<for my $field ($c-E<gt>req->upload)> loops automatically over all file
126 input fields and gets input names. After that is basic file saving code,
127 just like in single file upload.
128
129 Notice: C<die>ing might not be what you want to do, when an error
130 occurs, but it works as an example. A better idea would be to store
131 error C<$!> in $c->stash->{error} and show a custom error template
132 displaying this message.
133
134 For more information about uploads and usable methods look at
135 L<Catalyst::Request::Upload> and L<Catalyst::Request>.
136
137 =head2 Authentication (logging in)
138
139 This is extensively covered in other documentation; see in particular
140 L<Catalyst::Plugin::Authentication> and the Authentication chapter
141 of the Tutorial at L<Catalyst::Manual::Tutorial::Authorization>.
142
143 =head2 Pass-through login (and other actions)
144
145 An easy way of having assorted actions that occur during the processing
146 of a request that are orthogonal to its actual purpose - logins, silent
147 commands etc. Provide actions for these, but when they're required for
148 something else fill e.g. a form variable __login and have a sub begin
149 like so:
150
151     sub begin : Private {
152       my ($self, $c) = @_;
153       foreach my $action (qw/login docommand foo bar whatever/) {
154         if ($c->req->params->{"__${action}"}) {
155           $c->forward($action);
156         }
157       }
158     }
159
160
161 =head2 Serving static content
162
163 Serving static content in Catalyst used to be somewhat tricky; the use
164 of L<Catalyst::Plugin::Static::Simple> makes everything much easier.
165 This plugin will automatically serve your static content during development,
166 but allows you to easily switch to Apache (or other server) in a
167 production environment.
168
169 =head3 Introduction to Static::Simple
170
171 Static::Simple is a plugin that will help to serve static content for your
172 application. By default, it will serve most types of files, excluding some
173 standard Template Toolkit extensions, out of your B<root> file directory. All
174 files are served by path, so if B<images/me.jpg> is requested, then
175 B<root/images/me.jpg> is found and served.
176
177 =head3 Usage
178
179 Using the plugin is as simple as setting your use line in MyApp.pm to include:
180
181  use Catalyst qw/Static::Simple/;
182
183 and already files will be served.
184
185 =head3 Configuring
186
187 Static content is best served from a single directory within your root
188 directory. Having many different directories such as C<root/css> and
189 C<root/images> requires more code to manage, because you must separately
190 identify each static directory--if you decide to add a C<root/js>
191 directory, you'll need to change your code to account for it. In
192 contrast, keeping all static directories as subdirectories of a main
193 C<root/static> directory makes things much easier to manage. Here's an
194 example of a typical root directory structure:
195
196     root/
197     root/content.tt
198     root/controller/stuff.tt
199     root/header.tt
200     root/static/
201     root/static/css/main.css
202     root/static/images/logo.jpg
203     root/static/js/code.js
204
205
206 All static content lives under C<root/static>, with everything else being
207 Template Toolkit files.
208
209 =over 4
210
211 =item Include Path
212
213 You may of course want to change the default locations, and make
214 Static::Simple look somewhere else, this is as easy as:
215
216  MyApp->config->{static}->{include_path} = [
217   MyApp->config->{root},
218   '/path/to/my/files' 
219  ];
220
221 When you override include_path, it will not automatically append the
222 normal root path, so you need to add it yourself if you still want
223 it. These will be searched in order given, and the first matching file
224 served.
225
226 =item Static directories
227
228 If you want to force some directories to be only static, you can set
229 them using paths relative to the root dir, or regular expressions:
230
231  MyApp->config->{static}->{dirs} = [
232    'static',
233    qr/^(images|css)/,
234  ];
235
236 =item File extensions
237
238 By default, the following extensions are not served (that is, they will
239 be processed by Catalyst): B<tmpl, tt, tt2, html, xhtml>. This list can
240 be replaced easily:
241
242  MyApp->config->{static}->{ignore_extensions} = [
243     qw/tmpl tt tt2 html xhtml/ 
244  ];
245
246 =item Ignoring directories
247
248 Entire directories can be ignored. If used with include_path,
249 directories relative to the include_path dirs will also be ignored:
250
251  MyApp->config->{static}->{ignore_dirs} = [ qw/tmpl css/ ];
252
253 =back
254
255 =head3 More information
256
257 L<http://search.cpan.org/dist/Catalyst-Plugin-Static-Simple/>
258
259 =head3 Serving manually with the Static plugin with HTTP::Daemon (myapp_server.pl)
260
261 In some situations you might want to control things more directly,
262 using L<Catalyst::Plugin::Static>.
263
264 In your main application class (MyApp.pm), load the plugin:
265
266     use Catalyst qw/-Debug FormValidator Static OtherPlugin/;
267
268 You will also need to make sure your end method does I<not> forward
269 static content to the view, perhaps like this:
270
271     sub end : Private {
272         my ( $self, $c ) = @_;
273
274         $c->forward( 'MyApp::View::TT' ) 
275           unless ( $c->res->body || !$c->stash->{template} );
276     }
277
278 This code will only forward to the view if a template has been
279 previously defined by a controller and if there is not already data in
280 C<$c-E<gt>res-E<gt>body>.
281
282 Next, create a controller to handle requests for the /static path. Use
283 the Helper to save time. This command will create a stub controller as
284 C<lib/MyApp/Controller/Static.pm>.
285
286     $ script/myapp_create.pl controller Static
287
288 Edit the file and add the following methods:
289
290     # serve all files under /static as static files
291     sub default : Path('/static') {
292         my ( $self, $c ) = @_;
293
294         # Optional, allow the browser to cache the content
295         $c->res->headers->header( 'Cache-Control' => 'max-age=86400' );
296
297         $c->serve_static; # from Catalyst::Plugin::Static
298     }
299
300     # also handle requests for /favicon.ico
301     sub favicon : Path('/favicon.ico') {
302         my ( $self, $c ) = @_;
303
304         $c->serve_static;
305     }
306
307 You can also define a different icon for the browser to use instead of
308 favicon.ico by using this in your HTML header:
309
310     <link rel="icon" href="/static/myapp.ico" type="image/x-icon" />
311
312 =head3 Common problems with the Static plugin
313
314 The Static plugin makes use of the C<shared-mime-info> package to
315 automatically determine MIME types. This package is notoriously
316 difficult to install, especially on win32 and OS X. For OS X the easiest
317 path might be to install Fink, then use C<apt-get install
318 shared-mime-info>. Restart the server, and everything should be fine.
319
320 Make sure you are using the latest version (>= 0.16) for best
321 results. If you are having errors serving CSS files, or if they get
322 served as text/plain instead of text/css, you may have an outdated
323 shared-mime-info version. You may also wish to simply use the following
324 code in your Static controller:
325
326     if ($c->req->path =~ /css$/i) {
327         $c->serve_static( "text/css" );
328     } else {
329         $c->serve_static;
330     }
331
332 =head3 Serving Static Files with Apache
333
334 When using Apache, you can bypass Catalyst and any Static
335 plugins/controllers controller by intercepting requests for the
336 C<root/static> path at the server level. All that is required is to
337 define a DocumentRoot and add a separate Location block for your static
338 content. Here is a complete config for this application under mod_perl
339 1.x:
340
341     <Perl>
342         use lib qw(/var/www/MyApp/lib);
343     </Perl>
344     PerlModule MyApp
345
346     <VirtualHost *>
347         ServerName myapp.example.com
348         DocumentRoot /var/www/MyApp/root
349         <Location />
350             SetHandler perl-script
351             PerlHandler MyApp
352         </Location>
353         <LocationMatch "/(static|favicon.ico)">
354             SetHandler default-handler
355         </LocationMatch>
356     </VirtualHost>
357
358 And here's a simpler example that'll get you started:
359
360     Alias /static/ "/my/static/files/"
361     <Location "/static">
362         SetHandler none
363     </Location>
364
365 =head2 Forwarding with arguments
366
367 Sometimes you want to pass along arguments when forwarding to another
368 action. As of version 5.30, arguments can be passed in the call to
369 C<forward>; in earlier versions, you can manually set the arguments in
370 the Catalyst Request object:
371
372   # version 5.30 and later:
373   $c->forward('/wherever', [qw/arg1 arg2 arg3/]);
374
375   # pre-5.30
376   $c->req->args([qw/arg1 arg2 arg3/]);
377   $c->forward('/wherever');
378
379 (See the L<Catalyst::Manual::Intro> Flow_Control section for more 
380 information on passing arguments via C<forward>.)
381
382 =head2 Configure your application
383
384 You configure your application with the C<config> method in your
385 application class. This can be hard-coded, or brought in from a
386 separate configuration file.
387
388 =head3 Using YAML
389
390 YAML is a method for creating flexible and readable configuration
391 files. It's a great way to keep your Catalyst application configuration
392 in one easy-to-understand location.
393
394 In your application class (e.g. C<lib/MyApp.pm>):
395
396   use YAML;
397   # application setup
398   __PACKAGE__->config( YAML::LoadFile(__PACKAGE__->config->{'home'} . '/myapp.yml') );
399   __PACKAGE__->setup;
400
401 Now create C<myapp.yml> in your application home:
402
403   --- #YAML:1.0
404   # DO NOT USE TABS FOR INDENTATION OR label/value SEPARATION!!!
405   name:     MyApp
406
407   # session; perldoc Catalyst::Plugin::Session::FastMmap
408   session:
409     expires:        '3600'
410     rewrite:        '0'
411     storage:        '/tmp/myapp.session'
412
413   # emails; perldoc Catalyst::Plugin::Email
414   # this passes options as an array :(
415   email:
416     - SMTP
417     - localhost
418
419 This is equivalent to:
420
421   # configure base package
422   __PACKAGE__->config( name => MyApp );
423   # configure authentication
424   __PACKAGE__->config->{authentication} = {
425     user_class => 'MyApp::Model::MyDB::Customer',
426     ...
427   };
428   # configure sessions
429   __PACKAGE__->config->{session} = {
430     expires => 3600,
431     ...
432   };
433   # configure email sending
434   __PACKAGE__->config->{email} = [qw/SMTP localhost/];
435
436 See also L<YAML>.
437
438 =head2 Using existing DBIC (etc.) classes with Catalyst
439
440 Many people have existing Model classes that they would like to use with
441 Catalyst (or, conversely, they want to write Catalyst models that can be
442 used outside of Catalyst, e.g.  in a cron job). It's trivial to write a
443 simple component in Catalyst that slurps in an outside Model:
444
445     package MyApp::Model::DB;
446     use base qw/Catalyst::Model::DBIC::Schema/;
447     __PACKAGE__->config(
448         schema_class => 'Some::DBIC::Schema',
449         connect_info => ['dbi:SQLite:foo.db', '', '', {AutoCommit=>1}];
450     );
451     1;
452
453 and that's it! Now C<Some::DBIC::Schema> is part of your
454 Cat app as C<MyApp::Model::DB>.
455
456 =head2 Delivering a Custom Error Page
457
458 By default, Catalyst will display its own error page whenever it
459 encounters an error in your application. When running under C<-Debug>
460 mode, the error page is a useful screen including the error message and
461 L<Data::Dump> output of the relevant parts of the C<$c> context object. 
462 When not in C<-Debug>, users see a simple "Please come back later" screen.
463
464 To use a custom error page, use a special C<end> method to short-circuit
465 the error processing. The following is an example; you might want to
466 adjust it further depending on the needs of your application (for
467 example, any calls to C<fillform> will probably need to go into this
468 C<end> method; see L<Catalyst::Plugin::FillInForm>).
469
470     sub end : Private {
471         my ( $self, $c ) = @_;
472
473         if ( scalar @{ $c->error } ) {
474             $c->stash->{errors}   = $c->error;
475             $c->stash->{template} = 'errors.tt';
476             $c->forward('MyApp::View::TT');
477             $c->error(0);
478         }
479
480         return 1 if $c->response->status =~ /^3\d\d$/;
481         return 1 if $c->response->body;
482
483         unless ( $c->response->content_type ) {
484             $c->response->content_type('text/html; charset=utf-8');
485         }
486
487         $c->forward('MyApp::View::TT');
488     }
489
490 You can manually set errors in your code to trigger this page by calling
491
492     $c->error( 'You broke me!' );
493
494 =head2 Role-based Authorization
495
496 For more advanced access control, you may want to consider using role-based
497 authorization. This means you can assign different roles to each user, e.g.
498 "user", "admin", etc.
499
500 The C<login> and C<logout> methods and view template are exactly the same as
501 in the previous example.
502
503 The L<Catalyst::Plugin::Authorization::Roles> plugin is required when
504 implementing roles:
505
506  use Catalyst qw/
507     Authentication
508     Authentication::Credential::Password
509     Authentication::Store::Htpasswd
510     Authorization::Roles
511   /;
512
513 Roles are implemented automatically when using
514 L<Catalyst::Authentication::Store::Htpasswd>:
515
516   # no additional role configuration required
517   __PACKAGE__->config->{authentication}{htpasswd} = "passwdfile";
518
519 Or can be set up manually when using L<Catalyst::Authentication::Store::DBIC>:
520
521   # Authorization using a many-to-many role relationship
522   __PACKAGE__->config->{authorization}{dbic} = {
523     'role_class'           => 'My::Model::DBIC::Role',
524     'role_field'           => 'name',
525     'user_role_user_field' => 'user',
526
527     # DBIx::Class only (omit if using Class::DBI)
528     'role_rel'             => 'user_role',
529
530     # Class::DBI only, (omit if using DBIx::Class)
531     'user_role_class'      => 'My::Model::CDBI::UserRole'
532     'user_role_role_field' => 'role',
533   };
534
535 To restrict access to any action, you can use the C<check_user_roles> method:
536
537   sub restricted : Local {
538      my ( $self, $c ) = @_;
539
540      $c->detach("unauthorized")
541        unless $c->check_user_roles( "admin" );
542
543      # do something restricted here
544   }
545
546 You can also use the C<assert_user_roles> method. This just gives an error if
547 the current user does not have one of the required roles:
548
549   sub also_restricted : Global {
550     my ( $self, $c ) = @_;
551     $c->assert_user_roles( qw/ user admin / );
552   }
553   
554 =head2 Quick deployment: Building PAR Packages
555
556 You have an application running on your development box, but then you
557 have to quickly move it to another one for
558 demonstration/deployment/testing...
559
560 PAR packages can save you from a lot of trouble here. They are usual Zip
561 files that contain a blib tree; you can even include all prereqs and a
562 perl interpreter by setting a few flags!
563
564 =head3 Follow these few points to try it out!
565
566 1. Install Catalyst and PAR 0.89 (or later)
567
568     % perl -MCPAN -e 'install Catalyst'
569     ...
570     % perl -MCPAN -e 'install PAR'
571     ...
572
573 2. Create a application
574
575     % catalyst.pl MyApp
576     ...
577     % cd MyApp
578
579 3. Add these lines to Makefile.PL (below "catalyst_files();")
580
581     catalyst_par_core();   # Include modules that are also included
582                            # in the standard Perl distribution,
583                            # this is optional but highly suggested
584
585     catalyst_par();        # Generate a PAR as soon as the blib
586                            # directory is ready
587
588 4. Prepare the Makefile, test your app, create a PAR (the two
589 Makefile.PL calls are no typo)
590
591     % perl Makefile.PL
592     ...
593     % make test
594     ...
595     % perl Makefile.PL
596     ...
597
598 Recent versions of Catalyst include L<Module::Install::Catalyst>, which
599 simplifies the process greatly.
600
601     % perl Makefile.PL
602     ...
603     % make catalyst_par
604     ...
605
606 Congratulations! Your package "myapp.par" is ready, the following
607 steps are just optional.
608
609 5. Test your PAR package with "parl" (no typo)
610
611     % parl myapp.par
612     Usage:
613         [parl] myapp[.par] [script] [arguments]
614
615       Examples:
616         parl myapp.par myapp_server.pl -r
617         myapp myapp_cgi.pl
618
619       Available scripts:
620         myapp_cgi.pl
621         myapp_create.pl
622         myapp_fastcgi.pl
623         myapp_server.pl
624         myapp_test.pl
625
626     % parl myapp.par myapp_server.pl
627     You can connect to your server at http://localhost:3000
628
629 Yes, this nifty little starter application gets automatically included.
630 You can also use "catalyst_par_script('myapp_server.pl')" to set a
631 default script to execute.
632
633 6. Want to create a binary that includes the Perl interpreter?
634
635     % pp -o myapp myapp.par
636     % ./myapp myapp_server.pl
637     You can connect to your server at http://localhost:3000
638
639 =head2 mod_perl Deployment
640
641 In today's entry, I'll be talking about deploying an application in
642 production using Apache and mod_perl.
643
644 =head3 Pros & Cons
645
646 mod_perl is the best solution for many applications, but I'll list some pros
647 and cons so you can decide for yourself.  The other production deployment
648 option is FastCGI, which I'll talk about in a future calendar article.
649
650 =head4 Pros
651
652 =head4 Speed
653
654 mod_perl is very fast and your app will benefit from being loaded in memory
655 within each Apache process.
656
657 =head4 Shared memory for multiple apps
658
659 If you need to run several Catalyst apps on the same server, mod_perl will
660 share the memory for common modules.
661
662 =head4 Cons
663
664 =head4 Memory usage
665
666 Since your application is fully loaded in memory, every Apache process will
667 be rather large.  This means a large Apache process will be tied up while
668 serving static files, large files, or dealing with slow clients.  For this
669 reason, it is best to run a two-tiered web architecture with a lightweight
670 frontend server passing dynamic requests to a large backend mod_perl
671 server.
672
673 =head4 Reloading
674
675 Any changes made to the core code of your app require a full Apache restart.
676 Catalyst does not support Apache::Reload or StatINC.  This is another good
677 reason to run a frontend web server where you can set up an
678 C<ErrorDocument 502> page to report that your app is down for maintenance.
679
680 =head4 Cannot run multiple versions of the same app
681
682 It is not possible to run two different versions of the same application in
683 the same Apache instance because the namespaces will collide.
684
685 =head4 Setup
686
687 Now that we have that out of the way, let's talk about setting up mod_perl
688 to run a Catalyst app.
689
690 =head4 1. Install Catalyst::Engine::Apache
691
692 You should install the latest versions of both Catalyst and 
693 Catalyst::Engine::Apache.  The Apache engines were separated from the
694 Catalyst core in version 5.50 to allow for updates to the engine without
695 requiring a new Catalyst release.
696
697 =head4 2. Install Apache with mod_perl
698
699 Both Apache 1.3 and Apache 2 are supported, although Apache 2 is highly
700 recommended.  With Apache 2, make sure you are using the prefork MPM and not
701 the worker MPM.  The reason for this is that many Perl modules are not
702 thread-safe and may have problems running within the threaded worker
703 environment.  Catalyst is thread-safe however, so if you know what you're
704 doing, you may be able to run using worker.
705
706 In Debian, the following commands should get you going.
707
708     apt-get install apache2-mpm-prefork
709     apt-get install libapache2-mod-perl2
710
711 =head4 3. Configure your application
712
713 Every Catalyst application will automagically become a mod_perl handler
714 when run within mod_perl.  This makes the configuration extremely easy.
715 Here is a basic Apache 2 configuration.
716
717     PerlSwitches -I/var/www/MyApp/lib
718     PerlModule MyApp
719     
720     <Location />
721         SetHandler          modperl
722         PerlResponseHandler MyApp
723     </Location>
724
725 The most important line here is C<PerlModule MyApp>.  This causes mod_perl
726 to preload your entire application into shared memory, including all of your
727 controller, model, and view classes and configuration.  If you have -Debug
728 mode enabled, you will see the startup output scroll by when you first
729 start Apache.
730
731 For an example Apache 1.3 configuration, please see the documentation for
732 L<Catalyst::Engine::Apache::MP13>.
733
734 =head3 Test It
735
736 That's it, your app is now a full-fledged mod_perl application!  Try it out
737 by going to http://your.server.com/.
738
739 =head3 Other Options
740
741 =head4 Non-root location
742
743 You may not always want to run your app at the root of your server or virtual
744 host.  In this case, it's a simple change to run at any non-root location
745 of your choice.
746
747     <Location /myapp>
748         SetHandler          modperl
749         PerlResponseHandler MyApp
750     </Location>
751     
752 When running this way, it is best to make use of the C<uri_for> method in
753 Catalyst for constructing correct links.
754
755 =head4 Static file handling
756
757 Static files can be served directly by Apache for a performance boost.
758
759     DocumentRoot /var/www/MyApp/root
760     <Location /static>
761         SetHandler default-handler
762     </Location>
763     
764 This will let all files within root/static be handled directly by Apache.  In
765 a two-tiered setup, the frontend server should handle static files.
766 The configuration to do this on the frontend will vary.
767
768 =head2 Extending RenderView (formerly DefaultEnd)
769
770 The recommended approach for an C<end> action is to use
771 L<Catalyst::Action::RenderView> (taking the place of
772 L<Catalyst::Plugin::DefaultEnd>), which does what you usually need.
773 However there are times when you need to add a bit to it, but don't want
774 to write your own C<end> action.
775
776 You can extend it like this:
777
778 To add something to an C<end> action that is called before rendering
779 (this is likely to be what you want), simply place it in the C<end>
780 method:
781
782     sub end : ActionClass('RenderView') {
783       my ( $self, $c ) = @_;
784       # do stuff here; the RenderView action is called afterwards
785     }
786
787 To add things to an C<end> action that are called I<after> rendering,
788 you can set it up like this:
789
790     sub render : ActionClass('RenderView') { }
791
792     sub end : Private { 
793       my ( $self, $c ) = @_;
794       $c->forward('render');
795       # do stuff here
796     }
797   
798 =head2 Catalyst on shared hosting
799
800 So, you want to put your Catalyst app out there for the whole world to
801 see, but you don't want to break the bank. There is an answer - if you
802 can get shared hosting with FastCGI and a shell, you can install your
803 Catalyst app in a local directory on your shared host. First, run
804
805     perl -MCPAN -e shell
806
807 and go through the standard CPAN configuration process. Then exit out
808 without installing anything. Next, open your .bashrc and add
809
810     export PATH=$HOME/local/bin:$HOME/local/script:$PATH
811     perlversion=`perl -v | grep 'built for' | awk '{print $4}' | sed -e 's/v//;'`
812     export PERL5LIB=$HOME/local/share/perl/$perlversion:$HOME/local/lib/perl/$perlversion:$HOME/local/lib:$PERL5LIB
813
814 and log out, then back in again (or run C<". .bashrc"> if you
815 prefer). Finally, edit C<.cpan/CPAN/MyConfig.pm> and add
816
817     'make_install_arg' => qq[SITEPREFIX=$ENV{HOME}/local],
818     'makepl_arg' => qq[INSTALLDIRS=site install_base=$ENV{HOME}/local],
819
820 Now you can install the modules you need using CPAN as normal; they
821 will be installed into your local directory, and perl will pick them
822 up. Finally, change directory into the root of your virtual host and
823 symlink your application's script directory in:
824
825     cd path/to/mydomain.com
826     ln -s ~/lib/MyApp/script script
827
828 And add the following lines to your .htaccess file (assuming the server
829 is setup to handle .pl as fcgi - you may need to rename the script to
830 myapp_fastcgi.fcgi and/or use a SetHandler directive):
831
832   RewriteEngine On
833   RewriteCond %{REQUEST_URI} !^/?script/myapp_fastcgi.pl
834   RewriteRule ^(.*)$ script/myapp_fastcgi.pl/$1 [PT,L]
835
836 Now C<http://mydomain.com/> should now Just Work. Congratulations, now
837 you can tell your friends about your new website (or in our case, tell
838 the client it's time to pay the invoice :) )
839
840 =head2 Caching
841
842 Catalyst makes it easy to employ several different types of caching to
843 speed up your applications.
844
845 =head3 Cache Plugins
846
847 There are three wrapper plugins around common CPAN cache modules:
848 Cache::FastMmap, Cache::FileCache, and Cache::Memcached.  These can be
849 used to cache the result of slow operations.
850
851 This very page you're viewing makes use of the FileCache plugin to cache the
852 rendered XHTML version of the source POD document.  This is an ideal
853 application for a cache because the source document changes infrequently but
854 may be viewed many times.
855
856     use Catalyst qw/Cache::FileCache/;
857     
858     ...
859     
860     use File::stat;
861     sub render_pod : Local {
862         my ( self, $c ) = @_;
863         
864         # the cache is keyed on the filename and the modification time
865         # to check for updates to the file.
866         my $file  = $c->path_to( 'root', '2005', '11.pod' );
867         my $mtime = ( stat $file )->mtime;
868         
869         my $cached_pod = $c->cache->get("$file $mtime");
870         if ( !$cached_pod ) {
871             $cached_pod = do_slow_pod_rendering();
872             # cache the result for 12 hours
873             $c->cache->set( "$file $mtime", $cached_pod, '12h' );
874         }
875         $c->stash->{pod} = $cached_pod;
876     }
877     
878 We could actually cache the result forever, but using a value such as 12 hours
879 allows old entries to be automatically expired when they are no longer needed.
880
881 =head3 Page Caching
882
883 Another method of caching is to cache the entire HTML page.  While this is
884 traditionally handled by a front-end proxy server like Squid, the Catalyst
885 PageCache plugin makes it trivial to cache the entire output from
886 frequently-used or slow actions.
887
888 Many sites have a busy content-filled front page that might look something
889 like this.  It probably takes a while to process, and will do the exact same
890 thing for every single user who views the page.
891
892     sub front_page : Path('/') {
893         my ( $self, $c ) = @_;
894         
895         $c->forward( 'get_news_articles' );
896         $c->forward( 'build_lots_of_boxes' );
897         $c->forward( 'more_slow_stuff' );
898         
899         $c->stash->{template} = 'index.tt';
900     }
901
902 We can add the PageCache plugin to speed things up.
903
904     use Catalyst qw/Cache::FileCache PageCache/;
905     
906     sub front_page : Path ('/') {
907         my ( $self, $c ) = @_;
908         
909         $c->cache_page( 300 );
910         
911         # same processing as above
912     }
913     
914 Now the entire output of the front page, from <html> to </html>, will be
915 cached for 5 minutes.  After 5 minutes, the next request will rebuild the
916 page and it will be re-cached.
917
918 Note that the page cache is keyed on the page URI plus all parameters, so
919 requests for / and /?foo=bar will result in different cache items.  Also,
920 only GET requests will be cached by the plugin.
921
922 You can even get that front-end Squid proxy to help out by enabling HTTP
923 headers for the cached page.
924
925     MyApp->config->{page_cache}->{set_http_headers} = 1;
926     
927 This would now set the following headers so proxies and browsers may cache
928 the content themselves.
929
930     Cache-Control: max-age=($expire_time - time)
931     Expires: $expire_time
932     Last-Modified: $cache_created_time
933     
934 =head3 Template Caching
935
936 Template Toolkit provides support for caching compiled versions of your
937 templates.  To enable this in Catalyst, use the following configuration.
938 TT will cache compiled templates keyed on the file mtime, so changes will
939 still be automatically detected.
940
941     package MyApp::View::TT;
942     
943     use strict;
944     use warnings;
945     use base 'Catalyst::View::TT';
946     
947     __PACKAGE__->config(
948         COMPILE_DIR => '/tmp/template_cache',
949     );
950     
951     1;
952     
953 =head3 More Info
954
955 See the documentation for each cache plugin for more details and other
956 available configuration options.
957
958 L<Catalyst::Plugin::Cache::FastMmap>
959 L<Catalyst::Plugin::Cache::FileCache>
960 L<Catalyst::Plugin::Cache::Memcached>
961 L<Catalyst::Plugin::PageCache>
962 L<http://search.cpan.org/dist/Template-Toolkit/lib/Template/Manual/Config.pod#Caching_and_Compiling_Options>
963
964 =head2 Component-based Subrequests
965
966 See L<Catalyst::Plugin::SubRequest>.
967
968 =head2 DBIx::Class as a Catalyst Model
969
970 See L<Catalyst::Model::DBIC::Schema>.
971
972 =head2 Authentication/Authorization
973
974 This is done in several steps:
975
976 =over 4
977
978 =item Verification
979
980 Getting the user to identify themselves, by giving you some piece of
981 information known only to you and the user. Then you can assume that the user
982 is who they say they are. This is called B<credential verification>.
983
984 =item Authorization
985
986 Making sure the user only accesses functions you want them to access. This is
987 done by checking the verified users data against your internal list of groups,
988 or allowed persons for the current page.
989
990 =back
991
992 =head3 Modules
993
994 The Catalyst Authentication system is made up of many interacting modules, to
995 give you the most flexibility possible.
996
997 =head4 Credential verifiers
998
999 A Credential module tables the user input, and passes it to a Store, or some
1000 other system, for verification. Typically, a user object is created by either
1001 this module or the Store and made accessible by a C<< $c->user >> call.
1002
1003 Examples:
1004
1005  Password - Simple username/password checking.
1006  HTTPD    - Checks using basic HTTP auth.
1007  TypeKey  - Check using the typekey system.
1008
1009 =head3 Storage backends
1010
1011 A Storage backend contains the actual data representing the users. It is
1012 queried by the credential verifiers. Updating the store is not done within
1013 this system, you will need to do it yourself.
1014
1015 Examples:
1016
1017  DBIC     - Storage using a database.
1018  Minimal  - Storage using a simple hash (for testing).
1019
1020 =head3 User objects
1021
1022 A User object is created by either the storage backend or the credential
1023 verifier, and filled with the retrieved user information.
1024
1025 Examples:
1026
1027  Hash     - A simple hash of keys and values.
1028
1029 =head3 ACL authorization
1030
1031 ACL stands for Access Control List. The ACL plugin allows you to regulate
1032 access on a path by path basis, by listing which users, or roles, have access
1033 to which paths.
1034
1035 =head3 Roles authorization
1036
1037 Authorization by roles is for assigning users to groups, which can then be
1038 assigned to ACLs, or just checked when needed.
1039
1040 =head3 Logging in
1041
1042 When you have chosen your modules, all you need to do is call the C<<
1043 $c->login >> method. If called with no parameters, it will try to find
1044 suitable parameters, such as B<username> and B<password>, or you can pass it
1045 these values.
1046
1047 =head3 Checking roles
1048
1049 Role checking is done by using the C<< $c->check_user_roles >> method, this will
1050 check using the currently logged in user (via C<< $c->user >>). You pass it
1051 the name of a role to check, and it returns true if the user is a member.
1052
1053 =head3 EXAMPLE
1054
1055  use Catalyst qw/Authentication
1056                  Authentication::Credential::Password
1057                  Authentication::Store::Htpasswd
1058                  Authorization::Roles/;
1059
1060  __PACKAGE__->config->{authentication}{htpasswd} = "passwdfile";
1061
1062   sub login : Local {
1063      my ($self, $c) = @_;
1064
1065      if (    my $user = $c->req->param("user")
1066          and my $password = $c->req->param("password") )
1067      {
1068          if ( $c->login( $user, $password ) ) {
1069               $c->res->body( "hello " . $c->user->name );
1070          } else {
1071             # login incorrect
1072          }
1073      }
1074      else {
1075          # invalid form input
1076      }
1077   }
1078
1079   sub restricted : Local {
1080      my ( $self, $c ) = @_;
1081
1082      $c->detach("unauthorized")
1083        unless $c->check_user_roles( "admin" );
1084
1085      # do something restricted here
1086   }
1087
1088 =head3 Using authentication in a testing environment
1089
1090 Ideally, to write tests for authentication/authorization code one would first
1091 set up a test database with known data, then use
1092 L<Test::WWW::Mechanize::Catalyst> to simulate a user logging in. Unfortunately
1093 the former can be rather awkward, which is why it's a good thing that the
1094 authentication framework is so flexible.
1095
1096 Instead of using a test database, one can simply change the authentication
1097 store to something a bit easier to deal with in a testing
1098 environment. Additionally, this has the advantage of not modifying one's
1099 database, which can be problematic if one forgets to use the testing instead of
1100 production database.
1101
1102 e.g.,
1103
1104   use Catalyst::Plugin::Authentication::Store::Minimal::Backend;
1105
1106   # Sets up the user `test_user' with password `test_pass'
1107   MyApp->default_auth_store(
1108     Catalyst::Plugin::Authentication::Store::Minimal::Backend->new({
1109       test_user => { password => 'test_pass' },
1110     })
1111   );
1112
1113 Now, your test code can call C<$c->login('test_user', 'test_pass')> and
1114 successfully login, without messing with the database at all.
1115
1116 =head3 More information
1117
1118 L<http://search.cpan.org/perldoc?Catalyst::Plugin::Authentication> has a longer explanation.
1119
1120 =head2 Sessions
1121
1122 When you have your users identified, you will want to somehow remember that
1123 fact, to save them from having to identify themselves for every single
1124 page. One way to do this is to send the username and password parameters in
1125 every single page, but that's ugly, and won't work for static pages. 
1126
1127 Sessions are a method of saving data related to some transaction, and giving
1128 the whole collection a single ID. This ID is then given to the user to return
1129 to us on every page they visit while logged in. The usual way to do this is
1130 using a browser cookie.
1131
1132 Catalyst uses two types of plugins to represent sessions:
1133
1134 =head3 State
1135
1136 A State module is used to keep track of the state of the session between the
1137 users browser, and your application.  
1138
1139 A common example is the Cookie state module, which sends the browser a cookie
1140 containing the session ID. It will use default value for the cookie name and
1141 domain, so will "just work" when used. 
1142
1143 =head3 Store
1144
1145 A Store module is used to hold all the data relating to your session, for
1146 example the users ID, or the items for their shopping cart. You can store data
1147 in memory (FastMmap), in a file (File) or in a database (DBI).
1148
1149 =head3 Authentication magic
1150
1151 If you have included the session modules in your application, the
1152 Authentication modules will automagically use your session to save and
1153 retrieve the user data for you.
1154
1155 =head3 Using a session
1156
1157 Once the session modules are loaded, the session is available as C<<
1158 $c->session >>, and can be writen to and read from as a simple hash reference.
1159
1160 =head3 EXAMPLE
1161
1162   use Catalyst qw/
1163                  Session
1164                  Session::Store::FastMmap
1165                  Session::State::Cookie
1166                  /;
1167
1168
1169   ## Write data into the session
1170
1171   sub add_item : Local {
1172      my ( $self, $c ) = @_;
1173
1174      my $item_id = $c->req->param("item");
1175
1176      push @{ $c->session->{items} }, $item_id;
1177
1178   }
1179
1180   ## A page later we retrieve the data from the session:
1181
1182   sub get_items : Local {
1183      my ( $self, $c ) = @_;
1184
1185      $c->stash->{items_to_display} = $c->session->{items};
1186
1187   }
1188
1189
1190 =head3 More information
1191
1192 L<http://search.cpan.org/dist/Catalyst-Plugin-Session>
1193
1194 L<http://search.cpan.org/dist/Catalyst-Plugin-Session-State-Cookie>
1195
1196 L<http://search.cpan.org/dist/Catalyst-Plugin-Session-State-URI>
1197
1198 L<http://search.cpan.org/dist/Catalyst-Plugin-Session-Store-FastMmap>
1199
1200 L<http://search.cpan.org/dist/Catalyst-Plugin-Session-Store-File>
1201
1202 L<http://search.cpan.org/dist/Catalyst-Plugin-Session-Store-DBI>
1203
1204 =head2 Adding RSS feeds 
1205
1206 Adding RSS feeds to your Catalyst applications is simple. We'll see two
1207 different aproaches here, but the basic premise is that you forward to
1208 the normal view action first to get the objects, then handle the output
1209 differently.
1210
1211 =head3 Using TT templates
1212
1213 This is the aproach used in Agave (L<http://dev.rawmode.org/>).
1214
1215     sub rss : Local {
1216         my ($self,$c) = @_;
1217         $c->forward('view');
1218         $c->stash->{template}='rss.tt';
1219     }
1220
1221 Then you need a template. Here's the one from Agave: 
1222
1223     <?xml version="1.0" encoding="UTF-8"?>
1224     <rss version="2.0" xmlns:dc="http://purl.org/dc/elements/1.1/">
1225       <channel>
1226         <title>[ [% blog.name || c.config.name || "Agave" %] ] RSS Feed</title>
1227         <link>[% base %]</link>
1228         <description>Recent posts</description>
1229         <language>en-us</language>
1230         <ttl>40</ttl>
1231      [% WHILE (post = posts.next) %]
1232       <item>
1233         <title>[% post.title %]</title>
1234         <description>[% post.formatted_teaser|html%]</description>    
1235         <pubDate>[% post.pub_date %]</pubDate>
1236         <guid>[% post.full_uri %]</guid>
1237         <link>[% post.full_uri %]</link>
1238         <dc:creator>[% post.author.screenname %]</dc:creator>
1239       </item>
1240     [% END %]
1241       </channel>
1242     </rss> 
1243
1244 =head3 Using XML::Feed
1245
1246 A more robust solution is to use XML::Feed, as was done in the Catalyst
1247 Advent Calendar. Assuming we have a C<view> action that populates
1248 'entries' with some DBIx::Class iterator, the code would look something
1249 like this:
1250
1251     sub rss : Local {
1252         my ($self,$c) = @_;
1253         $c->forward('view'); # get the entries
1254
1255         my $feed = XML::Feed->new('RSS');
1256         $feed->title( $c->config->{name} . ' RSS Feed' );
1257         $feed->link( $c->req->base ); # link to the site.
1258         $feed->description('Catalyst advent calendar'); Some description
1259
1260         # Process the entries
1261         while( my $entry = $c->stash->{entries}->next ) {
1262             my $feed_entry = XML::Feed::Entry->new('RSS');
1263             $feed_entry->title($entry->title);
1264             $feed_entry->link( $c->uri_for($entry->link) );
1265             $feed_entry->issued( DateTime->from_epoch(epoch => $entry->created) );
1266             $feed->add_entry($feed_entry);
1267         }
1268         $c->res->body( $feed->as_xml );
1269    }
1270
1271 A little more code in the controller, but with this approach you're
1272 pretty sure to get something that validates. 
1273
1274 Note that for both of the above aproaches, you'll need to set the
1275 content type like this:
1276
1277     $c->res->content_type('application/rss+xml');
1278
1279 =head3 Final words
1280
1281 You could generalize the second variant easily by replacing 'RSS' with a
1282 variable, so you can generate Atom feeds with the same code.
1283
1284 Now, go ahead and make RSS feeds for all your stuff. The world *needs*
1285 updates on your goldfish!
1286
1287 =head2 FastCGI Deployment
1288
1289 FastCGI is a high-performance extension to CGI. It is suitable
1290 for production environments.
1291
1292 =head3 Pros
1293
1294 =head4 Speed
1295
1296 FastCGI performs equally as well as mod_perl.  Don't let the 'CGI' fool you;
1297 your app runs as multiple persistent processes ready to receive connections
1298 from the web server.
1299
1300 =head4 App Server
1301
1302 When using external FastCGI servers, your application runs as a standalone
1303 application server.  It may be restarted independently from the web server.
1304 This allows for a more robust environment and faster reload times when
1305 pushing new app changes.  The frontend server can even be configured to
1306 display a friendly "down for maintenance" page while the application is
1307 restarting.
1308
1309 =head4 Load-balancing
1310
1311 You can launch your application on multiple backend servers and allow the
1312 frontend web server to load-balance between all of them.  And of course, if
1313 one goes down, your app continues to run fine.
1314
1315 =head4 Multiple versions of the same app
1316
1317 Each FastCGI application is a separate process, so you can run different
1318 versions of the same app on a single server.
1319
1320 =head4 Can run with threaded Apache
1321
1322 Since your app is not running inside of Apache, the faster mpm_worker module
1323 can be used without worrying about the thread safety of your application.
1324
1325 =head3 Cons
1326
1327 =head4 More complex environment
1328
1329 With FastCGI, there are more things to monitor and more processes running
1330 than when using mod_perl.
1331
1332 =head3 Setup
1333
1334 =head4 1. Install Apache with mod_fastcgi
1335
1336 mod_fastcgi for Apache is a third party module, and can be found at
1337 L<http://www.fastcgi.com/>.  It is also packaged in many distributions,
1338 for example, libapache2-mod-fastcgi in Debian.
1339
1340 =head4 2. Configure your application
1341
1342     # Serve static content directly
1343     DocumentRoot  /var/www/MyApp/root
1344     Alias /static /var/www/MyApp/root/static
1345
1346     FastCgiServer /var/www/MyApp/script/myapp_fastcgi.pl -processes 3
1347     Alias /myapp/ /var/www/MyApp/script/myapp_fastcgi.pl/
1348     
1349     # Or, run at the root
1350     Alias / /var/www/MyApp/script/myapp_fastcgi.pl/
1351     
1352 The above commands will launch 3 app processes and make the app available at
1353 /myapp/
1354
1355 =head3 Standalone server mode
1356
1357 While not as easy as the previous method, running your app as an external
1358 server gives you much more flexibility.
1359
1360 First, launch your app as a standalone server listening on a socket.
1361
1362     script/myapp_fastcgi.pl -l /tmp/myapp.socket -n 5 -p /tmp/myapp.pid -d
1363     
1364 You can also listen on a TCP port if your web server is not on the same
1365 machine.
1366
1367     script/myapp_fastcgi.pl -l :8080 -n 5 -p /tmp/myapp.pid -d
1368     
1369 You will probably want to write an init script to handle starting/stopping
1370 of the app using the pid file.
1371
1372 Now, we simply configure Apache to connect to the running server.
1373
1374     # 502 is a Bad Gateway error, and will occur if the backend server is down
1375     # This allows us to display a friendly static page that says "down for
1376     # maintenance"
1377     Alias /_errors /var/www/MyApp/root/error-pages
1378     ErrorDocument 502 /_errors/502.html
1379
1380     FastCgiExternalServer /tmp/myapp -socket /tmp/myapp.socket
1381     Alias /myapp/ /tmp/myapp/
1382     
1383     # Or, run at the root
1384     Alias / /tmp/myapp/
1385     
1386 =head3 More Info
1387
1388 L<Catalyst::Engine::FastCGI>.
1389
1390 =head2 Catalyst::View::TT
1391
1392 One of the first things you probably want to do when starting a new
1393 Catalyst application is set up your View. Catalyst doesn't care how you
1394 display your data; you can choose to generate HTML, PDF files, or plain
1395 text if you wanted.
1396
1397 Most Catalyst applications use a template system to generate their HTML,
1398 and though there are several template systems available, Template
1399 Toolkit is probably the most popular.
1400
1401 Once again, the Catalyst developers have done all the hard work, and
1402 made things easy for the rest of us. Catalyst::View::TT provides the
1403 interface to Template Toolkit, and provides Helpers which let us set it
1404 up that much more easily.
1405
1406 =head3 Creating your View
1407
1408 Catalyst::View::TT provides two different helpers for us to use: TT and
1409 TTSite.
1410
1411 =head4 TT
1412
1413 Create a basic Template Toolkit View using the provided helper script:
1414
1415     script/myapp_create.pl view TT TT
1416
1417 This will create lib/MyApp/View/MyView.pm, which is going to be pretty
1418 empty to start. However, it sets everything up that you need to get
1419 started. You can now define which template you want and forward to your
1420 view. For instance:
1421
1422     sub hello : Local {
1423         my ( $self, $c ) = @_;
1424
1425         $c->stash->{template} = 'hello.tt';
1426
1427         $c->forward( $c->view('TT') );
1428     }
1429
1430 In practice you wouldn't do the forwarding manually, but would
1431 use L<Catalyst::Action::RenderView>.
1432
1433 =head4 TTSite
1434
1435 Although the TT helper does create a functional, working view, you may
1436 find yourself having to create the same template files and changing the
1437 same options every time you create a new application. The TTSite helper
1438 saves us even more time by creating the basic templates and setting some
1439 common options for us.
1440
1441 Once again, you can use the helper script:
1442
1443     script/myapp_create.pl view TT TTSite
1444
1445 This time, the helper sets several options for us in the generated View.
1446
1447     __PACKAGE__->config({
1448         CATALYST_VAR => 'Catalyst',
1449         INCLUDE_PATH => [
1450             MyApp->path_to( 'root', 'src' ),
1451             MyApp->path_to( 'root', 'lib' )
1452         ],
1453         PRE_PROCESS  => 'config/main',
1454         WRAPPER      => 'site/wrapper',
1455         ERROR        => 'error.tt2',
1456         TIMER        => 0
1457     });
1458
1459 =over
1460
1461 =item 
1462
1463 INCLUDE_PATH defines the directories that Template Toolkit should search
1464 for the template files.
1465
1466 =item
1467
1468 PRE_PROCESS is used to process configuration options which are common to
1469 every template file.
1470
1471 =item
1472
1473 WRAPPER is a file which is processed with each template, usually used to
1474 easily provide a common header and footer for every page.
1475
1476 =back
1477
1478 In addition to setting these options, the TTSite helper also created the
1479 template and config files for us! In the 'root' directory, you'll notice
1480 two new directories: src and lib.
1481
1482 Several configuration files in root/lib/config are called by PRE_PROCESS.
1483
1484 The files in root/lib/site are the site-wide templates, called by
1485 WRAPPER, and display the html framework, control the layout, and provide
1486 the templates for the header and footer of your page. Using the template
1487 organization provided makes it much easier to standardize pages and make
1488 changes when they are (inevitably) needed.
1489
1490 The template files that you will create for your application will go
1491 into root/src, and you don't need to worry about putting the the <html>
1492 or <head> sections; just put in the content. The WRAPPER will the rest
1493 of the page around your template for you.
1494
1495 =head2 $c->stash
1496
1497 Of course, having the template system include the header and footer for
1498 you isn't all that we want our templates to do. We need to be able to
1499 put data into our templates, and have it appear where and how we want
1500 it, right? That's where the stash comes in.
1501
1502 In our controllers, we can add data to the stash, and then access it
1503 from the template. For instance:
1504
1505     sub hello : Local {
1506         my ( $self, $c ) = @_;
1507
1508         $c->stash->{name} = 'Adam';
1509
1510         $c->stash->{template} = 'hello.tt';
1511
1512         $c->forward( $c->view('TT') );
1513     }
1514
1515 Then, in hello.tt:
1516
1517     <strong>Hello, [% name %]!</strong>
1518
1519 When you view this page, it will display "Hello, Adam!"
1520
1521 All of the information in your stash is available, by its name/key, in
1522 your templates. And your data don't have to be plain, old, boring
1523 scalars. You can pass array references and hash references, too.
1524
1525 In your controller:
1526
1527     sub hello : Local {
1528         my ( $self, $c ) = @_;
1529
1530         $c->stash->{names} = [ 'Adam', 'Dave', 'John' ];
1531
1532         $c->stash->{template} = 'hello.tt';
1533
1534         $c->forward( $c->view('TT') );
1535     }
1536
1537 In hello.tt:
1538
1539     [% FOREACH name IN names %]
1540         <strong>Hello, [% name %]!</strong><br />
1541     [% END %]
1542
1543 This allowed us to loop through each item in the arrayref, and display a
1544 line for each name that we have.
1545
1546 This is the most basic usage, but Template Toolkit is quite powerful,
1547 and allows you to truly keep your presentation logic separate from the
1548 rest of your application.
1549
1550 =head3 $c->uri_for()
1551
1552 One of my favorite things about Catalyst is the ability to move an
1553 application around without having to worry that everything is going to
1554 break. One of the areas that used to be a problem was with the http
1555 links in your template files. For example, suppose you have an
1556 application installed at http://www.domain.com/Calendar. The links point
1557 to "/Calendar", "/Calendar/2005", "/Calendar/2005/10", etc.  If you move
1558 the application to be at http://www.mydomain.com/Tools/Calendar, then
1559 all of those links will suddenly break.
1560
1561 That's where $c->uri_for() comes in. This function will merge its
1562 parameters with either the base location for the app, or its current
1563 namespace. Let's take a look at a couple of examples.
1564
1565 In your template, you can use the following:
1566
1567     <a href="[% c.uri_for('/login') %]">Login Here</a>
1568
1569 Although the parameter starts with a forward slash, this is relative to the application root, not the webserver root. This is important to remember. So, if your application is installed at http://www.domain.com/Calendar, then the link would be http://www.mydomain.com/Calendar/Login. If you move your application to a different domain or path, then that link will still be correct.
1570
1571 Likewise,
1572
1573     <a href="[% c.uri_for('2005','10', '24') %]">October, 24 2005</a>
1574
1575 The first parameter does NOT have a forward slash, and so it will be relative to the current namespace. If the application is installed at http://www.domain.com/Calendar. and if the template is called from MyApp::Controller::Display, then the link would become http://www.domain.com/Calendar/Display/2005/10/24.
1576
1577 Once again, this allows you to move your application around without having to worry about broken links. But there's something else, as well. Since the links are generated by uri_for, you can use the same template file by several different controllers, and each controller will get the links that its supposed to. Since we believe in Don't Repeat Yourself, this is particularly helpful if you have common elements in your site that you want to keep in one file.
1578
1579 Further Reading:
1580
1581 L<http://search.cpan.org/perldoc?Catalyst>
1582
1583 L<http://search.cpan.org/perldoc?Catalyst%3A%3AView%3A%3ATT>
1584
1585 L<http://search.cpan.org/perldoc?Template>
1586
1587 =head2 Testing
1588
1589 Catalyst provides a convenient way of testing your application during 
1590 development and before deployment in a real environment.
1591
1592 C<Catalyst::Test> makes it possible to run the same tests both locally 
1593 (without an external daemon) and against a remote server via HTTP.
1594
1595 =head3 Tests
1596
1597 Let's examine a skeleton application's C<t/> directory:
1598
1599     mundus:~/MyApp chansen$ ls -l t/
1600     total 24
1601     -rw-r--r--  1 chansen  chansen   95 18 Dec 20:50 01app.t
1602     -rw-r--r--  1 chansen  chansen  190 18 Dec 20:50 02pod.t
1603     -rw-r--r--  1 chansen  chansen  213 18 Dec 20:50 03podcoverage.t
1604
1605 =over 4
1606
1607 =item C<01app.t>
1608
1609 Verifies that the application loads, compiles, and returns a successful
1610 response.
1611
1612 =item C<02pod.t>
1613
1614 Verifies that all POD is free from errors. Only executed if the C<TEST_POD> 
1615 environment variable is true.
1616
1617 =item C<03podcoverage.t>
1618
1619 Verifies that all methods/functions have POD coverage. Only executed if the
1620 C<TEST_POD> environment variable is true.
1621
1622 =back
1623
1624 =head3 Creating tests
1625
1626     mundus:~/MyApp chansen$ cat t/01app.t | perl -ne 'printf( "%2d  %s", $., $_ )'
1627     1  use Test::More tests => 2;
1628     2  use_ok( Catalyst::Test, 'MyApp' );
1629     3
1630     4  ok( request('/')->is_success );
1631
1632 The first line declares how many tests we are going to run, in this case
1633 two. The second line tests and loads our application in test mode. The
1634 fourth line verifies that our application returns a successful response.
1635
1636 C<Catalyst::Test> exports two functions, C<request> and C<get>. Each can
1637 take three different arguments:
1638
1639 =over 4
1640
1641 =item A string which is a relative or absolute URI.
1642
1643     request('/my/path');
1644     request('http://www.host.com/my/path');
1645
1646 =item An instance of C<URI>.
1647
1648     request( URI->new('http://www.host.com/my/path') );
1649
1650 =item An instance of C<HTTP::Request>.
1651
1652     request( HTTP::Request->new( GET => 'http://www.host.com/my/path') );
1653
1654 =back
1655
1656 C<request> returns an instance of C<HTTP::Response> and C<get> returns the 
1657 content (body) of the response.
1658
1659 =head3 Running tests locally
1660
1661     mundus:~/MyApp chansen$ CATALYST_DEBUG=0 TEST_POD=1 prove --lib lib/ t/
1662     t/01app............ok                                                        
1663     t/02pod............ok                                                        
1664     t/03podcoverage....ok                                                        
1665     All tests successful.
1666     Files=3, Tests=4,  2 wallclock secs ( 1.60 cusr +  0.36 csys =  1.96 CPU)
1667  
1668 C<CATALYST_DEBUG=0> ensures that debugging is off; if it's enabled you
1669 will see debug logs between tests.
1670
1671 C<TEST_POD=1> enables POD checking and coverage.
1672
1673 C<prove> A command-line tool that makes it easy to run tests. You can
1674 find out more about it from the links below.
1675
1676 =head3 Running tests remotely
1677
1678     mundus:~/MyApp chansen$ CATALYST_SERVER=http://localhost:3000/ prove --lib lib/ t/01app.t
1679     t/01app....ok                                                                
1680     All tests successful.
1681     Files=1, Tests=2,  0 wallclock secs ( 0.40 cusr +  0.01 csys =  0.41 CPU)
1682
1683 C<CATALYST_SERVER=http://localhost:3000/> is the absolute deployment URI of 
1684 your application. In C<CGI> or C<FastCGI> it should be the host and path 
1685 to the script.
1686
1687 =head3 C<Test::WWW::Mechanize> and Catalyst
1688
1689 Be sure to check out C<Test::WWW::Mechanize::Catalyst>. It makes it easy to
1690 test HTML, forms and links. A short example of usage:
1691
1692     use Test::More tests => 6;
1693     use_ok( Test::WWW::Mechanize::Catalyst, 'MyApp' );
1694
1695     my $mech = Test::WWW::Mechanize::Catalyst->new;
1696     $mech->get_ok("http://localhost/", 'Got index page');
1697     $mech->title_like( qr/^MyApp on Catalyst/, 'Got right index title' );
1698     ok( $mech->find_link( text_regex => qr/^Wiki/i ), 'Found link to Wiki' );
1699     ok( $mech->find_link( text_regex => qr/^Mailing-List/i ), 'Found link to Mailing-List' );
1700     ok( $mech->find_link( text_regex => qr/^IRC channel/i ), 'Found link to IRC channel' );
1701
1702 =head3 Further Reading
1703
1704 =over 4
1705
1706 =item Catalyst::Test
1707
1708 L<http://search.cpan.org/dist/Catalyst/lib/Catalyst/Test.pm>
1709
1710 =item Test::WWW::Mechanize::Catalyst
1711
1712 L<http://search.cpan.org/dist/Test-WWW-Mechanize-Catalyst/lib/Test/WWW/Mechanize/Catalyst.pm>
1713
1714 =item Test::WWW::Mechanize
1715
1716 L<http://search.cpan.org/dist/Test-WWW-Mechanize/Mechanize.pm>
1717
1718 =item WWW::Mechanize
1719
1720 L<http://search.cpan.org/dist/WWW-Mechanize/lib/WWW/Mechanize.pm>
1721
1722 =item LWP::UserAgent
1723
1724 L<http://search.cpan.org/dist/libwww-perl/lib/LWP/UserAgent.pm>
1725
1726 =item HTML::Form
1727
1728 L<http://search.cpan.org/dist/libwww-perl/lib/HTML/Form.pm>
1729
1730 =item HTTP::Message
1731
1732 L<http://search.cpan.org/dist/libwww-perl/lib/HTTP/Message.pm>
1733
1734 =item HTTP::Request
1735
1736 L<http://search.cpan.org/dist/libwww-perl/lib/HTTP/Request.pm>
1737
1738 =item HTTP::Request::Common
1739
1740 L<http://search.cpan.org/dist/libwww-perl/lib/HTTP/Request/Common.pm>
1741
1742 =item HTTP::Response
1743
1744 L<http://search.cpan.org/dist/libwww-perl/lib/HTTP/Response.pm>
1745
1746 =item HTTP::Status
1747
1748 L<http://search.cpan.org/dist/libwww-perl/lib/HTTP/Status.pm>
1749
1750 =item URI
1751
1752 L<http://search.cpan.org/dist/URI/URI.pm>
1753
1754 =item Test::More
1755
1756 L<http://search.cpan.org/dist/Test-Simple/lib/Test/More.pm>
1757
1758 =item Test::Pod
1759
1760 L<http://search.cpan.org/dist/Test-Pod/Pod.pm>
1761
1762 =item Test::Pod::Coverage
1763
1764 L<http://search.cpan.org/dist/Test-Pod-Coverage/Coverage.pm>
1765
1766 =item prove (Test::Harness)
1767
1768 L<http://search.cpan.org/dist/Test-Harness/bin/prove>
1769
1770 =back
1771
1772 =head2 XMLRPC
1773
1774 Unlike SOAP, XMLRPC is a very simple (and imo elegant) web-services
1775 protocol, exchanging small XML messages like these:
1776
1777 Request:
1778
1779     POST /api HTTP/1.1
1780     TE: deflate,gzip;q=0.3
1781     Connection: TE, close
1782     Accept: text/xml
1783     Accept: multipart/*
1784     Host: 127.0.0.1:3000
1785     User-Agent: SOAP::Lite/Perl/0.60
1786     Content-Length: 192
1787     Content-Type: text/xml
1788
1789     <?xml version="1.0" encoding="UTF-8"?>
1790     <methodCall>
1791         <methodName>add</methodName>
1792         <params>
1793             <param><value><int>1</int></value></param>
1794             <param><value><int>2</int></value></param>
1795         </params>
1796     </methodCall>
1797
1798 Response:
1799
1800     Connection: close
1801     Date: Tue, 20 Dec 2005 07:45:55 GMT
1802     Content-Length: 133
1803     Content-Type: text/xml
1804     Status: 200
1805     X-Catalyst: 5.70
1806
1807     <?xml version="1.0" encoding="us-ascii"?>
1808     <methodResponse>
1809         <params>
1810             <param><value><int>3</int></value></param>
1811         </params>
1812     </methodResponse>
1813
1814 Now follow these few steps to implement the application:
1815
1816 1. Install Catalyst (5.61 or later), Catalyst::Plugin::XMLRPC (0.06 or
1817 later) and SOAP::Lite (for XMLRPCsh.pl).
1818
1819 2. Create an application framework:
1820
1821     % catalyst.pl MyApp
1822     ...
1823     % cd MyApp
1824
1825 3. Add the XMLRPC plugin to MyApp.pm
1826
1827     use Catalyst qw/-Debug Static::Simple XMLRPC/;
1828
1829 4. Add an API controller
1830
1831     % ./script/myapp_create.pl controller API
1832
1833 5. Add a XMLRPC redispatch method and an add method with Remote
1834 attribute to lib/MyApp/Controller/API.pm
1835
1836     sub default : Private {
1837         my ( $self, $c ) = @_;
1838         $c->xmlrpc;
1839     }
1840
1841     sub add : Remote {
1842         my ( $self, $c, $a, $b ) = @_;
1843         return $a + $b;
1844     }
1845
1846 The default action is the entry point for each XMLRPC request. It will
1847 redispatch every request to methods with Remote attribute in the same
1848 class.
1849
1850 The C<add> method is not a traditional action; it has no private or
1851 public path. Only the XMLRPC dispatcher knows it exists.
1852
1853 6. That's it! You have built your first web service. Let's test it with
1854 XMLRPCsh.pl (part of SOAP::Lite):
1855
1856     % ./script/myapp_server.pl
1857     ...
1858     % XMLRPCsh.pl http://127.0.0.1:3000/api
1859     Usage: method[(parameters)]
1860     > add( 1, 2 )
1861     --- XMLRPC RESULT ---
1862     '3'
1863
1864 =head3 Tip
1865
1866 Your return data type is usually auto-detected, but you can easily
1867 enforce a specific one.
1868
1869     sub add : Remote {
1870         my ( $self, $c, $a, $b ) = @_;
1871         return RPC::XML::int->new( $a + $b );
1872     }
1873     
1874 =head2 Action Types
1875
1876 =head3 Introduction
1877
1878 A Catalyst application is driven by one or more Controller modules. There are
1879 a number of ways that Catalyst can decide which of the methods in your
1880 controller modules it should call. Controller methods are also called actions,
1881 because they determine how your catalyst application should (re-)act to any
1882 given URL. When the application is started up, catalyst looks at all your
1883 actions, and decides which URLs they map to.
1884
1885 =head3 Type attributes
1886
1887 Each action is a normal method in your controller, except that it has an
1888 L<attribute|http://search.cpan.org/~nwclark/perl-5.8.7/lib/attributes.pm>
1889 attached. These can be one of several types.
1890
1891 Assume our Controller module starts with the following package declaration:
1892
1893  package MyApp::Controller::Buckets;
1894
1895 and we are running our application on localhost, port 3000 (the test
1896 server default).
1897
1898 =over 4
1899
1900 =item Path
1901
1902 A Path attribute also takes an argument, this can be either a relative
1903 or an absolute path. A relative path will be relative to the controller
1904 namespace, an absolute path will represent an exact matching URL.
1905
1906  sub my_handles : Path('handles') { .. }
1907
1908 becomes
1909
1910  http://localhost:3000/buckets/handles
1911
1912 and
1913
1914  sub my_handles : Path('/handles') { .. }
1915
1916 becomes 
1917
1918  http://localhost:3000/handles
1919
1920 =item Local
1921
1922 When using a Local attribute, no parameters are needed, instead, the name of
1923 the action is matched in the URL. The namespaces created by the name of the
1924 controller package is always part of the URL.
1925
1926  sub my_handles : Local { .. }
1927
1928 becomes
1929
1930  http://localhost:3000/buckets/my_handles
1931
1932 =item Global
1933
1934 A Global attribute is similar to a Local attribute, except that the namespace
1935 of the controller is ignored, and matching starts at root.
1936
1937  sub my_handles : Global { .. }
1938
1939 becomes
1940
1941  http://localhost:3000/my_handles
1942
1943 =item Regex
1944
1945 By now you should have figured that a Regex attribute is just what it sounds
1946 like. This one takes a regular expression, and matches starting from
1947 root. These differ from the rest as they can match multiple URLs.
1948
1949  sub my_handles : Regex('^handles') { .. }
1950
1951 matches
1952
1953  http://localhost:3000/handles
1954
1955 and 
1956
1957  http://localhost:3000/handles_and_other_parts
1958
1959 etc.
1960
1961 =item LocalRegex
1962
1963 A LocalRegex is similar to a Regex, except it only matches below the current
1964 controller namespace.
1965
1966  sub my_handles : LocalRegex(^handles') { .. }
1967
1968 matches
1969
1970  http://localhost:3000/buckets/handles
1971
1972 and
1973
1974  http://localhost:3000/buckets/handles_and_other_parts
1975
1976 etc.
1977
1978 =item Private
1979
1980 Last but not least, there is the Private attribute, which allows you to create
1981 your own internal actions, which can be forwarded to, but won't be matched as
1982 URLs.
1983
1984  sub my_handles : Private { .. }
1985
1986 becomes nothing at all..
1987
1988 Catalyst also predefines some special Private actions, which you can override,
1989 these are:
1990
1991 =over 4
1992
1993 =item default
1994
1995 The default action will be called, if no other matching action is found. If
1996 you don't have one of these in your namespace, or any sub part of your
1997 namespace, you'll get an error page instead. If you want to find out where it
1998 was the user was trying to go, you can look in the request object using 
1999 C<< $c->req->path >>.
2000
2001  sub default : Private { .. }
2002
2003 works for all unknown URLs, in this controller namespace, or every one if put
2004 directly into MyApp.pm.
2005
2006 =item index 
2007
2008 The index action is called when someone tries to visit the exact namespace of
2009 your controller. If index, default and matching Path actions are defined, then
2010 index will be used instead of default and Path.
2011
2012  sub index : Private { .. }
2013
2014 becomes
2015
2016  http://localhost:3000/buckets
2017
2018 =item begin
2019
2020 The begin action is called at the beginning of every request involving this
2021 namespace directly, before other matching actions are called. It can be used
2022 to set up variables/data for this particular part of your app. A single begin
2023 action is called, its always the one most relevant to the current namespace.
2024
2025  sub begin : Private { .. }
2026
2027 is called once when 
2028
2029  http://localhost:3000/bucket/(anything)?
2030
2031 is visited.
2032
2033 =item end
2034
2035 Like begin, this action is always called for the namespace it is in, after
2036 every other action has finished. It is commonly used to forward processing to
2037 the View component. A single end action is called, its always the one most
2038 relevant to the current namespace. 
2039
2040
2041  sub end : Private { .. }
2042
2043 is called once after any actions when
2044
2045  http://localhost:3000/bucket/(anything)?
2046
2047 is visited.
2048
2049 =item auto
2050
2051 Lastly, the auto action is magic in that B<every> auto action in
2052 the chain of paths up to and including the ending namespace, will be
2053 called. (In contrast, only one of the begin/end/default actions will be
2054 called, the relevant one).
2055
2056  package MyApp.pm;
2057  sub auto : Private { .. }
2058
2059 and 
2060
2061  sub auto : Private { .. }
2062
2063 will both be called when visiting 
2064
2065  http://localhost:3000/bucket/(anything)?
2066
2067 =back
2068
2069 =back
2070
2071 =head3 A word of warning
2072
2073 Due to possible namespace conflicts with Plugins, it is advised to only put the
2074 pre-defined Private actions in your main MyApp.pm file, all others should go
2075 in a Controller module.
2076
2077 =head3 More Information
2078
2079 L<http://search.cpan.org/author/SRI/Catalyst-5.61/lib/Catalyst/Manual/Intro.pod>
2080
2081 L<http://dev.catalyst.perl.org/wiki/FlowChart>
2082
2083
2084 =head2 Authorization
2085
2086 =head3 Introduction
2087
2088 Authorization is the step that comes after authentication. Authentication
2089 establishes that the user agent is really representing the user we think it's
2090 representing, and then authorization determines what this user is allowed to
2091 do.
2092
2093 =head3 Role Based Access Control
2094
2095 Under role based access control each user is allowed to perform any number of
2096 roles. For example, at a zoo no one but specially trained personnel can enter
2097 the moose cage (Mynd you, møøse bites kan be pretty nasti!). For example: 
2098
2099     package Zoo::Controller::MooseCage;
2100
2101     sub feed_moose : Local {
2102         my ( $self, $c ) = @_;
2103
2104         $c->model( "Moose" )->eat( $c->req->param("food") );
2105     }
2106
2107 With this action, anyone can just come into the moose cage and feed the moose,
2108 which is a very dangerous thing. We need to restrict this action, so that only
2109 a qualified moose feeder can perform that action.
2110
2111 The Authorization::Roles plugin let's us perform role based access control
2112 checks. Let's load it:
2113
2114     use Catalyst qw/
2115         Authentication # yadda yadda
2116         Authorization::Roles
2117     /;
2118
2119 And now our action should look like this:
2120
2121     sub feed_moose : Local {
2122         my ( $self, $c ) = @_;
2123
2124         if ( $c->check_roles( "moose_feeder" ) ) {
2125             $c->model( "Moose" )->eat( $c->req->param("food") );
2126         } else {
2127             $c->stash->{error} = "unauthorized";
2128         }
2129     }
2130
2131 This checks C<< $c->user >>, and only if the user has B<all> the roles in the
2132 list, a true value is returned.
2133
2134 C<check_roles> has a sister method, C<assert_roles>, which throws an exception
2135 if any roles are missing.
2136
2137 Some roles that might actually make sense in, say, a forum application:
2138
2139 =over 4
2140
2141 =item *
2142
2143 administrator
2144
2145 =item *
2146
2147 moderator
2148
2149 =back
2150
2151 each with a distinct task (system administration versus content administration).
2152
2153 =head3 Access Control Lists
2154
2155 Checking for roles all the time can be tedious and error prone.
2156
2157 The Authorization::ACL plugin let's us declare where we'd like checks to be
2158 done automatically for us.
2159
2160 For example, we may want to completely block out anyone who isn't a
2161 C<moose_feeder> from the entire C<MooseCage> controller:
2162
2163     Zoo->deny_access_unless( "/moose_cage", [qw/moose_feeder/] );
2164
2165 The role list behaves in the same way as C<check_roles>. However, the ACL
2166 plugin isn't limited to just interacting with the Roles plugin. We can use a
2167 code reference instead. For example, to allow either moose trainers or moose
2168 feeders into the moose cage, we can create a more complex check:
2169
2170     Zoo->deny_access_unless( "/moose_cage", sub {
2171         my $c = shift;
2172         $c->check_roles( "moose_trainer" ) || $c->check_roles( "moose_feeder" );
2173     });
2174
2175 The more specific a role, the earlier it will be checked. Let's say moose
2176 feeders are now restricted to only the C<feed_moose> action, while moose
2177 trainers get access everywhere:
2178
2179     Zoo->deny_access_unless( "/moose_cage", [qw/moose_trainer/] );
2180     Zoo->allow_access_if( "/moose_cage/feed_moose", [qw/moose_feeder/]);
2181
2182 When the C<feed_moose> action is accessed the second check will be made. If the
2183 user is a C<moose_feeder>, then access will be immediately granted. Otherwise,
2184 the next rule in line will be tested - the one checking for a C<moose_trainer>.
2185 If this rule is not satisfied, access will be immediately denied.
2186
2187 Rules applied to the same path will be checked in the order they were added.
2188
2189 Lastly, handling access denial events is done by creating an C<access_denied>
2190 private action:
2191
2192     sub access_denied : Private {
2193         my ( $self, $c, $action ) = @_;
2194
2195         
2196     }
2197
2198 This action works much like auto, in that it is inherited across namespaces
2199 (not like object oriented code). This means that the C<access_denied> action
2200 which is B<nearest> to the action which was blocked will be triggered.
2201
2202 If this action does not exist, an error will be thrown, which you can clean up
2203 in your C<end> private action instead.
2204
2205 Also, it's important to note that if you restrict access to "/" then C<end>,
2206 C<default>, etc will also be restricted.
2207
2208    MyApp->acl_allow_root_internals;
2209
2210 will create rules that permit access to C<end>, C<begin>, and C<auto> in the
2211 root of your app (but not in any other controller).
2212
2213 =head3 More Information
2214
2215 L<http://search.cpan.org/perldoc?Catalyst::Plugin::Authorization::Roles>
2216 L<http://search.cpan.org/perldoc?Catalyst::Plugin::Authorization::ACL>
2217
2218 =head1 AUTHORS
2219
2220 Sebastian Riedel, C<sri@oook.de>
2221 Danijel Milicevic, C<me@danijel.de>
2222 Viljo Marrandi, C<vilts@yahoo.com>  
2223 Marcus Ramberg, C<mramberg@cpan.org>
2224 Jesse Sheidlower, C<jester@panix.com>
2225 Andy Grundman, C<andy@hybridized.org> 
2226 Chisel Wright, C<pause@herlpacker.co.uk>
2227 Will Hawes, C<info@whawes.co.uk>
2228 Gavin Henry, C<ghenry@perl.me.uk>
2229
2230
2231 =head1 COPYRIGHT
2232
2233 This program is free software, you can redistribute it and/or modify it
2234 under the same terms as Perl itself.