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