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 Skipping your VCS's directories
210 Catalyst uses Module::Pluggable to load Models, Views and Controllers.
211 Module::Pluggable will scan through all directories and load modules
212 it finds. Sometimes you might want to skip some of these directories,
213 for example when your version control system makes a subdirectory with
214 meta-information in every version-controlled directory. While
215 Catalyst skips subversion and CVS directories already, there are other
216 source control systems. Here is the configuration you need to add
217 their directories to the list to skip.
219 You can make catalyst skip these directories using the Catalyst config:
221 # Configure the application
224 setup_components => { except => qr/SCCS/ },
227 See the Module::Pluggable manual page for more information on B<except>
230 =head1 Users and Access Control
232 Most multiuser, and some single user web applications require that
233 users identify themselves, and the application is often required to
234 define those roles. The recipes below describe some ways of doing
237 =head2 Authentication (logging in)
239 This is extensively covered in other documentation; see in particular
240 L<Catalyst::Plugin::Authentication> and the Authentication chapter
241 of the Tutorial at L<Catalyst::Manual::Tutorial::Authorization>.
243 =head2 Pass-through login (and other actions)
245 An easy way of having assorted actions that occur during the processing
246 of a request that are orthogonal to its actual purpose - logins, silent
247 commands etc. Provide actions for these, but when they're required for
248 something else fill e.g. a form variable __login and have a sub begin
251 sub begin : Private {
253 foreach my $action (qw/login docommand foo bar whatever/) {
254 if ($c->req->params->{"__${action}"}) {
255 $c->forward($action);
261 =head2 Role-based Authorization
263 For more advanced access control, you may want to consider using role-based
264 authorization. This means you can assign different roles to each user, e.g.
265 "user", "admin", etc.
267 The C<login> and C<logout> methods and view template are exactly the same as
268 in the previous example.
270 The L<Catalyst::Plugin::Authorization::Roles> plugin is required when
275 Authentication::Credential::Password
276 Authentication::Store::Htpasswd
280 Roles are implemented automatically when using
281 L<Catalyst::Authentication::Store::Htpasswd>:
283 # no additional role configuration required
284 __PACKAGE__->config->{authentication}{htpasswd} = "passwdfile";
286 Or can be set up manually when using L<Catalyst::Authentication::Store::DBIC>:
288 # Authorization using a many-to-many role relationship
289 __PACKAGE__->config->{authorization}{dbic} = {
290 'role_class' => 'My::Model::DBIC::Role',
291 'role_field' => 'name',
292 'user_role_user_field' => 'user',
294 # DBIx::Class only (omit if using Class::DBI)
295 'role_rel' => 'user_role',
297 # Class::DBI only, (omit if using DBIx::Class)
298 'user_role_class' => 'My::Model::CDBI::UserRole'
299 'user_role_role_field' => 'role',
302 To restrict access to any action, you can use the C<check_user_roles> method:
304 sub restricted : Local {
305 my ( $self, $c ) = @_;
307 $c->detach("unauthorized")
308 unless $c->check_user_roles( "admin" );
310 # do something restricted here
313 You can also use the C<assert_user_roles> method. This just gives an error if
314 the current user does not have one of the required roles:
316 sub also_restricted : Global {
317 my ( $self, $c ) = @_;
318 $c->assert_user_roles( qw/ user admin / );
321 =head2 Authentication/Authorization
323 This is done in several steps:
329 Getting the user to identify themselves, by giving you some piece of
330 information known only to you and the user. Then you can assume that the user
331 is who they say they are. This is called B<credential verification>.
335 Making sure the user only accesses functions you want them to access. This is
336 done by checking the verified users data against your internal list of groups,
337 or allowed persons for the current page.
343 The Catalyst Authentication system is made up of many interacting modules, to
344 give you the most flexibility possible.
346 =head4 Credential verifiers
348 A Credential module tables the user input, and passes it to a Store, or some
349 other system, for verification. Typically, a user object is created by either
350 this module or the Store and made accessible by a C<< $c->user >> call.
354 Password - Simple username/password checking.
355 HTTPD - Checks using basic HTTP auth.
356 TypeKey - Check using the typekey system.
358 =head3 Storage backends
360 A Storage backend contains the actual data representing the users. It is
361 queried by the credential verifiers. Updating the store is not done within
362 this system, you will need to do it yourself.
366 DBIC - Storage using a database.
367 Minimal - Storage using a simple hash (for testing).
371 A User object is created by either the storage backend or the credential
372 verifier, and filled with the retrieved user information.
376 Hash - A simple hash of keys and values.
378 =head3 ACL authorization
380 ACL stands for Access Control List. The ACL plugin allows you to regulate
381 access on a path by path basis, by listing which users, or roles, have access
384 =head3 Roles authorization
386 Authorization by roles is for assigning users to groups, which can then be
387 assigned to ACLs, or just checked when needed.
391 When you have chosen your modules, all you need to do is call the C<<
392 $c->login >> method. If called with no parameters, it will try to find
393 suitable parameters, such as B<username> and B<password>, or you can pass it
396 =head3 Checking roles
398 Role checking is done by using the C<< $c->check_user_roles >> method, this will
399 check using the currently logged in user (via C<< $c->user >>). You pass it
400 the name of a role to check, and it returns true if the user is a member.
404 use Catalyst qw/Authentication
405 Authentication::Credential::Password
406 Authentication::Store::Htpasswd
407 Authorization::Roles/;
409 __PACKAGE__->config->{authentication}{htpasswd} = "passwdfile";
414 if ( my $user = $c->req->param("user")
415 and my $password = $c->req->param("password") )
417 if ( $c->login( $user, $password ) ) {
418 $c->res->body( "hello " . $c->user->name );
428 sub restricted : Local {
429 my ( $self, $c ) = @_;
431 $c->detach("unauthorized")
432 unless $c->check_user_roles( "admin" );
434 # do something restricted here
437 =head3 Using authentication in a testing environment
439 Ideally, to write tests for authentication/authorization code one would first
440 set up a test database with known data, then use
441 L<Test::WWW::Mechanize::Catalyst> to simulate a user logging in. Unfortunately
442 the former can be rather awkward, which is why it's a good thing that the
443 authentication framework is so flexible.
445 Instead of using a test database, one can simply change the authentication
446 store to something a bit easier to deal with in a testing
447 environment. Additionally, this has the advantage of not modifying one's
448 database, which can be problematic if one forgets to use the testing instead of
453 use Catalyst::Plugin::Authentication::Store::Minimal::Backend;
455 # Sets up the user `test_user' with password `test_pass'
456 MyApp->default_auth_store(
457 Catalyst::Plugin::Authentication::Store::Minimal::Backend->new({
458 test_user => { password => 'test_pass' },
462 Now, your test code can call C<$c->login('test_user', 'test_pass')> and
463 successfully login, without messing with the database at all.
465 =head3 More information
467 L<http://search.cpan.org/perldoc?Catalyst::Plugin::Authentication> has a longer explanation.
473 Authorization is the step that comes after authentication. Authentication
474 establishes that the user agent is really representing the user we think it's
475 representing, and then authorization determines what this user is allowed to
478 =head3 Role Based Access Control
480 Under role based access control each user is allowed to perform any number of
481 roles. For example, at a zoo no one but specially trained personnel can enter
482 the moose cage (Mynd you, møøse bites kan be pretty nasti!). For example:
484 package Zoo::Controller::MooseCage;
486 sub feed_moose : Local {
487 my ( $self, $c ) = @_;
489 $c->model( "Moose" )->eat( $c->req->param("food") );
492 With this action, anyone can just come into the moose cage and feed the moose,
493 which is a very dangerous thing. We need to restrict this action, so that only
494 a qualified moose feeder can perform that action.
496 The Authorization::Roles plugin let's us perform role based access control
497 checks. Let's load it:
500 Authentication # yadda yadda
504 And now our action should look like this:
506 sub feed_moose : Local {
507 my ( $self, $c ) = @_;
509 if ( $c->check_roles( "moose_feeder" ) ) {
510 $c->model( "Moose" )->eat( $c->req->param("food") );
512 $c->stash->{error} = "unauthorized";
516 This checks C<< $c->user >>, and only if the user has B<all> the roles in the
517 list, a true value is returned.
519 C<check_roles> has a sister method, C<assert_roles>, which throws an exception
520 if any roles are missing.
522 Some roles that might actually make sense in, say, a forum application:
536 each with a distinct task (system administration versus content administration).
538 =head3 Access Control Lists
540 Checking for roles all the time can be tedious and error prone.
542 The Authorization::ACL plugin let's us declare where we'd like checks to be
543 done automatically for us.
545 For example, we may want to completely block out anyone who isn't a
546 C<moose_feeder> from the entire C<MooseCage> controller:
548 Zoo->deny_access_unless( "/moose_cage", [qw/moose_feeder/] );
550 The role list behaves in the same way as C<check_roles>. However, the ACL
551 plugin isn't limited to just interacting with the Roles plugin. We can use a
552 code reference instead. For example, to allow either moose trainers or moose
553 feeders into the moose cage, we can create a more complex check:
555 Zoo->deny_access_unless( "/moose_cage", sub {
557 $c->check_roles( "moose_trainer" ) || $c->check_roles( "moose_feeder" );
560 The more specific a role, the earlier it will be checked. Let's say moose
561 feeders are now restricted to only the C<feed_moose> action, while moose
562 trainers get access everywhere:
564 Zoo->deny_access_unless( "/moose_cage", [qw/moose_trainer/] );
565 Zoo->allow_access_if( "/moose_cage/feed_moose", [qw/moose_feeder/]);
567 When the C<feed_moose> action is accessed the second check will be made. If the
568 user is a C<moose_feeder>, then access will be immediately granted. Otherwise,
569 the next rule in line will be tested - the one checking for a C<moose_trainer>.
570 If this rule is not satisfied, access will be immediately denied.
572 Rules applied to the same path will be checked in the order they were added.
574 Lastly, handling access denial events is done by creating an C<access_denied>
577 sub access_denied : Private {
578 my ( $self, $c, $action ) = @_;
583 This action works much like auto, in that it is inherited across namespaces
584 (not like object oriented code). This means that the C<access_denied> action
585 which is B<nearest> to the action which was blocked will be triggered.
587 If this action does not exist, an error will be thrown, which you can clean up
588 in your C<end> private action instead.
590 Also, it's important to note that if you restrict access to "/" then C<end>,
591 C<default>, etc will also be restricted.
593 MyApp->acl_allow_root_internals;
595 will create rules that permit access to C<end>, C<begin>, and C<auto> in the
596 root of your app (but not in any other controller).
600 Models are where application data belongs. Catalyst is exteremely
601 flexible with the kind of models that it can use. The recipes here
604 =head2 Using existing DBIC (etc.) classes with Catalyst
606 Many people have existing Model classes that they would like to use with
607 Catalyst (or, conversely, they want to write Catalyst models that can be
608 used outside of Catalyst, e.g. in a cron job). It's trivial to write a
609 simple component in Catalyst that slurps in an outside Model:
611 package MyApp::Model::DB;
612 use base qw/Catalyst::Model::DBIC::Schema/;
614 schema_class => 'Some::DBIC::Schema',
615 connect_info => ['dbi:SQLite:foo.db', '', '', {AutoCommit=>1}];
619 and that's it! Now C<Some::DBIC::Schema> is part of your
620 Cat app as C<MyApp::Model::DB>.
622 =head2 DBIx::Class as a Catalyst Model
624 See L<Catalyst::Model::DBIC::Schema>.
628 Unlike SOAP, XMLRPC is a very simple (and imo elegant) web-services
629 protocol, exchanging small XML messages like these:
634 TE: deflate,gzip;q=0.3
635 Connection: TE, close
639 User-Agent: SOAP::Lite/Perl/0.60
641 Content-Type: text/xml
643 <?xml version="1.0" encoding="UTF-8"?>
645 <methodName>add</methodName>
647 <param><value><int>1</int></value></param>
648 <param><value><int>2</int></value></param>
655 Date: Tue, 20 Dec 2005 07:45:55 GMT
657 Content-Type: text/xml
661 <?xml version="1.0" encoding="us-ascii"?>
664 <param><value><int>3</int></value></param>
668 Now follow these few steps to implement the application:
670 1. Install Catalyst (5.61 or later), Catalyst::Plugin::XMLRPC (0.06 or
671 later) and SOAP::Lite (for XMLRPCsh.pl).
673 2. Create an application framework:
679 3. Add the XMLRPC plugin to MyApp.pm
681 use Catalyst qw/-Debug Static::Simple XMLRPC/;
683 4. Add an API controller
685 % ./script/myapp_create.pl controller API
687 5. Add a XMLRPC redispatch method and an add method with Remote
688 attribute to lib/MyApp/Controller/API.pm
690 sub default : Private {
691 my ( $self, $c ) = @_;
696 my ( $self, $c, $a, $b ) = @_;
700 The default action is the entry point for each XMLRPC request. It will
701 redispatch every request to methods with Remote attribute in the same
704 The C<add> method is not a traditional action; it has no private or
705 public path. Only the XMLRPC dispatcher knows it exists.
707 6. That's it! You have built your first web service. Let's test it with
708 XMLRPCsh.pl (part of SOAP::Lite):
710 % ./script/myapp_server.pl
712 % XMLRPCsh.pl http://127.0.0.1:3000/api
713 Usage: method[(parameters)]
715 --- XMLRPC RESULT ---
720 Your return data type is usually auto-detected, but you can easily
721 enforce a specific one.
724 my ( $self, $c, $a, $b ) = @_;
725 return RPC::XML::int->new( $a + $b );
732 Views pertain to the display of your application. As with models,
733 catalyst is uncommonly flexible. The recipes below are just a start.
735 =head2 Catalyst::View::TT
737 One of the first things you probably want to do when starting a new
738 Catalyst application is set up your View. Catalyst doesn't care how you
739 display your data; you can choose to generate HTML, PDF files, or plain
742 Most Catalyst applications use a template system to generate their HTML,
743 and though there are several template systems available, Template
744 Toolkit is probably the most popular.
746 Once again, the Catalyst developers have done all the hard work, and
747 made things easy for the rest of us. Catalyst::View::TT provides the
748 interface to Template Toolkit, and provides Helpers which let us set it
749 up that much more easily.
751 =head3 Creating your View
753 Catalyst::View::TT provides two different helpers for us to use: TT and
758 Create a basic Template Toolkit View using the provided helper script:
760 script/myapp_create.pl view TT TT
762 This will create lib/MyApp/View/MyView.pm, which is going to be pretty
763 empty to start. However, it sets everything up that you need to get
764 started. You can now define which template you want and forward to your
768 my ( $self, $c ) = @_;
770 $c->stash->{template} = 'hello.tt';
772 $c->forward( $c->view('TT') );
775 In practice you wouldn't do the forwarding manually, but would
776 use L<Catalyst::Action::RenderView>.
780 Although the TT helper does create a functional, working view, you may
781 find yourself having to create the same template files and changing the
782 same options every time you create a new application. The TTSite helper
783 saves us even more time by creating the basic templates and setting some
784 common options for us.
786 Once again, you can use the helper script:
788 script/myapp_create.pl view TT TTSite
790 This time, the helper sets several options for us in the generated View.
792 __PACKAGE__->config({
793 CATALYST_VAR => 'Catalyst',
795 MyApp->path_to( 'root', 'src' ),
796 MyApp->path_to( 'root', 'lib' )
798 PRE_PROCESS => 'config/main',
799 WRAPPER => 'site/wrapper',
800 ERROR => 'error.tt2',
808 INCLUDE_PATH defines the directories that Template Toolkit should search
809 for the template files.
813 PRE_PROCESS is used to process configuration options which are common to
818 WRAPPER is a file which is processed with each template, usually used to
819 easily provide a common header and footer for every page.
823 In addition to setting these options, the TTSite helper also created the
824 template and config files for us! In the 'root' directory, you'll notice
825 two new directories: src and lib.
827 Several configuration files in root/lib/config are called by PRE_PROCESS.
829 The files in root/lib/site are the site-wide templates, called by
830 WRAPPER, and display the html framework, control the layout, and provide
831 the templates for the header and footer of your page. Using the template
832 organization provided makes it much easier to standardize pages and make
833 changes when they are (inevitably) needed.
835 The template files that you will create for your application will go
836 into root/src, and you don't need to worry about putting the the <html>
837 or <head> sections; just put in the content. The WRAPPER will the rest
838 of the page around your template for you.
843 Of course, having the template system include the header and footer for
844 you isn't all that we want our templates to do. We need to be able to
845 put data into our templates, and have it appear where and how we want
846 it, right? That's where the stash comes in.
848 In our controllers, we can add data to the stash, and then access it
849 from the template. For instance:
852 my ( $self, $c ) = @_;
854 $c->stash->{name} = 'Adam';
856 $c->stash->{template} = 'hello.tt';
858 $c->forward( $c->view('TT') );
863 <strong>Hello, [% name %]!</strong>
865 When you view this page, it will display "Hello, Adam!"
867 All of the information in your stash is available, by its name/key, in
868 your templates. And your data don't have to be plain, old, boring
869 scalars. You can pass array references and hash references, too.
874 my ( $self, $c ) = @_;
876 $c->stash->{names} = [ 'Adam', 'Dave', 'John' ];
878 $c->stash->{template} = 'hello.tt';
880 $c->forward( $c->view('TT') );
885 [% FOREACH name IN names %]
886 <strong>Hello, [% name %]!</strong><br />
889 This allowed us to loop through each item in the arrayref, and display a
890 line for each name that we have.
892 This is the most basic usage, but Template Toolkit is quite powerful,
893 and allows you to truly keep your presentation logic separate from the
894 rest of your application.
898 One of my favorite things about Catalyst is the ability to move an
899 application around without having to worry that everything is going to
900 break. One of the areas that used to be a problem was with the http
901 links in your template files. For example, suppose you have an
902 application installed at http://www.domain.com/Calendar. The links point
903 to "/Calendar", "/Calendar/2005", "/Calendar/2005/10", etc. If you move
904 the application to be at http://www.mydomain.com/Tools/Calendar, then
905 all of those links will suddenly break.
907 That's where $c->uri_for() comes in. This function will merge its
908 parameters with either the base location for the app, or its current
909 namespace. Let's take a look at a couple of examples.
911 In your template, you can use the following:
913 <a href="[% c.uri_for('/login') %]">Login Here</a>
915 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.
919 <a href="[% c.uri_for('2005','10', '24') %]">October, 24 2005</a>
921 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.
923 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.
927 L<http://search.cpan.org/perldoc?Catalyst>
929 L<http://search.cpan.org/perldoc?Catalyst%3A%3AView%3A%3ATT>
931 L<http://search.cpan.org/perldoc?Template>
933 =head2 Adding RSS feeds
935 Adding RSS feeds to your Catalyst applications is simple. We'll see two
936 different aproaches here, but the basic premise is that you forward to
937 the normal view action first to get the objects, then handle the output
940 =head3 Using TT templates
942 This is the aproach used in Agave (L<http://dev.rawmode.org/>).
947 $c->stash->{template}='rss.tt';
950 Then you need a template. Here's the one from Agave:
952 <?xml version="1.0" encoding="UTF-8"?>
953 <rss version="2.0" xmlns:dc="http://purl.org/dc/elements/1.1/">
955 <title>[ [% blog.name || c.config.name || "Agave" %] ] RSS Feed</title>
956 <link>[% base %]</link>
957 <description>Recent posts</description>
958 <language>en-us</language>
960 [% WHILE (post = posts.next) %]
962 <title>[% post.title %]</title>
963 <description>[% post.formatted_teaser|html%]</description>
964 <pubDate>[% post.pub_date %]</pubDate>
965 <guid>[% post.full_uri %]</guid>
966 <link>[% post.full_uri %]</link>
967 <dc:creator>[% post.author.screenname %]</dc:creator>
973 =head3 Using XML::Feed
975 A more robust solution is to use XML::Feed, as was done in the Catalyst
976 Advent Calendar. Assuming we have a C<view> action that populates
977 'entries' with some DBIx::Class iterator, the code would look something
982 $c->forward('view'); # get the entries
984 my $feed = XML::Feed->new('RSS');
985 $feed->title( $c->config->{name} . ' RSS Feed' );
986 $feed->link( $c->req->base ); # link to the site.
987 $feed->description('Catalyst advent calendar'); Some description
989 # Process the entries
990 while( my $entry = $c->stash->{entries}->next ) {
991 my $feed_entry = XML::Feed::Entry->new('RSS');
992 $feed_entry->title($entry->title);
993 $feed_entry->link( $c->uri_for($entry->link) );
994 $feed_entry->issued( DateTime->from_epoch(epoch => $entry->created) );
995 $feed->add_entry($feed_entry);
997 $c->res->body( $feed->as_xml );
1000 A little more code in the controller, but with this approach you're
1001 pretty sure to get something that validates.
1003 Note that for both of the above aproaches, you'll need to set the
1004 content type like this:
1006 $c->res->content_type('application/rss+xml');
1010 You could generalize the second variant easily by replacing 'RSS' with a
1011 variable, so you can generate Atom feeds with the same code.
1013 Now, go ahead and make RSS feeds for all your stuff. The world *needs*
1014 updates on your goldfish!
1016 =head2 Forcing the browser to download content
1018 Sometimes you need your application to send content for download. For
1019 example, you can generate a comma-separated values (CSV) file for your
1020 users to download and import into their spreadsheet program.
1022 Let's say you have an C<Orders> controller which generates a CSV file
1023 in the C<export> action (i.e., C<http://localhost:3000/orders/export>):
1025 sub export : Local Args(0) {
1026 my ( $self, $c ) = @_;
1028 # In a real application, you'd generate this from the database
1029 my $csv = "1,5.99\n2,29.99\n3,3.99\n";
1031 $c->res->content_type('text/comma-separated-values');
1032 $c->res->body($csv);
1035 Normally the browser uses the last part of the URI to generate a
1036 filename for data it cannot display. In this case your browser would
1037 likely ask you to save a file named C<export>.
1039 Luckily you can have the browser download the content with a specific
1040 filename by setting the C<Content-Disposition> header:
1042 my $filename = 'Important Orders.csv';
1043 $c->res->header('Content-Disposition', qq[attachment; filename="$filename"]);
1045 Note the use of quotes around the filename; this ensures that any
1046 spaces in the filename are handled by the browser.
1048 Put this right before calling C<< $c->res->body >> and your browser
1049 will download a file named C<Important Orders.csv> instead of
1052 You can also use this to have the browser download content which it
1053 normally displays, such as JPEG images or even HTML. Just be sure to
1054 set the appropriate content type and disposition.
1059 Controllers are the main point of communication between the web server
1060 and your application. Here we explore some aspects of how they work.
1062 =head2 Extending RenderView (formerly DefaultEnd)
1064 The recommended approach for an C<end> action is to use
1065 L<Catalyst::Action::RenderView> (taking the place of
1066 L<Catalyst::Plugin::DefaultEnd>), which does what you usually need.
1067 However there are times when you need to add a bit to it, but don't want
1068 to write your own C<end> action.
1070 You can extend it like this:
1072 To add something to an C<end> action that is called before rendering
1073 (this is likely to be what you want), simply place it in the C<end>
1076 sub end : ActionClass('RenderView') {
1077 my ( $self, $c ) = @_;
1078 # do stuff here; the RenderView action is called afterwards
1081 To add things to an C<end> action that are called I<after> rendering,
1082 you can set it up like this:
1084 sub render : ActionClass('RenderView') { }
1087 my ( $self, $c ) = @_;
1088 $c->forward('render');
1096 A Catalyst application is driven by one or more Controller modules. There are
1097 a number of ways that Catalyst can decide which of the methods in your
1098 controller modules it should call. Controller methods are also called actions,
1099 because they determine how your catalyst application should (re-)act to any
1100 given URL. When the application is started up, catalyst looks at all your
1101 actions, and decides which URLs they map to.
1103 =head3 Type attributes
1105 Each action is a normal method in your controller, except that it has an
1106 L<attribute|http://search.cpan.org/~nwclark/perl-5.8.7/lib/attributes.pm>
1107 attached. These can be one of several types.
1109 Assume our Controller module starts with the following package declaration:
1111 package MyApp::Controller::Buckets;
1113 and we are running our application on localhost, port 3000 (the test
1120 A Path attribute also takes an argument, this can be either a relative
1121 or an absolute path. A relative path will be relative to the controller
1122 namespace, an absolute path will represent an exact matching URL.
1124 sub my_handles : Path('handles') { .. }
1128 http://localhost:3000/buckets/handles
1132 sub my_handles : Path('/handles') { .. }
1136 http://localhost:3000/handles
1140 When using a Local attribute, no parameters are needed, instead, the name of
1141 the action is matched in the URL. The namespaces created by the name of the
1142 controller package is always part of the URL.
1144 sub my_handles : Local { .. }
1148 http://localhost:3000/buckets/my_handles
1152 A Global attribute is similar to a Local attribute, except that the namespace
1153 of the controller is ignored, and matching starts at root.
1155 sub my_handles : Global { .. }
1159 http://localhost:3000/my_handles
1163 By now you should have figured that a Regex attribute is just what it sounds
1164 like. This one takes a regular expression, and matches starting from
1165 root. These differ from the rest as they can match multiple URLs.
1167 sub my_handles : Regex('^handles') { .. }
1171 http://localhost:3000/handles
1175 http://localhost:3000/handles_and_other_parts
1181 A LocalRegex is similar to a Regex, except it only matches below the current
1182 controller namespace.
1184 sub my_handles : LocalRegex(^handles') { .. }
1188 http://localhost:3000/buckets/handles
1192 http://localhost:3000/buckets/handles_and_other_parts
1198 Last but not least, there is the Private attribute, which allows you to create
1199 your own internal actions, which can be forwarded to, but won't be matched as
1202 sub my_handles : Private { .. }
1204 becomes nothing at all..
1206 Catalyst also predefines some special Private actions, which you can override,
1213 The default action will be called, if no other matching action is found. If
1214 you don't have one of these in your namespace, or any sub part of your
1215 namespace, you'll get an error page instead. If you want to find out where it
1216 was the user was trying to go, you can look in the request object using
1217 C<< $c->req->path >>.
1219 sub default : Private { .. }
1221 works for all unknown URLs, in this controller namespace, or every one if put
1222 directly into MyApp.pm.
1226 The index action is called when someone tries to visit the exact namespace of
1227 your controller. If index, default and matching Path actions are defined, then
1228 index will be used instead of default and Path.
1230 sub index : Private { .. }
1234 http://localhost:3000/buckets
1238 The begin action is called at the beginning of every request involving this
1239 namespace directly, before other matching actions are called. It can be used
1240 to set up variables/data for this particular part of your app. A single begin
1241 action is called, its always the one most relevant to the current namespace.
1243 sub begin : Private { .. }
1247 http://localhost:3000/bucket/(anything)?
1253 Like begin, this action is always called for the namespace it is in, after
1254 every other action has finished. It is commonly used to forward processing to
1255 the View component. A single end action is called, its always the one most
1256 relevant to the current namespace.
1259 sub end : Private { .. }
1261 is called once after any actions when
1263 http://localhost:3000/bucket/(anything)?
1269 Lastly, the auto action is magic in that B<every> auto action in
1270 the chain of paths up to and including the ending namespace, will be
1271 called. (In contrast, only one of the begin/end/default actions will be
1272 called, the relevant one).
1275 sub auto : Private { .. }
1279 sub auto : Private { .. }
1281 will both be called when visiting
1283 http://localhost:3000/bucket/(anything)?
1289 =head3 A word of warning
1291 Due to possible namespace conflicts with Plugins, it is advised to only put the
1292 pre-defined Private actions in your main MyApp.pm file, all others should go
1293 in a Controller module.
1295 =head3 More Information
1297 L<http://search.cpan.org/author/SRI/Catalyst-5.61/lib/Catalyst/Manual/Intro.pod>
1299 L<http://dev.catalyst.perl.org/wiki/FlowChart>
1301 =head2 Component-based Subrequests
1303 See L<Catalyst::Plugin::SubRequest>.
1307 =head3 Single file upload with Catalyst
1309 To implement uploads in Catalyst, you need to have a HTML form similar to
1312 <form action="/upload" method="post" enctype="multipart/form-data">
1313 <input type="hidden" name="form_submit" value="yes">
1314 <input type="file" name="my_file">
1315 <input type="submit" value="Send">
1318 It's very important not to forget C<enctype="multipart/form-data"> in
1321 Catalyst Controller module 'upload' action:
1323 sub upload : Global {
1324 my ($self, $c) = @_;
1326 if ( $c->request->parameters->{form_submit} eq 'yes' ) {
1328 if ( my $upload = $c->request->upload('my_file') ) {
1330 my $filename = $upload->filename;
1331 my $target = "/tmp/upload/$filename";
1333 unless ( $upload->link_to($target) || $upload->copy_to($target) ) {
1334 die( "Failed to copy '$filename' to '$target': $!" );
1339 $c->stash->{template} = 'file_upload.html';
1342 =head3 Multiple file upload with Catalyst
1344 Code for uploading multiple files from one form needs a few changes:
1346 The form should have this basic structure:
1348 <form action="/upload" method="post" enctype="multipart/form-data">
1349 <input type="hidden" name="form_submit" value="yes">
1350 <input type="file" name="file1" size="50"><br>
1351 <input type="file" name="file2" size="50"><br>
1352 <input type="file" name="file3" size="50"><br>
1353 <input type="submit" value="Send">
1356 And in the controller:
1358 sub upload : Local {
1359 my ($self, $c) = @_;
1361 if ( $c->request->parameters->{form_submit} eq 'yes' ) {
1363 for my $field ( $c->req->upload ) {
1365 my $upload = $c->req->upload($field);
1366 my $filename = $upload->filename;
1367 my $target = "/tmp/upload/$filename";
1369 unless ( $upload->link_to($target) || $upload->copy_to($target) ) {
1370 die( "Failed to copy '$filename' to '$target': $!" );
1375 $c->stash->{template} = 'file_upload.html';
1378 C<for my $field ($c-E<gt>req->upload)> loops automatically over all file
1379 input fields and gets input names. After that is basic file saving code,
1380 just like in single file upload.
1382 Notice: C<die>ing might not be what you want to do, when an error
1383 occurs, but it works as an example. A better idea would be to store
1384 error C<$!> in $c->stash->{error} and show a custom error template
1385 displaying this message.
1387 For more information about uploads and usable methods look at
1388 L<Catalyst::Request::Upload> and L<Catalyst::Request>.
1390 =head2 Forwarding with arguments
1392 Sometimes you want to pass along arguments when forwarding to another
1393 action. As of version 5.30, arguments can be passed in the call to
1394 C<forward>; in earlier versions, you can manually set the arguments in
1395 the Catalyst Request object:
1397 # version 5.30 and later:
1398 $c->forward('/wherever', [qw/arg1 arg2 arg3/]);
1401 $c->req->args([qw/arg1 arg2 arg3/]);
1402 $c->forward('/wherever');
1404 (See the L<Catalyst::Manual::Intro> Flow_Control section for more
1405 information on passing arguments via C<forward>.)
1410 The recipes below describe aspects of the deployment process,
1411 including web server engines and tips to improve application efficiency.
1413 =head2 mod_perl Deployment
1415 mod_perl is the best solution for many applications, but we'll list some pros
1416 and cons so you can decide for yourself. The other production deployment
1417 option is FastCGI, for which see below.
1423 mod_perl is very fast and your app will benefit from being loaded in memory
1424 within each Apache process.
1426 =head4 Shared memory for multiple apps
1428 If you need to run several Catalyst apps on the same server, mod_perl will
1429 share the memory for common modules.
1435 Since your application is fully loaded in memory, every Apache process will
1436 be rather large. This means a large Apache process will be tied up while
1437 serving static files, large files, or dealing with slow clients. For this
1438 reason, it is best to run a two-tiered web architecture with a lightweight
1439 frontend server passing dynamic requests to a large backend mod_perl
1444 Any changes made to the core code of your app require a full Apache restart.
1445 Catalyst does not support Apache::Reload or StatINC. This is another good
1446 reason to run a frontend web server where you can set up an
1447 C<ErrorDocument 502> page to report that your app is down for maintenance.
1449 =head4 Cannot run multiple versions of the same app
1451 It is not possible to run two different versions of the same application in
1452 the same Apache instance because the namespaces will collide.
1456 Now that we have that out of the way, let's talk about setting up mod_perl
1457 to run a Catalyst app.
1459 =head4 1. Install Catalyst::Engine::Apache
1461 You should install the latest versions of both Catalyst and
1462 Catalyst::Engine::Apache. The Apache engines were separated from the
1463 Catalyst core in version 5.50 to allow for updates to the engine without
1464 requiring a new Catalyst release.
1466 =head4 2. Install Apache with mod_perl
1468 Both Apache 1.3 and Apache 2 are supported, although Apache 2 is highly
1469 recommended. With Apache 2, make sure you are using the prefork MPM and not
1470 the worker MPM. The reason for this is that many Perl modules are not
1471 thread-safe and may have problems running within the threaded worker
1472 environment. Catalyst is thread-safe however, so if you know what you're
1473 doing, you may be able to run using worker.
1475 In Debian, the following commands should get you going.
1477 apt-get install apache2-mpm-prefork
1478 apt-get install libapache2-mod-perl2
1480 =head4 3. Configure your application
1482 Every Catalyst application will automagically become a mod_perl handler
1483 when run within mod_perl. This makes the configuration extremely easy.
1484 Here is a basic Apache 2 configuration.
1486 PerlSwitches -I/var/www/MyApp/lib
1491 PerlResponseHandler MyApp
1494 The most important line here is C<PerlModule MyApp>. This causes mod_perl
1495 to preload your entire application into shared memory, including all of your
1496 controller, model, and view classes and configuration. If you have -Debug
1497 mode enabled, you will see the startup output scroll by when you first
1500 For an example Apache 1.3 configuration, please see the documentation for
1501 L<Catalyst::Engine::Apache::MP13>.
1505 That's it, your app is now a full-fledged mod_perl application! Try it out
1506 by going to http://your.server.com/.
1508 =head3 Other Options
1510 =head4 Non-root location
1512 You may not always want to run your app at the root of your server or virtual
1513 host. In this case, it's a simple change to run at any non-root location
1518 PerlResponseHandler MyApp
1521 When running this way, it is best to make use of the C<uri_for> method in
1522 Catalyst for constructing correct links.
1524 =head4 Static file handling
1526 Static files can be served directly by Apache for a performance boost.
1528 DocumentRoot /var/www/MyApp/root
1530 SetHandler default-handler
1533 This will let all files within root/static be handled directly by Apache. In
1534 a two-tiered setup, the frontend server should handle static files.
1535 The configuration to do this on the frontend will vary.
1537 =head2 Catalyst on shared hosting
1539 So, you want to put your Catalyst app out there for the whole world to
1540 see, but you don't want to break the bank. There is an answer - if you
1541 can get shared hosting with FastCGI and a shell, you can install your
1542 Catalyst app in a local directory on your shared host. First, run
1544 perl -MCPAN -e shell
1546 and go through the standard CPAN configuration process. Then exit out
1547 without installing anything. Next, open your .bashrc and add
1549 export PATH=$HOME/local/bin:$HOME/local/script:$PATH
1550 perlversion=`perl -v | grep 'built for' | awk '{print $4}' | sed -e 's/v//;'`
1551 export PERL5LIB=$HOME/local/share/perl/$perlversion:$HOME/local/lib/perl/$perlversion:$HOME/local/lib:$PERL5LIB
1553 and log out, then back in again (or run C<". .bashrc"> if you
1554 prefer). Finally, edit C<.cpan/CPAN/MyConfig.pm> and add
1556 'make_install_arg' => qq[SITEPREFIX=$ENV{HOME}/local],
1557 'makepl_arg' => qq[INSTALLDIRS=site install_base=$ENV{HOME}/local],
1559 Now you can install the modules you need using CPAN as normal; they
1560 will be installed into your local directory, and perl will pick them
1561 up. Finally, change directory into the root of your virtual host and
1562 symlink your application's script directory in:
1564 cd path/to/mydomain.com
1565 ln -s ~/lib/MyApp/script script
1567 And add the following lines to your .htaccess file (assuming the server
1568 is setup to handle .pl as fcgi - you may need to rename the script to
1569 myapp_fastcgi.fcgi and/or use a SetHandler directive):
1572 RewriteCond %{REQUEST_URI} !^/?script/myapp_fastcgi.pl
1573 RewriteRule ^(.*)$ script/myapp_fastcgi.pl/$1 [PT,L]
1575 Now C<http://mydomain.com/> should now Just Work. Congratulations, now
1576 you can tell your friends about your new website (or in our case, tell
1577 the client it's time to pay the invoice :) )
1579 =head2 FastCGI Deployment
1581 FastCGI is a high-performance extension to CGI. It is suitable
1582 for production environments.
1588 FastCGI performs equally as well as mod_perl. Don't let the 'CGI' fool you;
1589 your app runs as multiple persistent processes ready to receive connections
1590 from the web server.
1594 When using external FastCGI servers, your application runs as a standalone
1595 application server. It may be restarted independently from the web server.
1596 This allows for a more robust environment and faster reload times when
1597 pushing new app changes. The frontend server can even be configured to
1598 display a friendly "down for maintenance" page while the application is
1601 =head4 Load-balancing
1603 You can launch your application on multiple backend servers and allow the
1604 frontend web server to load-balance between all of them. And of course, if
1605 one goes down, your app continues to run fine.
1607 =head4 Multiple versions of the same app
1609 Each FastCGI application is a separate process, so you can run different
1610 versions of the same app on a single server.
1612 =head4 Can run with threaded Apache
1614 Since your app is not running inside of Apache, the faster mpm_worker module
1615 can be used without worrying about the thread safety of your application.
1619 =head4 More complex environment
1621 With FastCGI, there are more things to monitor and more processes running
1622 than when using mod_perl.
1626 =head4 1. Install Apache with mod_fastcgi
1628 mod_fastcgi for Apache is a third party module, and can be found at
1629 L<http://www.fastcgi.com/>. It is also packaged in many distributions,
1630 for example, libapache2-mod-fastcgi in Debian.
1632 =head4 2. Configure your application
1634 # Serve static content directly
1635 DocumentRoot /var/www/MyApp/root
1636 Alias /static /var/www/MyApp/root/static
1638 FastCgiServer /var/www/MyApp/script/myapp_fastcgi.pl -processes 3
1639 Alias /myapp/ /var/www/MyApp/script/myapp_fastcgi.pl/
1641 # Or, run at the root
1642 Alias / /var/www/MyApp/script/myapp_fastcgi.pl/
1644 The above commands will launch 3 app processes and make the app available at
1647 =head3 Standalone server mode
1649 While not as easy as the previous method, running your app as an external
1650 server gives you much more flexibility.
1652 First, launch your app as a standalone server listening on a socket.
1654 script/myapp_fastcgi.pl -l /tmp/myapp.socket -n 5 -p /tmp/myapp.pid -d
1656 You can also listen on a TCP port if your web server is not on the same
1659 script/myapp_fastcgi.pl -l :8080 -n 5 -p /tmp/myapp.pid -d
1661 You will probably want to write an init script to handle starting/stopping
1662 of the app using the pid file.
1664 Now, we simply configure Apache to connect to the running server.
1666 # 502 is a Bad Gateway error, and will occur if the backend server is down
1667 # This allows us to display a friendly static page that says "down for
1669 Alias /_errors /var/www/MyApp/root/error-pages
1670 ErrorDocument 502 /_errors/502.html
1672 FastCgiExternalServer /tmp/myapp -socket /tmp/myapp.socket
1673 Alias /myapp/ /tmp/myapp/
1675 # Or, run at the root
1680 L<Catalyst::Engine::FastCGI>.
1682 =head2 Development server deployment
1684 The development server is a mini web server written in perl. If you
1685 expect a low number of hits or you don't need mod_perl/FastCGI speed,
1686 you could use the development server as the application server with a
1687 lightweight proxy web server at the front. However, be aware that
1688 there are known issues, especially with Internet Explorer. Many of
1689 these issues can be dealt with by running the server with the -k
1690 (keepalive) option but be aware for more complex applications this may
1691 not be suitable. Consider using Catalyst::Engine::HTTP::POE. This
1692 recipe is easily adapted for POE as well.
1696 As this is an application server setup, the pros are the same as
1697 FastCGI (with the exception of speed).
1702 The development server is what you create your code on, so if it works
1703 here, it should work in production!
1709 Not as fast as mod_perl or FastCGI. Needs to fork for each request
1710 that comes in - make sure static files are served by the web server to
1715 =head4 Start up the development server
1717 script/myapp_server.pl -p 8080 -k -f -pidfile=/tmp/myapp.pid -daemon
1719 You will probably want to write an init script to handle stop/starting
1720 the app using the pid file.
1722 =head4 Configuring Apache
1724 Make sure mod_proxy is enabled and add:
1726 # Serve static content directly
1727 DocumentRoot /var/www/MyApp/root
1728 Alias /static /var/www/MyApp/root/static
1735 ProxyPass / http://localhost:8080/
1736 ProxyPassReverse / http://localhost:8080/
1738 You can wrap the above within a VirtualHost container if you want
1739 different apps served on the same host.
1741 =head2 Quick deployment: Building PAR Packages
1743 You have an application running on your development box, but then you
1744 have to quickly move it to another one for
1745 demonstration/deployment/testing...
1747 PAR packages can save you from a lot of trouble here. They are usual Zip
1748 files that contain a blib tree; you can even include all prereqs and a
1749 perl interpreter by setting a few flags!
1751 =head3 Follow these few points to try it out!
1753 1. Install Catalyst and PAR 0.89 (or later)
1755 % perl -MCPAN -e 'install Catalyst'
1757 % perl -MCPAN -e 'install PAR'
1760 2. Create a application
1766 Recent versions of Catalyst (5.62 and up) include
1767 L<Module::Install::Catalyst>, which simplifies the process greatly. From the shell in your application directory:
1772 Congratulations! Your package "myapp.par" is ready, the following
1773 steps are just optional.
1775 3. Test your PAR package with "parl" (no typo)
1779 [parl] myapp[.par] [script] [arguments]
1782 parl myapp.par myapp_server.pl -r
1792 % parl myapp.par myapp_server.pl
1793 You can connect to your server at http://localhost:3000
1795 Yes, this nifty little starter application gets automatically included.
1796 You can also use "catalyst_par_script('myapp_server.pl')" to set a
1797 default script to execute.
1799 6. Want to create a binary that includes the Perl interpreter?
1801 % pp -o myapp myapp.par
1802 % ./myapp myapp_server.pl
1803 You can connect to your server at http://localhost:3000
1805 =head2 Serving static content
1807 Serving static content in Catalyst used to be somewhat tricky; the use
1808 of L<Catalyst::Plugin::Static::Simple> makes everything much easier.
1809 This plugin will automatically serve your static content during development,
1810 but allows you to easily switch to Apache (or other server) in a
1811 production environment.
1813 =head3 Introduction to Static::Simple
1815 Static::Simple is a plugin that will help to serve static content for your
1816 application. By default, it will serve most types of files, excluding some
1817 standard Template Toolkit extensions, out of your B<root> file directory. All
1818 files are served by path, so if B<images/me.jpg> is requested, then
1819 B<root/images/me.jpg> is found and served.
1823 Using the plugin is as simple as setting your use line in MyApp.pm to include:
1825 use Catalyst qw/Static::Simple/;
1827 and already files will be served.
1831 Static content is best served from a single directory within your root
1832 directory. Having many different directories such as C<root/css> and
1833 C<root/images> requires more code to manage, because you must separately
1834 identify each static directory--if you decide to add a C<root/js>
1835 directory, you'll need to change your code to account for it. In
1836 contrast, keeping all static directories as subdirectories of a main
1837 C<root/static> directory makes things much easier to manage. Here's an
1838 example of a typical root directory structure:
1842 root/controller/stuff.tt
1845 root/static/css/main.css
1846 root/static/images/logo.jpg
1847 root/static/js/code.js
1850 All static content lives under C<root/static>, with everything else being
1851 Template Toolkit files.
1857 You may of course want to change the default locations, and make
1858 Static::Simple look somewhere else, this is as easy as:
1860 MyApp->config->{static}->{include_path} = [
1861 MyApp->config->{root},
1865 When you override include_path, it will not automatically append the
1866 normal root path, so you need to add it yourself if you still want
1867 it. These will be searched in order given, and the first matching file
1870 =item Static directories
1872 If you want to force some directories to be only static, you can set
1873 them using paths relative to the root dir, or regular expressions:
1875 MyApp->config->{static}->{dirs} = [
1880 =item File extensions
1882 By default, the following extensions are not served (that is, they will
1883 be processed by Catalyst): B<tmpl, tt, tt2, html, xhtml>. This list can
1886 MyApp->config->{static}->{ignore_extensions} = [
1887 qw/tmpl tt tt2 html xhtml/
1890 =item Ignoring directories
1892 Entire directories can be ignored. If used with include_path,
1893 directories relative to the include_path dirs will also be ignored:
1895 MyApp->config->{static}->{ignore_dirs} = [ qw/tmpl css/ ];
1899 =head3 More information
1901 L<http://search.cpan.org/dist/Catalyst-Plugin-Static-Simple/>
1903 =head3 Serving manually with the Static plugin with HTTP::Daemon (myapp_server.pl)
1905 In some situations you might want to control things more directly,
1906 using L<Catalyst::Plugin::Static>.
1908 In your main application class (MyApp.pm), load the plugin:
1910 use Catalyst qw/-Debug FormValidator Static OtherPlugin/;
1912 You will also need to make sure your end method does I<not> forward
1913 static content to the view, perhaps like this:
1916 my ( $self, $c ) = @_;
1918 $c->forward( 'MyApp::View::TT' )
1919 unless ( $c->res->body || !$c->stash->{template} );
1922 This code will only forward to the view if a template has been
1923 previously defined by a controller and if there is not already data in
1924 C<$c-E<gt>res-E<gt>body>.
1926 Next, create a controller to handle requests for the /static path. Use
1927 the Helper to save time. This command will create a stub controller as
1928 C<lib/MyApp/Controller/Static.pm>.
1930 $ script/myapp_create.pl controller Static
1932 Edit the file and add the following methods:
1934 # serve all files under /static as static files
1935 sub default : Path('/static') {
1936 my ( $self, $c ) = @_;
1938 # Optional, allow the browser to cache the content
1939 $c->res->headers->header( 'Cache-Control' => 'max-age=86400' );
1941 $c->serve_static; # from Catalyst::Plugin::Static
1944 # also handle requests for /favicon.ico
1945 sub favicon : Path('/favicon.ico') {
1946 my ( $self, $c ) = @_;
1951 You can also define a different icon for the browser to use instead of
1952 favicon.ico by using this in your HTML header:
1954 <link rel="icon" href="/static/myapp.ico" type="image/x-icon" />
1956 =head3 Common problems with the Static plugin
1958 The Static plugin makes use of the C<shared-mime-info> package to
1959 automatically determine MIME types. This package is notoriously
1960 difficult to install, especially on win32 and OS X. For OS X the easiest
1961 path might be to install Fink, then use C<apt-get install
1962 shared-mime-info>. Restart the server, and everything should be fine.
1964 Make sure you are using the latest version (>= 0.16) for best
1965 results. If you are having errors serving CSS files, or if they get
1966 served as text/plain instead of text/css, you may have an outdated
1967 shared-mime-info version. You may also wish to simply use the following
1968 code in your Static controller:
1970 if ($c->req->path =~ /css$/i) {
1971 $c->serve_static( "text/css" );
1976 =head3 Serving Static Files with Apache
1978 When using Apache, you can bypass Catalyst and any Static
1979 plugins/controllers controller by intercepting requests for the
1980 C<root/static> path at the server level. All that is required is to
1981 define a DocumentRoot and add a separate Location block for your static
1982 content. Here is a complete config for this application under mod_perl
1986 use lib qw(/var/www/MyApp/lib);
1991 ServerName myapp.example.com
1992 DocumentRoot /var/www/MyApp/root
1994 SetHandler perl-script
1997 <LocationMatch "/(static|favicon.ico)">
1998 SetHandler default-handler
2002 And here's a simpler example that'll get you started:
2004 Alias /static/ "/my/static/files/"
2005 <Location "/static">
2011 Catalyst makes it easy to employ several different types of caching to
2012 speed up your applications.
2014 =head3 Cache Plugins
2016 There are three wrapper plugins around common CPAN cache modules:
2017 Cache::FastMmap, Cache::FileCache, and Cache::Memcached. These can be
2018 used to cache the result of slow operations.
2020 This very page you're viewing makes use of the FileCache plugin to cache the
2021 rendered XHTML version of the source POD document. This is an ideal
2022 application for a cache because the source document changes infrequently but
2023 may be viewed many times.
2025 use Catalyst qw/Cache::FileCache/;
2030 sub render_pod : Local {
2031 my ( self, $c ) = @_;
2033 # the cache is keyed on the filename and the modification time
2034 # to check for updates to the file.
2035 my $file = $c->path_to( 'root', '2005', '11.pod' );
2036 my $mtime = ( stat $file )->mtime;
2038 my $cached_pod = $c->cache->get("$file $mtime");
2039 if ( !$cached_pod ) {
2040 $cached_pod = do_slow_pod_rendering();
2041 # cache the result for 12 hours
2042 $c->cache->set( "$file $mtime", $cached_pod, '12h' );
2044 $c->stash->{pod} = $cached_pod;
2047 We could actually cache the result forever, but using a value such as 12 hours
2048 allows old entries to be automatically expired when they are no longer needed.
2052 Another method of caching is to cache the entire HTML page. While this is
2053 traditionally handled by a front-end proxy server like Squid, the Catalyst
2054 PageCache plugin makes it trivial to cache the entire output from
2055 frequently-used or slow actions.
2057 Many sites have a busy content-filled front page that might look something
2058 like this. It probably takes a while to process, and will do the exact same
2059 thing for every single user who views the page.
2061 sub front_page : Path('/') {
2062 my ( $self, $c ) = @_;
2064 $c->forward( 'get_news_articles' );
2065 $c->forward( 'build_lots_of_boxes' );
2066 $c->forward( 'more_slow_stuff' );
2068 $c->stash->{template} = 'index.tt';
2071 We can add the PageCache plugin to speed things up.
2073 use Catalyst qw/Cache::FileCache PageCache/;
2075 sub front_page : Path ('/') {
2076 my ( $self, $c ) = @_;
2078 $c->cache_page( 300 );
2080 # same processing as above
2083 Now the entire output of the front page, from <html> to </html>, will be
2084 cached for 5 minutes. After 5 minutes, the next request will rebuild the
2085 page and it will be re-cached.
2087 Note that the page cache is keyed on the page URI plus all parameters, so
2088 requests for / and /?foo=bar will result in different cache items. Also,
2089 only GET requests will be cached by the plugin.
2091 You can even get that front-end Squid proxy to help out by enabling HTTP
2092 headers for the cached page.
2094 MyApp->config->{page_cache}->{set_http_headers} = 1;
2096 This would now set the following headers so proxies and browsers may cache
2097 the content themselves.
2099 Cache-Control: max-age=($expire_time - time)
2100 Expires: $expire_time
2101 Last-Modified: $cache_created_time
2103 =head3 Template Caching
2105 Template Toolkit provides support for caching compiled versions of your
2106 templates. To enable this in Catalyst, use the following configuration.
2107 TT will cache compiled templates keyed on the file mtime, so changes will
2108 still be automatically detected.
2110 package MyApp::View::TT;
2114 use base 'Catalyst::View::TT';
2116 __PACKAGE__->config(
2117 COMPILE_DIR => '/tmp/template_cache',
2124 See the documentation for each cache plugin for more details and other
2125 available configuration options.
2127 L<Catalyst::Plugin::Cache::FastMmap>
2128 L<Catalyst::Plugin::Cache::FileCache>
2129 L<Catalyst::Plugin::Cache::Memcached>
2130 L<Catalyst::Plugin::PageCache>
2131 L<http://search.cpan.org/dist/Template-Toolkit/lib/Template/Manual/Config.pod#Caching_and_Compiling_Options>
2135 Testing is an integral part of the web application development
2136 process. Tests make multi developer teams easier to coordinate, and
2137 they help ensure that there are no nasty surprises after upgrades or
2142 Catalyst provides a convenient way of testing your application during
2143 development and before deployment in a real environment.
2145 C<Catalyst::Test> makes it possible to run the same tests both locally
2146 (without an external daemon) and against a remote server via HTTP.
2150 Let's examine a skeleton application's C<t/> directory:
2152 mundus:~/MyApp chansen$ ls -l t/
2154 -rw-r--r-- 1 chansen chansen 95 18 Dec 20:50 01app.t
2155 -rw-r--r-- 1 chansen chansen 190 18 Dec 20:50 02pod.t
2156 -rw-r--r-- 1 chansen chansen 213 18 Dec 20:50 03podcoverage.t
2162 Verifies that the application loads, compiles, and returns a successful
2167 Verifies that all POD is free from errors. Only executed if the C<TEST_POD>
2168 environment variable is true.
2170 =item C<03podcoverage.t>
2172 Verifies that all methods/functions have POD coverage. Only executed if the
2173 C<TEST_POD> environment variable is true.
2177 =head3 Creating tests
2179 mundus:~/MyApp chansen$ cat t/01app.t | perl -ne 'printf( "%2d %s", $., $_ )'
2180 1 use Test::More tests => 2;
2181 2 use_ok( Catalyst::Test, 'MyApp' );
2183 4 ok( request('/')->is_success );
2185 The first line declares how many tests we are going to run, in this case
2186 two. The second line tests and loads our application in test mode. The
2187 fourth line verifies that our application returns a successful response.
2189 C<Catalyst::Test> exports two functions, C<request> and C<get>. Each can
2190 take three different arguments:
2194 =item A string which is a relative or absolute URI.
2196 request('/my/path');
2197 request('http://www.host.com/my/path');
2199 =item An instance of C<URI>.
2201 request( URI->new('http://www.host.com/my/path') );
2203 =item An instance of C<HTTP::Request>.
2205 request( HTTP::Request->new( GET => 'http://www.host.com/my/path') );
2209 C<request> returns an instance of C<HTTP::Response> and C<get> returns the
2210 content (body) of the response.
2212 =head3 Running tests locally
2214 mundus:~/MyApp chansen$ CATALYST_DEBUG=0 TEST_POD=1 prove --lib lib/ t/
2215 t/01app............ok
2216 t/02pod............ok
2217 t/03podcoverage....ok
2218 All tests successful.
2219 Files=3, Tests=4, 2 wallclock secs ( 1.60 cusr + 0.36 csys = 1.96 CPU)
2221 C<CATALYST_DEBUG=0> ensures that debugging is off; if it's enabled you
2222 will see debug logs between tests.
2224 C<TEST_POD=1> enables POD checking and coverage.
2226 C<prove> A command-line tool that makes it easy to run tests. You can
2227 find out more about it from the links below.
2229 =head3 Running tests remotely
2231 mundus:~/MyApp chansen$ CATALYST_SERVER=http://localhost:3000/ prove --lib lib/ t/01app.t
2233 All tests successful.
2234 Files=1, Tests=2, 0 wallclock secs ( 0.40 cusr + 0.01 csys = 0.41 CPU)
2236 C<CATALYST_SERVER=http://localhost:3000/> is the absolute deployment URI of
2237 your application. In C<CGI> or C<FastCGI> it should be the host and path
2240 =head3 C<Test::WWW::Mechanize> and Catalyst
2242 Be sure to check out C<Test::WWW::Mechanize::Catalyst>. It makes it easy to
2243 test HTML, forms and links. A short example of usage:
2245 use Test::More tests => 6;
2246 use_ok( Test::WWW::Mechanize::Catalyst, 'MyApp' );
2248 my $mech = Test::WWW::Mechanize::Catalyst->new;
2249 $mech->get_ok("http://localhost/", 'Got index page');
2250 $mech->title_like( qr/^MyApp on Catalyst/, 'Got right index title' );
2251 ok( $mech->find_link( text_regex => qr/^Wiki/i ), 'Found link to Wiki' );
2252 ok( $mech->find_link( text_regex => qr/^Mailing-List/i ), 'Found link to Mailing-List' );
2253 ok( $mech->find_link( text_regex => qr/^IRC channel/i ), 'Found link to IRC channel' );
2255 =head3 Further Reading
2259 =item Catalyst::Test
2261 L<http://search.cpan.org/dist/Catalyst/lib/Catalyst/Test.pm>
2263 =item Test::WWW::Mechanize::Catalyst
2265 L<http://search.cpan.org/dist/Test-WWW-Mechanize-Catalyst/lib/Test/WWW/Mechanize/Catalyst.pm>
2267 =item Test::WWW::Mechanize
2269 L<http://search.cpan.org/dist/Test-WWW-Mechanize/Mechanize.pm>
2271 =item WWW::Mechanize
2273 L<http://search.cpan.org/dist/WWW-Mechanize/lib/WWW/Mechanize.pm>
2275 =item LWP::UserAgent
2277 L<http://search.cpan.org/dist/libwww-perl/lib/LWP/UserAgent.pm>
2281 L<http://search.cpan.org/dist/libwww-perl/lib/HTML/Form.pm>
2285 L<http://search.cpan.org/dist/libwww-perl/lib/HTTP/Message.pm>
2289 L<http://search.cpan.org/dist/libwww-perl/lib/HTTP/Request.pm>
2291 =item HTTP::Request::Common
2293 L<http://search.cpan.org/dist/libwww-perl/lib/HTTP/Request/Common.pm>
2295 =item HTTP::Response
2297 L<http://search.cpan.org/dist/libwww-perl/lib/HTTP/Response.pm>
2301 L<http://search.cpan.org/dist/libwww-perl/lib/HTTP/Status.pm>
2305 L<http://search.cpan.org/dist/URI/URI.pm>
2309 L<http://search.cpan.org/dist/Test-Simple/lib/Test/More.pm>
2313 L<http://search.cpan.org/dist/Test-Pod/Pod.pm>
2315 =item Test::Pod::Coverage
2317 L<http://search.cpan.org/dist/Test-Pod-Coverage/Coverage.pm>
2319 =item prove (Test::Harness)
2321 L<http://search.cpan.org/dist/Test-Harness/bin/prove>
2325 =head3 More Information
2327 L<http://search.cpan.org/perldoc?Catalyst::Plugin::Authorization::Roles>
2328 L<http://search.cpan.org/perldoc?Catalyst::Plugin::Authorization::ACL>
2332 Sebastian Riedel C<sri@oook.de>
2334 Danijel Milicevic C<me@danijel.de>
2336 Viljo Marrandi C<vilts@yahoo.com>
2338 Marcus Ramberg C<mramberg@cpan.org>
2340 Jesse Sheidlower C<jester@panix.com>
2342 Andy Grundman C<andy@hybridized.org>
2344 Chisel Wright C<pause@herlpacker.co.uk>
2346 Will Hawes C<info@whawes.co.uk>
2348 Gavin Henry C<ghenry@perl.me.uk>
2350 Kieren Diment C<kd@totaldatasolution.com>
2354 This document is free, you can redistribute it and/or modify it
2355 under the same terms as Perl itself.