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