3 Catalyst::Manual::Cookbook - Cooking with Catalyst
7 Yummy code like your mum used to bake!
13 These recipes cover some basic stuff that is worth knowing for catalyst developers.
15 =head2 Delivering a Custom Error Page
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.
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>).
30 my ( $self, $c ) = @_;
32 if ( scalar @{ $c->error } ) {
33 $c->stash->{errors} = $c->error;
34 $c->stash->{template} = 'errors.tt';
35 $c->forward('MyApp::View::TT');
39 return 1 if $c->response->status =~ /^3\d\d$/;
40 return 1 if $c->response->body;
42 unless ( $c->response->content_type ) {
43 $c->response->content_type('text/html; charset=utf-8');
46 $c->forward('MyApp::View::TT');
49 You can manually set errors in your code to trigger this page by calling
51 $c->error( 'You broke me!' );
53 =head2 Disable statistics
55 Just add this line to your application class if you don't want those nifty
56 statistics in your debug messages.
58 sub Catalyst::Log::info { }
60 =head2 Enable debug status in the environment
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.
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.
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.
80 Catalyst uses two types of plugins to represent sessions:
84 A State module is used to keep track of the state of the session between the
85 users browser, and your application.
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.
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).
97 =head3 Authentication magic
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.
103 =head3 Using a session
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.
112 Session::Store::FastMmap
113 Session::State::Cookie
117 ## Write data into the session
119 sub add_item : Local {
120 my ( $self, $c ) = @_;
122 my $item_id = $c->req->param("item");
124 push @{ $c->session->{items} }, $item_id;
128 ## A page later we retrieve the data from the session:
130 sub get_items : Local {
131 my ( $self, $c ) = @_;
133 $c->stash->{items_to_display} = $c->session->{items};
138 =head3 More information
140 L<http://search.cpan.org/dist/Catalyst-Plugin-Session>
142 L<http://search.cpan.org/dist/Catalyst-Plugin-Session-State-Cookie>
144 L<http://search.cpan.org/dist/Catalyst-Plugin-Session-State-URI>
146 L<http://search.cpan.org/dist/Catalyst-Plugin-Session-Store-FastMmap>
148 L<http://search.cpan.org/dist/Catalyst-Plugin-Session-Store-File>
150 L<http://search.cpan.org/dist/Catalyst-Plugin-Session-Store-DBI>
152 =head2 Configure your application
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.
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.
164 In your application class (e.g. C<lib/MyApp.pm>):
168 __PACKAGE__->config( YAML::LoadFile(__PACKAGE__->config->{'home'} . '/myapp.yml') );
171 Now create C<myapp.yml> in your application home:
174 # DO NOT USE TABS FOR INDENTATION OR label/value SEPARATION!!!
177 # session; perldoc Catalyst::Plugin::Session::FastMmap
181 storage: '/tmp/myapp.session'
183 # emails; perldoc Catalyst::Plugin::Email
184 # this passes options as an array :(
189 This is equivalent to:
191 # configure base package
192 __PACKAGE__->config( name => MyApp );
193 # configure authentication
194 __PACKAGE__->config->{authentication} = {
195 user_class => 'MyApp::Model::MyDB::Customer',
199 __PACKAGE__->config->{session} = {
203 # configure email sending
204 __PACKAGE__->config->{email} = [qw/SMTP localhost/];
208 =head1 Users and Access Control
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
215 =head2 Authentication (logging in)
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>.
221 =head2 Pass-through login (and other actions)
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
229 sub begin : Private {
231 foreach my $action (qw/login docommand foo bar whatever/) {
232 if ($c->req->params->{"__${action}"}) {
233 $c->forward($action);
239 =head2 Role-based Authorization
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.
245 The C<login> and C<logout> methods and view template are exactly the same as
246 in the previous example.
248 The L<Catalyst::Plugin::Authorization::Roles> plugin is required when
253 Authentication::Credential::Password
254 Authentication::Store::Htpasswd
258 Roles are implemented automatically when using
259 L<Catalyst::Authentication::Store::Htpasswd>:
261 # no additional role configuration required
262 __PACKAGE__->config->{authentication}{htpasswd} = "passwdfile";
264 Or can be set up manually when using L<Catalyst::Authentication::Store::DBIC>:
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',
272 # DBIx::Class only (omit if using Class::DBI)
273 'role_rel' => 'user_role',
275 # Class::DBI only, (omit if using DBIx::Class)
276 'user_role_class' => 'My::Model::CDBI::UserRole'
277 'user_role_role_field' => 'role',
280 To restrict access to any action, you can use the C<check_user_roles> method:
282 sub restricted : Local {
283 my ( $self, $c ) = @_;
285 $c->detach("unauthorized")
286 unless $c->check_user_roles( "admin" );
288 # do something restricted here
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:
294 sub also_restricted : Global {
295 my ( $self, $c ) = @_;
296 $c->assert_user_roles( qw/ user admin / );
299 =head2 Authentication/Authorization
301 This is done in several steps:
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>.
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.
321 The Catalyst Authentication system is made up of many interacting modules, to
322 give you the most flexibility possible.
324 =head4 Credential verifiers
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.
332 Password - Simple username/password checking.
333 HTTPD - Checks using basic HTTP auth.
334 TypeKey - Check using the typekey system.
336 =head3 Storage backends
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.
344 DBIC - Storage using a database.
345 Minimal - Storage using a simple hash (for testing).
349 A User object is created by either the storage backend or the credential
350 verifier, and filled with the retrieved user information.
354 Hash - A simple hash of keys and values.
356 =head3 ACL authorization
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
362 =head3 Roles authorization
364 Authorization by roles is for assigning users to groups, which can then be
365 assigned to ACLs, or just checked when needed.
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
374 =head3 Checking roles
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.
382 use Catalyst qw/Authentication
383 Authentication::Credential::Password
384 Authentication::Store::Htpasswd
385 Authorization::Roles/;
387 __PACKAGE__->config->{authentication}{htpasswd} = "passwdfile";
392 if ( my $user = $c->req->param("user")
393 and my $password = $c->req->param("password") )
395 if ( $c->login( $user, $password ) ) {
396 $c->res->body( "hello " . $c->user->name );
406 sub restricted : Local {
407 my ( $self, $c ) = @_;
409 $c->detach("unauthorized")
410 unless $c->check_user_roles( "admin" );
412 # do something restricted here
415 =head3 Using authentication in a testing environment
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.
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
431 use Catalyst::Plugin::Authentication::Store::Minimal::Backend;
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' },
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.
443 =head3 More information
445 L<http://search.cpan.org/perldoc?Catalyst::Plugin::Authentication> has a longer explanation.
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
456 =head3 Role Based Access Control
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:
462 package Zoo::Controller::MooseCage;
464 sub feed_moose : Local {
465 my ( $self, $c ) = @_;
467 $c->model( "Moose" )->eat( $c->req->param("food") );
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.
474 The Authorization::Roles plugin let's us perform role based access control
475 checks. Let's load it:
478 Authentication # yadda yadda
482 And now our action should look like this:
484 sub feed_moose : Local {
485 my ( $self, $c ) = @_;
487 if ( $c->check_roles( "moose_feeder" ) ) {
488 $c->model( "Moose" )->eat( $c->req->param("food") );
490 $c->stash->{error} = "unauthorized";
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.
497 C<check_roles> has a sister method, C<assert_roles>, which throws an exception
498 if any roles are missing.
500 Some roles that might actually make sense in, say, a forum application:
514 each with a distinct task (system administration versus content administration).
516 =head3 Access Control Lists
518 Checking for roles all the time can be tedious and error prone.
520 The Authorization::ACL plugin let's us declare where we'd like checks to be
521 done automatically for us.
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:
526 Zoo->deny_access_unless( "/moose_cage", [qw/moose_feeder/] );
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:
533 Zoo->deny_access_unless( "/moose_cage", sub {
535 $c->check_roles( "moose_trainer" ) || $c->check_roles( "moose_feeder" );
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:
542 Zoo->deny_access_unless( "/moose_cage", [qw/moose_trainer/] );
543 Zoo->allow_access_if( "/moose_cage/feed_moose", [qw/moose_feeder/]);
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.
550 Rules applied to the same path will be checked in the order they were added.
552 Lastly, handling access denial events is done by creating an C<access_denied>
555 sub access_denied : Private {
556 my ( $self, $c, $action ) = @_;
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.
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.
568 Also, it's important to note that if you restrict access to "/" then C<end>,
569 C<default>, etc will also be restricted.
571 MyApp->acl_allow_root_internals;
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).
578 Models are where application data belongs. Catalyst is exteremely
579 flexible with the kind of models that it can use. The recipes here
582 =head2 Using existing DBIC (etc.) classes with Catalyst
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:
589 package MyApp::Model::DB;
590 use base qw/Catalyst::Model::DBIC::Schema/;
592 schema_class => 'Some::DBIC::Schema',
593 connect_info => ['dbi:SQLite:foo.db', '', '', {AutoCommit=>1}];
597 and that's it! Now C<Some::DBIC::Schema> is part of your
598 Cat app as C<MyApp::Model::DB>.
600 =head2 DBIx::Class as a Catalyst Model
602 See L<Catalyst::Model::DBIC::Schema>.
606 Unlike SOAP, XMLRPC is a very simple (and imo elegant) web-services
607 protocol, exchanging small XML messages like these:
612 TE: deflate,gzip;q=0.3
613 Connection: TE, close
617 User-Agent: SOAP::Lite/Perl/0.60
619 Content-Type: text/xml
621 <?xml version="1.0" encoding="UTF-8"?>
623 <methodName>add</methodName>
625 <param><value><int>1</int></value></param>
626 <param><value><int>2</int></value></param>
633 Date: Tue, 20 Dec 2005 07:45:55 GMT
635 Content-Type: text/xml
639 <?xml version="1.0" encoding="us-ascii"?>
642 <param><value><int>3</int></value></param>
646 Now follow these few steps to implement the application:
648 1. Install Catalyst (5.61 or later), Catalyst::Plugin::XMLRPC (0.06 or
649 later) and SOAP::Lite (for XMLRPCsh.pl).
651 2. Create an application framework:
657 3. Add the XMLRPC plugin to MyApp.pm
659 use Catalyst qw/-Debug Static::Simple XMLRPC/;
661 4. Add an API controller
663 % ./script/myapp_create.pl controller API
665 5. Add a XMLRPC redispatch method and an add method with Remote
666 attribute to lib/MyApp/Controller/API.pm
668 sub default : Private {
669 my ( $self, $c ) = @_;
674 my ( $self, $c, $a, $b ) = @_;
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
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.
685 6. That's it! You have built your first web service. Let's test it with
686 XMLRPCsh.pl (part of SOAP::Lite):
688 % ./script/myapp_server.pl
690 % XMLRPCsh.pl http://127.0.0.1:3000/api
691 Usage: method[(parameters)]
693 --- XMLRPC RESULT ---
698 Your return data type is usually auto-detected, but you can easily
699 enforce a specific one.
702 my ( $self, $c, $a, $b ) = @_;
703 return RPC::XML::int->new( $a + $b );
710 Views pertain to the display of your application. As with models,
711 catalyst is uncommonly flexible. The recipes below are just a start.
713 =head2 Catalyst::View::TT
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
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.
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.
729 =head3 Creating your View
731 Catalyst::View::TT provides two different helpers for us to use: TT and
736 Create a basic Template Toolkit View using the provided helper script:
738 script/myapp_create.pl view TT TT
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
746 my ( $self, $c ) = @_;
748 $c->stash->{template} = 'hello.tt';
750 $c->forward( $c->view('TT') );
753 In practice you wouldn't do the forwarding manually, but would
754 use L<Catalyst::Action::RenderView>.
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.
764 Once again, you can use the helper script:
766 script/myapp_create.pl view TT TTSite
768 This time, the helper sets several options for us in the generated View.
770 __PACKAGE__->config({
771 CATALYST_VAR => 'Catalyst',
773 MyApp->path_to( 'root', 'src' ),
774 MyApp->path_to( 'root', 'lib' )
776 PRE_PROCESS => 'config/main',
777 WRAPPER => 'site/wrapper',
778 ERROR => 'error.tt2',
786 INCLUDE_PATH defines the directories that Template Toolkit should search
787 for the template files.
791 PRE_PROCESS is used to process configuration options which are common to
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.
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.
805 Several configuration files in root/lib/config are called by PRE_PROCESS.
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.
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.
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.
826 In our controllers, we can add data to the stash, and then access it
827 from the template. For instance:
830 my ( $self, $c ) = @_;
832 $c->stash->{name} = 'Adam';
834 $c->stash->{template} = 'hello.tt';
836 $c->forward( $c->view('TT') );
841 <strong>Hello, [% name %]!</strong>
843 When you view this page, it will display "Hello, Adam!"
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.
852 my ( $self, $c ) = @_;
854 $c->stash->{names} = [ 'Adam', 'Dave', 'John' ];
856 $c->stash->{template} = 'hello.tt';
858 $c->forward( $c->view('TT') );
863 [% FOREACH name IN names %]
864 <strong>Hello, [% name %]!</strong><br />
867 This allowed us to loop through each item in the arrayref, and display a
868 line for each name that we have.
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.
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.
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.
889 In your template, you can use the following:
891 <a href="[% c.uri_for('/login') %]">Login Here</a>
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.
897 <a href="[% c.uri_for('2005','10', '24') %]">October, 24 2005</a>
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.
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.
905 L<http://search.cpan.org/perldoc?Catalyst>
907 L<http://search.cpan.org/perldoc?Catalyst%3A%3AView%3A%3ATT>
909 L<http://search.cpan.org/perldoc?Template>
911 =head2 Adding RSS feeds
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
918 =head3 Using TT templates
920 This is the aproach used in Agave (L<http://dev.rawmode.org/>).
925 $c->stash->{template}='rss.tt';
928 Then you need a template. Here's the one from Agave:
930 <?xml version="1.0" encoding="UTF-8"?>
931 <rss version="2.0" xmlns:dc="http://purl.org/dc/elements/1.1/">
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>
938 [% WHILE (post = posts.next) %]
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>
951 =head3 Using XML::Feed
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
960 $c->forward('view'); # get the entries
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
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);
975 $c->res->body( $feed->as_xml );
978 A little more code in the controller, but with this approach you're
979 pretty sure to get something that validates.
981 Note that for both of the above aproaches, you'll need to set the
982 content type like this:
984 $c->res->content_type('application/rss+xml');
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.
991 Now, go ahead and make RSS feeds for all your stuff. The world *needs*
992 updates on your goldfish!
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.
1001 =head2 Extending RenderView (formerly DefaultEnd)
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.
1009 You can extend it like this:
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>
1015 sub end : ActionClass('RenderView') {
1016 my ( $self, $c ) = @_;
1017 # do stuff here; the RenderView action is called afterwards
1020 To add things to an C<end> action that are called I<after> rendering,
1021 you can set it up like this:
1023 sub render : ActionClass('RenderView') { }
1026 my ( $self, $c ) = @_;
1027 $c->forward('render');
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.
1042 =head3 Type attributes
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.
1048 Assume our Controller module starts with the following package declaration:
1050 package MyApp::Controller::Buckets;
1052 and we are running our application on localhost, port 3000 (the test
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.
1063 sub my_handles : Path('handles') { .. }
1067 http://localhost:3000/buckets/handles
1071 sub my_handles : Path('/handles') { .. }
1075 http://localhost:3000/handles
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.
1083 sub my_handles : Local { .. }
1087 http://localhost:3000/buckets/my_handles
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.
1094 sub my_handles : Global { .. }
1098 http://localhost:3000/my_handles
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.
1106 sub my_handles : Regex('^handles') { .. }
1110 http://localhost:3000/handles
1114 http://localhost:3000/handles_and_other_parts
1120 A LocalRegex is similar to a Regex, except it only matches below the current
1121 controller namespace.
1123 sub my_handles : LocalRegex(^handles') { .. }
1127 http://localhost:3000/buckets/handles
1131 http://localhost:3000/buckets/handles_and_other_parts
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
1141 sub my_handles : Private { .. }
1143 becomes nothing at all..
1145 Catalyst also predefines some special Private actions, which you can override,
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 >>.
1158 sub default : Private { .. }
1160 works for all unknown URLs, in this controller namespace, or every one if put
1161 directly into MyApp.pm.
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.
1169 sub index : Private { .. }
1173 http://localhost:3000/buckets
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.
1182 sub begin : Private { .. }
1186 http://localhost:3000/bucket/(anything)?
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.
1198 sub end : Private { .. }
1200 is called once after any actions when
1202 http://localhost:3000/bucket/(anything)?
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).
1214 sub auto : Private { .. }
1218 sub auto : Private { .. }
1220 will both be called when visiting
1222 http://localhost:3000/bucket/(anything)?
1228 =head3 A word of warning
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.
1234 =head3 More Information
1236 L<http://search.cpan.org/author/SRI/Catalyst-5.61/lib/Catalyst/Manual/Intro.pod>
1238 L<http://dev.catalyst.perl.org/wiki/FlowChart>
1240 =head2 Component-based Subrequests
1242 See L<Catalyst::Plugin::SubRequest>.
1246 =head3 Single file upload with Catalyst
1248 To implement uploads in Catalyst, you need to have a HTML form similar to
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">
1257 It's very important not to forget C<enctype="multipart/form-data"> in
1260 Catalyst Controller module 'upload' action:
1262 sub upload : Global {
1263 my ($self, $c) = @_;
1265 if ( $c->request->parameters->{form_submit} eq 'yes' ) {
1267 if ( my $upload = $c->request->upload('my_file') ) {
1269 my $filename = $upload->filename;
1270 my $target = "/tmp/upload/$filename";
1272 unless ( $upload->link_to($target) || $upload->copy_to($target) ) {
1273 die( "Failed to copy '$filename' to '$target': $!" );
1278 $c->stash->{template} = 'file_upload.html';
1281 =head3 Multiple file upload with Catalyst
1283 Code for uploading multiple files from one form needs a few changes:
1285 The form should have this basic structure:
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">
1295 And in the controller:
1297 sub upload : Local {
1298 my ($self, $c) = @_;
1300 if ( $c->request->parameters->{form_submit} eq 'yes' ) {
1302 for my $field ( $c->req->upload ) {
1304 my $upload = $c->req->upload($field);
1305 my $filename = $upload->filename;
1306 my $target = "/tmp/upload/$filename";
1308 unless ( $upload->link_to($target) || $upload->copy_to($target) ) {
1309 die( "Failed to copy '$filename' to '$target': $!" );
1314 $c->stash->{template} = 'file_upload.html';
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.
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.
1326 For more information about uploads and usable methods look at
1327 L<Catalyst::Request::Upload> and L<Catalyst::Request>.
1329 =head2 Forwarding with arguments
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:
1336 # version 5.30 and later:
1337 $c->forward('/wherever', [qw/arg1 arg2 arg3/]);
1340 $c->req->args([qw/arg1 arg2 arg3/]);
1341 $c->forward('/wherever');
1343 (See the L<Catalyst::Manual::Intro> Flow_Control section for more
1344 information on passing arguments via C<forward>.)
1349 The recipes below describe aspects of the deployment process,
1350 including web server engines and tips to improve application efficiency.
1352 =head2 mod_perl Deployment
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.
1362 mod_perl is very fast and your app will benefit from being loaded in memory
1363 within each Apache process.
1365 =head4 Shared memory for multiple apps
1367 If you need to run several Catalyst apps on the same server, mod_perl will
1368 share the memory for common modules.
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
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.
1388 =head4 Cannot run multiple versions of the same app
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.
1395 Now that we have that out of the way, let's talk about setting up mod_perl
1396 to run a Catalyst app.
1398 =head4 1. Install Catalyst::Engine::Apache
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.
1405 =head4 2. Install Apache with mod_perl
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.
1414 In Debian, the following commands should get you going.
1416 apt-get install apache2-mpm-prefork
1417 apt-get install libapache2-mod-perl2
1419 =head4 3. Configure your application
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.
1425 PerlSwitches -I/var/www/MyApp/lib
1430 PerlResponseHandler MyApp
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
1439 For an example Apache 1.3 configuration, please see the documentation for
1440 L<Catalyst::Engine::Apache::MP13>.
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/.
1447 =head3 Other Options
1449 =head4 Non-root location
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
1457 PerlResponseHandler MyApp
1460 When running this way, it is best to make use of the C<uri_for> method in
1461 Catalyst for constructing correct links.
1463 =head4 Static file handling
1465 Static files can be served directly by Apache for a performance boost.
1467 DocumentRoot /var/www/MyApp/root
1469 SetHandler default-handler
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.
1476 =head2 Catalyst on shared hosting
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
1483 perl -MCPAN -e shell
1485 and go through the standard CPAN configuration process. Then exit out
1486 without installing anything. Next, open your .bashrc and add
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
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
1495 'make_install_arg' => qq[SITEPREFIX=$ENV{HOME}/local],
1496 'makepl_arg' => qq[INSTALLDIRS=site install_base=$ENV{HOME}/local],
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:
1503 cd path/to/mydomain.com
1504 ln -s ~/lib/MyApp/script script
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):
1511 RewriteCond %{REQUEST_URI} !^/?script/myapp_fastcgi.pl
1512 RewriteRule ^(.*)$ script/myapp_fastcgi.pl/$1 [PT,L]
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 :) )
1518 =head2 FastCGI Deployment
1520 FastCGI is a high-performance extension to CGI. It is suitable
1521 for production environments.
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.
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
1540 =head4 Load-balancing
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.
1546 =head4 Multiple versions of the same app
1548 Each FastCGI application is a separate process, so you can run different
1549 versions of the same app on a single server.
1551 =head4 Can run with threaded Apache
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.
1558 =head4 More complex environment
1560 With FastCGI, there are more things to monitor and more processes running
1561 than when using mod_perl.
1565 =head4 1. Install Apache with mod_fastcgi
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.
1571 =head4 2. Configure your application
1573 # Serve static content directly
1574 DocumentRoot /var/www/MyApp/root
1575 Alias /static /var/www/MyApp/root/static
1577 FastCgiServer /var/www/MyApp/script/myapp_fastcgi.pl -processes 3
1578 Alias /myapp/ /var/www/MyApp/script/myapp_fastcgi.pl/
1580 # Or, run at the root
1581 Alias / /var/www/MyApp/script/myapp_fastcgi.pl/
1583 The above commands will launch 3 app processes and make the app available at
1586 =head3 Standalone server mode
1588 While not as easy as the previous method, running your app as an external
1589 server gives you much more flexibility.
1591 First, launch your app as a standalone server listening on a socket.
1593 script/myapp_fastcgi.pl -l /tmp/myapp.socket -n 5 -p /tmp/myapp.pid -d
1595 You can also listen on a TCP port if your web server is not on the same
1598 script/myapp_fastcgi.pl -l :8080 -n 5 -p /tmp/myapp.pid -d
1600 You will probably want to write an init script to handle starting/stopping
1601 of the app using the pid file.
1603 Now, we simply configure Apache to connect to the running server.
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
1608 Alias /_errors /var/www/MyApp/root/error-pages
1609 ErrorDocument 502 /_errors/502.html
1611 FastCgiExternalServer /tmp/myapp -socket /tmp/myapp.socket
1612 Alias /myapp/ /tmp/myapp/
1614 # Or, run at the root
1619 L<Catalyst::Engine::FastCGI>.
1621 =head2 Quick deployment: Building PAR Packages
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...
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!
1631 =head3 Follow these few points to try it out!
1633 1. Install Catalyst and PAR 0.89 (or later)
1635 % perl -MCPAN -e 'install Catalyst'
1637 % perl -MCPAN -e 'install PAR'
1640 2. Create a application
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:
1652 Congratulations! Your package "myapp.par" is ready, the following
1653 steps are just optional.
1655 3. Test your PAR package with "parl" (no typo)
1659 [parl] myapp[.par] [script] [arguments]
1662 parl myapp.par myapp_server.pl -r
1672 % parl myapp.par myapp_server.pl
1673 You can connect to your server at http://localhost:3000
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.
1679 6. Want to create a binary that includes the Perl interpreter?
1681 % pp -o myapp myapp.par
1682 % ./myapp myapp_server.pl
1683 You can connect to your server at http://localhost:3000
1685 =head2 Serving static content
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.
1693 =head3 Introduction to Static::Simple
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.
1703 Using the plugin is as simple as setting your use line in MyApp.pm to include:
1705 use Catalyst qw/Static::Simple/;
1707 and already files will be served.
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:
1722 root/controller/stuff.tt
1725 root/static/css/main.css
1726 root/static/images/logo.jpg
1727 root/static/js/code.js
1730 All static content lives under C<root/static>, with everything else being
1731 Template Toolkit files.
1737 You may of course want to change the default locations, and make
1738 Static::Simple look somewhere else, this is as easy as:
1740 MyApp->config->{static}->{include_path} = [
1741 MyApp->config->{root},
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
1750 =item Static directories
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:
1755 MyApp->config->{static}->{dirs} = [
1760 =item File extensions
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
1766 MyApp->config->{static}->{ignore_extensions} = [
1767 qw/tmpl tt tt2 html xhtml/
1770 =item Ignoring directories
1772 Entire directories can be ignored. If used with include_path,
1773 directories relative to the include_path dirs will also be ignored:
1775 MyApp->config->{static}->{ignore_dirs} = [ qw/tmpl css/ ];
1779 =head3 More information
1781 L<http://search.cpan.org/dist/Catalyst-Plugin-Static-Simple/>
1783 =head3 Serving manually with the Static plugin with HTTP::Daemon (myapp_server.pl)
1785 In some situations you might want to control things more directly,
1786 using L<Catalyst::Plugin::Static>.
1788 In your main application class (MyApp.pm), load the plugin:
1790 use Catalyst qw/-Debug FormValidator Static OtherPlugin/;
1792 You will also need to make sure your end method does I<not> forward
1793 static content to the view, perhaps like this:
1796 my ( $self, $c ) = @_;
1798 $c->forward( 'MyApp::View::TT' )
1799 unless ( $c->res->body || !$c->stash->{template} );
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>.
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>.
1810 $ script/myapp_create.pl controller Static
1812 Edit the file and add the following methods:
1814 # serve all files under /static as static files
1815 sub default : Path('/static') {
1816 my ( $self, $c ) = @_;
1818 # Optional, allow the browser to cache the content
1819 $c->res->headers->header( 'Cache-Control' => 'max-age=86400' );
1821 $c->serve_static; # from Catalyst::Plugin::Static
1824 # also handle requests for /favicon.ico
1825 sub favicon : Path('/favicon.ico') {
1826 my ( $self, $c ) = @_;
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:
1834 <link rel="icon" href="/static/myapp.ico" type="image/x-icon" />
1836 =head3 Common problems with the Static plugin
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.
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:
1850 if ($c->req->path =~ /css$/i) {
1851 $c->serve_static( "text/css" );
1856 =head3 Serving Static Files with Apache
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
1866 use lib qw(/var/www/MyApp/lib);
1871 ServerName myapp.example.com
1872 DocumentRoot /var/www/MyApp/root
1874 SetHandler perl-script
1877 <LocationMatch "/(static|favicon.ico)">
1878 SetHandler default-handler
1882 And here's a simpler example that'll get you started:
1884 Alias /static/ "/my/static/files/"
1885 <Location "/static">
1891 Catalyst makes it easy to employ several different types of caching to
1892 speed up your applications.
1894 =head3 Cache Plugins
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.
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.
1905 use Catalyst qw/Cache::FileCache/;
1910 sub render_pod : Local {
1911 my ( self, $c ) = @_;
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;
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' );
1924 $c->stash->{pod} = $cached_pod;
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.
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.
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.
1941 sub front_page : Path('/') {
1942 my ( $self, $c ) = @_;
1944 $c->forward( 'get_news_articles' );
1945 $c->forward( 'build_lots_of_boxes' );
1946 $c->forward( 'more_slow_stuff' );
1948 $c->stash->{template} = 'index.tt';
1951 We can add the PageCache plugin to speed things up.
1953 use Catalyst qw/Cache::FileCache PageCache/;
1955 sub front_page : Path ('/') {
1956 my ( $self, $c ) = @_;
1958 $c->cache_page( 300 );
1960 # same processing as above
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.
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.
1971 You can even get that front-end Squid proxy to help out by enabling HTTP
1972 headers for the cached page.
1974 MyApp->config->{page_cache}->{set_http_headers} = 1;
1976 This would now set the following headers so proxies and browsers may cache
1977 the content themselves.
1979 Cache-Control: max-age=($expire_time - time)
1980 Expires: $expire_time
1981 Last-Modified: $cache_created_time
1983 =head3 Template Caching
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.
1990 package MyApp::View::TT;
1994 use base 'Catalyst::View::TT';
1996 __PACKAGE__->config(
1997 COMPILE_DIR => '/tmp/template_cache',
2004 See the documentation for each cache plugin for more details and other
2005 available configuration options.
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>
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
2022 Catalyst provides a convenient way of testing your application during
2023 development and before deployment in a real environment.
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.
2030 Let's examine a skeleton application's C<t/> directory:
2032 mundus:~/MyApp chansen$ ls -l t/
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
2042 Verifies that the application loads, compiles, and returns a successful
2047 Verifies that all POD is free from errors. Only executed if the C<TEST_POD>
2048 environment variable is true.
2050 =item C<03podcoverage.t>
2052 Verifies that all methods/functions have POD coverage. Only executed if the
2053 C<TEST_POD> environment variable is true.
2057 =head3 Creating tests
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' );
2063 4 ok( request('/')->is_success );
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.
2069 C<Catalyst::Test> exports two functions, C<request> and C<get>. Each can
2070 take three different arguments:
2074 =item A string which is a relative or absolute URI.
2076 request('/my/path');
2077 request('http://www.host.com/my/path');
2079 =item An instance of C<URI>.
2081 request( URI->new('http://www.host.com/my/path') );
2083 =item An instance of C<HTTP::Request>.
2085 request( HTTP::Request->new( GET => 'http://www.host.com/my/path') );
2089 C<request> returns an instance of C<HTTP::Response> and C<get> returns the
2090 content (body) of the response.
2092 =head3 Running tests locally
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)
2101 C<CATALYST_DEBUG=0> ensures that debugging is off; if it's enabled you
2102 will see debug logs between tests.
2104 C<TEST_POD=1> enables POD checking and coverage.
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.
2109 =head3 Running tests remotely
2111 mundus:~/MyApp chansen$ CATALYST_SERVER=http://localhost:3000/ prove --lib lib/ t/01app.t
2113 All tests successful.
2114 Files=1, Tests=2, 0 wallclock secs ( 0.40 cusr + 0.01 csys = 0.41 CPU)
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
2120 =head3 C<Test::WWW::Mechanize> and Catalyst
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:
2125 use Test::More tests => 6;
2126 use_ok( Test::WWW::Mechanize::Catalyst, 'MyApp' );
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' );
2135 =head3 Further Reading
2139 =item Catalyst::Test
2141 L<http://search.cpan.org/dist/Catalyst/lib/Catalyst/Test.pm>
2143 =item Test::WWW::Mechanize::Catalyst
2145 L<http://search.cpan.org/dist/Test-WWW-Mechanize-Catalyst/lib/Test/WWW/Mechanize/Catalyst.pm>
2147 =item Test::WWW::Mechanize
2149 L<http://search.cpan.org/dist/Test-WWW-Mechanize/Mechanize.pm>
2151 =item WWW::Mechanize
2153 L<http://search.cpan.org/dist/WWW-Mechanize/lib/WWW/Mechanize.pm>
2155 =item LWP::UserAgent
2157 L<http://search.cpan.org/dist/libwww-perl/lib/LWP/UserAgent.pm>
2161 L<http://search.cpan.org/dist/libwww-perl/lib/HTML/Form.pm>
2165 L<http://search.cpan.org/dist/libwww-perl/lib/HTTP/Message.pm>
2169 L<http://search.cpan.org/dist/libwww-perl/lib/HTTP/Request.pm>
2171 =item HTTP::Request::Common
2173 L<http://search.cpan.org/dist/libwww-perl/lib/HTTP/Request/Common.pm>
2175 =item HTTP::Response
2177 L<http://search.cpan.org/dist/libwww-perl/lib/HTTP/Response.pm>
2181 L<http://search.cpan.org/dist/libwww-perl/lib/HTTP/Status.pm>
2185 L<http://search.cpan.org/dist/URI/URI.pm>
2189 L<http://search.cpan.org/dist/Test-Simple/lib/Test/More.pm>
2193 L<http://search.cpan.org/dist/Test-Pod/Pod.pm>
2195 =item Test::Pod::Coverage
2197 L<http://search.cpan.org/dist/Test-Pod-Coverage/Coverage.pm>
2199 =item prove (Test::Harness)
2201 L<http://search.cpan.org/dist/Test-Harness/bin/prove>
2205 =head3 More Information
2207 L<http://search.cpan.org/perldoc?Catalyst::Plugin::Authorization::Roles>
2208 L<http://search.cpan.org/perldoc?Catalyst::Plugin::Authorization::ACL>
2212 Sebastian Riedel C<sri@oook.de>
2214 Danijel Milicevic C<me@danijel.de>
2216 Viljo Marrandi C<vilts@yahoo.com>
2218 Marcus Ramberg C<mramberg@cpan.org>
2220 Jesse Sheidlower C<jester@panix.com>
2222 Andy Grundman C<andy@hybridized.org>
2224 Chisel Wright C<pause@herlpacker.co.uk>
2226 Will Hawes C<info@whawes.co.uk>
2228 Gavin Henry C<ghenry@perl.me.uk>
2230 Kieren Diment C<kd@totaldatasolution.com>
2234 This document is free, you can redistribute it and/or modify it
2235 under the same terms as Perl itself.