3 Catalyst::Manual::Intro - Introduction to Catalyst
7 This is a brief introduction to Catalyst. It explains the most important
8 features of how Catalyst works and shows how to get a simple application
9 up and running quickly. For an introduction (without code) to Catalyst
10 itself, and why you should be using it, see L<Catalyst::Manual::About>.
12 =head2 What is Catalyst?
14 Catalyst is an elegant web application framework, extremely flexible yet
15 extremely simple. It's similar to Ruby on Rails, Spring (Java), and
16 L<Maypole>, upon which it was originally based.
20 Catalyst follows the Model-View-Controller (MVC) design pattern,
21 allowing you to easily separate concerns, like content, presentation,
22 and flow control, into separate modules. This separation allows you to
23 modify code that handles one concern without affecting code that handles
24 the others. Catalyst promotes the re-use of existing Perl modules that
25 already handle common web application concerns well.
27 Here's how the M, V, and C map to those concerns, with examples of
28 well-known Perl modules you may want to use for each.
34 Access and modify content (data). L<DBIx::Class>, L<Class::DBI>,
35 L<Plucene>, L<Net::LDAP>...
39 Present content to the user. L<Template Toolkit|Template>,
40 L<Mason|HTML::Mason>, L<HTML::Template>...
44 Control the whole request phase, check parameters, dispatch actions, flow
45 control. Catalyst itself!
49 If you're unfamiliar with MVC and design patterns, you may want to check
50 out the original book on the subject, I<Design Patterns>, by Gamma,
51 Helm, Johnson, and Vlissides, also known as the Gang of Four (GoF).
52 Many, many web application frameworks are based on MVC, including all
57 Catalyst is much more flexible than many other frameworks. We'll talk
58 more about this later, but rest assured you can use your favorite Perl
59 modules with Catalyst.
63 =item * B<Multiple Models, Views, and Controllers>
65 To build a Catalyst application, you handle each type of concern inside
66 special modules called L</Components>. Often this code will be very
67 simple, just calling out to Perl modules like those listed above under
68 L</MVC>. Catalyst handles these components in a very flexible way. Use
69 as many Models, Views, and Controllers as you like, using as many
70 different Perl modules as you like, all in the same application. Want to
71 manipulate multiple databases, and retrieve some data via LDAP? No
72 problem. Want to present data from the same Model using L<Template
73 Toolkit|Template> and L<PDF::Template>? Easy.
75 =item * B<Reuseable Components>
77 Not only does Catalyst promote the re-use of already existing Perl
78 modules, it also allows you to re-use your Catalyst components in
79 multiple Catalyst applications.
81 =item * B<Unrestrained URL-to-Action Dispatching>
83 Catalyst allows you to dispatch any URLs to any application L</Actions>,
84 even through regular expressions! Unlike most other frameworks, it
85 doesn't require mod_rewrite or class and method names in URLs.
87 With Catalyst you register your actions and address them directly. For
91 my ( $self, $context ) = @_;
92 $context->response->body('Hello World!');
95 Now http://localhost:3000/hello prints "Hello World!".
97 =item * B<Support for CGI, mod_perl, Apache::Request>
99 Use L<Catalyst::Engine::Apache> or L<Catalyst::Engine::CGI>.
105 The best part is that Catalyst implements all this flexibility in a very
110 =item * B<Building Block Interface>
112 Components interoperate very smoothly. For example, Catalyst
113 automatically makes a L</Context> object available to every
114 component. Via the context, you can access the request object, share
115 data between components, and control the flow of your
116 application. Building a Catalyst application feels a lot like snapping
117 together toy building blocks, and everything just works.
119 =item * B<Component Auto-Discovery>
121 No need to C<use> all of your components. Catalyst automatically finds
124 =item * B<Pre-Built Components for Popular Modules>
126 See L<Catalyst::Model::DBIC::Schema> for L<DBIx::Class>, or
127 L<Catalyst::View::TT> for L<Template Toolkit|Template>.
129 =item * B<Built-in Test Framework>
131 Catalyst comes with a built-in, lightweight http server and test
132 framework, making it easy to test applications from the command line.
134 =item * B<Helper Scripts>
136 Catalyst provides helper scripts to quickly generate running starter
137 code for components and unit tests. See L<Catalyst::Helper>.
143 Here's how to install Catalyst and get a simple application up and
144 running, using the helper scripts described above.
148 $ perl -MCPAN -e 'install Task::Catalyst'
155 $ script/myapp_create.pl controller Library::Login
159 $ script/myapp_server.pl
161 Now visit these locations with your favorite browser or user agent to see
166 =item http://localhost:3000/
168 =item http://localhost:3000/library/login/
176 Let's see how Catalyst works, by taking a closer look at the components
177 and other parts of a Catalyst application.
179 =head3 Application Class
181 In addition to the Model, View, and Controller components, there's a
182 single class that represents your application itself. This is where you
183 configure your application, load plugins, define application-wide
184 actions, and extend Catalyst.
189 use Catalyst qw/-Debug/;
192 name => 'My Application',
194 # You can put anything else you want in here:
195 my_configuration_variable => 'something',
198 sub default : Private {
199 my ( $self, $context ) = @_;
200 $context->response->body('Catalyst rocks!');
205 For most applications, Catalyst requires you to define only one config
212 The name of your application.
216 Optionally, you can specify a B<root> parameter for templates and static
217 data. If omitted, Catalyst will try to auto-detect the directory's
218 location. You can define as many parameters as you want for plugins or
219 whatever you need. You can access them anywhere in your application via
220 C<$context-E<gt>config-E<gt>{$param_name}>.
224 Catalyst automatically blesses a Context object into your application
225 class and makes it available everywhere in your application. Use the
226 Context to directly interact with Catalyst and glue your L</Components>
227 together. For example, if you need to use the Context from within a
228 Template Toolkit template, it's already there:
230 <h1>Welcome to [% c.config.name %]!</h1>
232 As illustrated in our URL-to-Action dispatching example, the Context is
233 always the second method parameter, behind the Component object
234 reference or class name itself. Previously we called it C<$context> for
235 clarity, but most Catalyst developers just call it C<$c>:
238 my ( $self, $c ) = @_;
239 $c->res->body('Hello World!');
242 The Context contains several important objects:
246 =item * L<Catalyst::Request>
251 The request object contains all kinds of request-specific information, like
252 query parameters, cookies, uploads, headers, and more.
254 $c->req->params->{foo};
255 $c->req->cookies->{sessionid};
256 $c->req->headers->content_type;
259 =item * L<Catalyst::Response>
264 The response is like the request, but contains just response-specific
267 $c->res->body('Hello World');
268 $c->res->status(404);
269 $c->res->redirect('http://oook.de');
271 =item * L<Catalyst::Config>
277 =item * L<Catalyst::Log>
280 $c->log->debug('Something happened');
281 $c->log->info('Something you should know');
286 $c->stash->{foo} = 'bar';
290 The last of these, the stash, is a universal hash for sharing data among
291 application components. For an example, we return to our 'hello' action:
294 my ( $self, $c ) = @_;
295 $c->stash->{message} = 'Hello World!';
296 $c->forward('show_message');
299 sub show_message : Private {
300 my ( $self, $c ) = @_;
301 $c->res->body( $c->stash->{message} );
304 Note that the stash should be used only for passing data in an
305 individual request cycle; it gets cleared at a new request. If you need
306 to maintain more persistent data, use a session.
310 A Catalyst controller is defined by its actions. An action is a
311 subroutine with a special attribute. You've already seen some examples
312 of actions in this document. The URL (for example
313 http://localhost.3000/foo/bar) consists of two parts, the base
314 (http://localhost:3000/ in this example) and the path (foo/bar). Please
315 note that the trailing slash after the hostname[:port] always belongs to
316 base and not to the action.
318 Catalyst supports several types of actions:
322 =item * B<Literal> (B<Path> actions)
324 package MyApp::Controller::My::Controller;
325 sub bar : Path('foo/bar') { }
327 Literal C<Path> actions will act relative to their current
328 namespace. The above example matches only
329 http://localhost:3000/my/controller/foo/bar. If you start your path with
330 a forward slash, it will match from the root. Example:
332 package MyApp::Controller::My::Controller;
333 sub bar : Path('/foo/bar') { }
335 Matches only http://localhost:3000/foo/bar.
337 package MyApp::Controller::My::Controller;
340 By leaving the C<Path> definition empty, it will match on the namespace
341 root. The above code matches http://localhost:3000/my/controller.
345 sub bar : Regex('^item(\d+)/order(\d+)$') { }
347 Matches any URL that matches the pattern in the action key, e.g.
348 http://localhost:3000/item23/order42. The '' around the regexp is
349 optional, but perltidy likes it. :)
351 Regex matches act globally, i.e. without reference to the namespace from
352 which it is called, so that a C<bar> method in the
353 C<MyApp::Controller::Catalog::Order::Process> namespace won't match any
354 form of C<bar>, C<Catalog>, C<Order>, or C<Process> unless you
355 explicitly put this in the regex. To achieve the above, you should
356 consider using a C<LocalRegex> action.
358 =item * B<LocalRegex>
360 sub bar : LocalRegex('^widget(\d+)$') { }
362 LocalRegex actions act locally. If you were to use C<bar> in
363 C<MyApp::Controller::Catalog>, the above example would match urls like
364 http://localhost:3000/catalog/widget23.
366 If you omit the "C<^>" from your regex, then it will match any depth
367 from the controller and not immediately off of the controller name. The
368 following example differs from the above code in that it will match
369 http://localhost:3000/catalog/foo/widget23 as well.
371 package MyApp::Controller::Catalog;
372 sub bar : LocalRegex('widget(\d+)$') { }
374 For both LocalRegex and Regex actions, if you use capturing parentheses
375 to extract values within the matching URL, those values are available in
376 the C<$c-E<gt>req-E<gt>snippets> array. In the above example, "widget23"
377 would capture "23" in the above example, and
378 C<$c-E<gt>req-E<gt>snippets-E<gt>[0]> would be "23". If you want to pass
379 arguments at the end of your URL, you must use regex action keys. See
380 L</URL Path Handling> below.
382 =item * B<Top-level> (B<Global>)
387 Matches http://localhost:3000/foo. The function name is mapped directly
388 to the application base.
390 =item * B<Namespace-Prefixed> (B<Local>)
392 package MyApp::Controller::My::Controller;
395 Matches http://localhost:3000/my/controller/foo.
397 This action type indicates that the matching URL must be prefixed with a
398 modified form of the component's class (package) name. This modified
399 class name excludes the parts that have a pre-defined meaning in
400 Catalyst ("MyApp::Controller" in the above example), replaces "::" with
401 "/", and converts the name to lower case. See L</Components> for a full
402 explanation of the pre-defined meaning of Catalyst component class
407 sub foo : Private { }
409 Matches no URL, and cannot be executed by requesting a URL that
410 corresponds to the action key. Private actions can be executed only
411 inside a Catalyst application, by calling the C<forward> method:
415 See L</Flow Control> for a full explanation of C<forward>. Note that, as
416 discussed there, when forwarding from another component, you must use
417 the absolute path to the method, so that a private C<bar> method in your
418 C<MyApp::Controller::Catalog::Order::Process> controller must, if called
419 from elsewhere, be reached with
420 C<$c-E<gt>forward('/catalog/order/process/bar')>.
424 B<Note:> After seeing these examples, you probably wonder what the point
425 is of defining names for regex and path actions. Every public action is
426 also a private one, so you have one unified way of addressing components
429 =head4 Built-in Private Actions
431 In response to specific application states, Catalyst will automatically
432 call these built-in private actions in your application class:
436 =item * B<default : Private>
438 Called when no other action matches. Could be used, for example, for
439 displaying a generic frontpage for the main app, or an error page for
440 individual controllers.
442 If C<default> isn't acting how you would expect, look at using a
443 L</Literal> C<Path> action (with an empty path string). The difference is
444 that C<Path> takes arguments relative from the namespace and C<default>
445 I<always> takes arguments relative from the root, regardless of what
448 =item * B<index : Private>
450 C<index> is much like C<default> except that it takes no arguments
451 and it is weighted slightly higher in the matching process. It is
452 useful as a static entry point to a controller, e.g. to have a static
453 welcome page. Note that it's also weighted higher than Path.
455 =item * B<begin : Private>
457 Called at the beginning of a request, before any matching actions are
460 =item * B<end : Private>
462 Called at the end of a request, after all matching actions are called.
466 =head4 Built-in actions in controllers/autochaining
468 Package MyApp::Controller::Foo;
469 sub begin : Private { }
470 sub default : Private { }
471 sub auto : Private { }
473 You can define built-in private actions within your controllers as
474 well. The actions will override the ones in less-specific controllers,
475 or your application class. In other words, for each of the three
476 built-in private actions, only one will be run in any request
477 cycle. Thus, if C<MyApp::Controller::Catalog::begin> exists, it will be
478 run in place of C<MyApp::begin> if you're in the C<catalog> namespace,
479 and C<MyApp::Controller::Catalog::Order::begin> would override this in
482 In addition to the normal built-in actions, you have a special action
483 for making chains, C<auto>. Such C<auto> actions will be run after any
484 C<begin>, but before your action is processed. Unlike the other
485 built-ins, C<auto> actions I<do not> override each other; they will be
486 called in turn, starting with the application class and going through to
487 the I<most> specific class. I<This is the reverse of the order in which
488 the normal built-ins override each other>.
490 Here are some examples of the order in which the various built-ins
495 =item for a request for C</foo/foo>
499 MyApp::Controller::Foo::default # in the absence of MyApp::Controller::Foo::Foo
502 =item for a request for C</foo/bar/foo>
504 MyApp::Controller::Foo::Bar::begin
506 MyApp::Controller::Foo::auto
507 MyApp::Controller::Foo::Bar::auto
508 MyApp::Controller::Foo::Bar::default # for MyApp::Controller::Foo::Bar::foo
509 MyApp::Controller::Foo::Bar::end
513 The C<auto> action is also distinguished by the fact that you can break
514 out of the processing chain by returning 0. If an C<auto> action returns
515 0, any remaining actions will be skipped, except for C<end>. So, for the
516 request above, if the first auto returns false, the chain would look
521 =item for a request for C</foo/bar/foo> where first C<auto> returns
524 MyApp::Controller::Foo::Bar::begin
526 MyApp::Controller::Foo::Bar::end
530 An example of why one might use this is an authentication action: you
531 could set up a C<auto> action to handle authentication in your
532 application class (which will always be called first), and if
533 authentication fails, returning 0 would skip any remaining methods
536 B<Note:> Looking at it another way, C<auto> actions have to return a
537 true value to continue processing! You can also C<die> in the autochain
538 action; in that case, the request will go straight to the finalize
539 stage, without processing further actions.
541 =head4 URL Path Handling
543 You can pass variable arguments as part of the URL path, separated with
544 forward slashes (/). If the action is a Regex or LocalRegex, the '$' anchor
545 must be used. For example, suppose you want to handle C</foo/$bar/$baz>,
546 where C<$bar> and C<$baz> may vary:
548 sub foo : Regex('^foo$') { my ($self, $context, $bar, $baz) = @_; }
550 But what if you also defined actions for C</foo/boo> and C</foo/boo/hoo>?
552 sub boo : Path('foo/boo') { .. }
553 sub hoo : Path('foo/boo/hoo') { .. }
555 Catalyst matches actions in most specific to least specific order:
559 /foo # might be /foo/bar/baz but won't be /foo/boo/hoo
561 So Catalyst would never mistakenly dispatch the first two URLs to the
564 If a Regex or LocalRegex action doesn't use the '$' anchor, the action will
565 still match a URL containing arguments, however the arguments won't be
568 =head4 Parameter Processing
570 Parameters passed in the URL query string are handled with methods in
571 the L<Catalyst::Request> class. The C<param> method is functionally
572 equivalent to the C<param> method of C<CGI.pm> and can be used in
573 modules that require this.
575 # http://localhost:3000/catalog/view/?category=hardware&page=3
576 my $category = $c->req->param('category');
577 my $current_page = $c->req->param('page') || 1;
579 # multiple values for single parameter name
580 my @values = $c->req->param('scrolling_list');
582 # DFV requires a CGI.pm-like input hash
583 my $results = Data::FormValidator->check($c->req->params, \%dfv_profile);
587 You control the application flow with the C<forward> method, which
588 accepts the key of an action to execute. This can be an action in the
589 same or another Catalyst controller, or a Class name, optionally
590 followed by a method name. After a C<forward>, the control flow will
591 return to the method from which the C<forward> was issued.
593 A C<forward> is similar to a method call. The main differences are that
594 it wraps the call in an C<eval> to allow exception handling; it
595 automatically passes along the context object (C<$c> or C<$context>);
596 and it allows profiling of each call (displayed in the log with
600 my ( $self, $c ) = @_;
601 $c->stash->{message} = 'Hello World!';
602 $c->forward('check_message'); # $c is automatically included
605 sub check_message : Private {
606 my ( $self, $c ) = @_;
607 return unless $c->stash->{message};
608 $c->forward('show_message');
611 sub show_message : Private {
612 my ( $self, $c ) = @_;
613 $c->res->body( $c->stash->{message} );
616 A C<forward> does not create a new request, so your request
617 object (C<$c-E<gt>req>) will remain unchanged. This is a
618 key difference between using C<forward> and issuing a
621 You can pass new arguments to a C<forward> by adding them
622 in an anonymous array. In this case C<$c-E<gt>req-E<gt>args>
623 will be changed for the duration of the C<forward> only; upon
624 return, the original value of C<$c-E<gt>req-E<gt>args> will
628 my ( $self, $c ) = @_;
629 $c->stash->{message} = 'Hello World!';
630 $c->forward('check_message',[qw/test1/]);
631 # now $c->req->args is back to what it was before
634 sub check_message : Private {
635 my ( $self, $c ) = @_;
636 my $first_argument = $c->req->args->[0]; # now = 'test1'
640 As you can see from these examples, you can just use the method name as
641 long as you are referring to methods in the same controller. If you want
642 to forward to a method in another controller, or the main application,
643 you will have to refer to the method by absolute path.
645 $c->forward('/my/controller/action');
646 $c->forward('/default'); # calls default in main application
648 Here are some examples of how to forward to classes and methods.
651 my ( $self, $c ) = @_;
652 $c->forward(qw/MyApp::Model::Hello say_hello/);
656 my ( $self, $c ) = @_;
657 $c->forward('MyApp::Model::Hello'); # no method: will try 'process'
660 package MyApp::Model::Hello;
663 my ( $self, $c ) = @_;
664 $c->res->body('Hello World!');
668 my ( $self, $c ) = @_;
669 $c->res->body('Goodbye World!');
672 Note that C<forward> returns to the calling action and continues
673 processing after the action finishes. If you want all further processing
674 in the calling action to stop, use C<detach> instead, which will execute
675 the C<detach>ed action and not return to the calling sub. In both cases,
676 Catalyst will automatically try to call process() if you omit the
681 Catalyst has an uncommonly flexible component system. You can define as
682 many L</Models>, L</Views>, and L</Controllers> as you like.
684 All components must inherit from L<Catalyst::Base>, which provides a
685 simple class structure and some common class methods like C<config> and
686 C<new> (constructor).
688 package MyApp::Controller::Catalog;
691 use base 'Catalyst::Base';
693 __PACKAGE__->config( foo => 'bar' );
697 You don't have to C<use> or otherwise register Models, Views, and
698 Controllers. Catalyst automatically discovers and instantiates them
699 when you call C<setup> in the main application. All you need to do is
700 put them in directories named for each Component type. Notice that you
701 can use some very terse aliases for each one.
705 =item * B<MyApp/Model/>
709 =item * B<MyApp/View/>
713 =item * B<MyApp/Controller/>
721 To show how to define views, we'll use an already-existing base class for the
722 L<Template Toolkit|Template>, L<Catalyst::View::TT>. All we need to do is
723 inherit from this class:
725 package MyApp::View::TT;
728 use base 'Catalyst::View::TT';
732 (You can also generate this automatically by using the helper script:
734 script/myapp_create.pl view TT TT
736 where the first C<TT> tells the script that the name of the view should
737 be C<TT>, and the second that it should be a Template Toolkit view.)
739 This gives us a process() method and we can now just do
740 $c->forward('MyApp::View::TT') to render our templates. The base class
741 makes process() implicit, so we don't have to say
742 C<$c-E<gt>forward(qw/MyApp::View::TT process/)>.
745 my ( $self, $c ) = @_;
746 $c->stash->{template} = 'hello.tt';
750 my ( $self, $c ) = @_;
751 $c->forward('MyApp::View::TT');
754 You normally render templates at the end of a request, so it's a perfect
755 use for the global C<end> action.
757 Also, be sure to put the template under the directory specified in
758 C<$c-E<gt>config-E<gt>{root}>, or you'll be forced to look at our
759 eyecandy debug screen. ;)
763 To show how to define models, again we'll use an already-existing base
764 class, this time for L<DBIx::Class>: L<Catalyst::Model::DBIC::Schema>.
765 We'll also need L<DBIx::Class::Schema::Loader>.
767 But first, we need a database.
771 id INTEGER PRIMARY KEY,
776 id INTEGER PRIMARY KEY,
777 foo INTEGER REFERENCES foo,
781 INSERT INTO foo (data) VALUES ('TEST!');
784 % sqlite /tmp/myapp.db < myapp.sql
786 Now we can create a DBIC::SchemaLoader component for this database.
788 script/myapp_create.pl model DBIC DBIC::SchemaLoader 'dbi:SQLite:/tmp/myapp.db'
790 L<DBIx::Class::Schema::Loader> automatically loads table layouts and
791 relationships. Use the stash to pass data to your templates.
793 We add the following to MyApp/Controller/Root.pm
796 my ( $self, $c, $id ) = @_;
798 $c->stash->{item} = $c->model('DBIC::Foo')->find($id);
804 my ( $self, $c ) = @_;
806 $c->stash->{template} ||= 'index.tt';
807 $c->forward( $c->view('TT') );
810 We then create a new template file "root/index.tt" containing:
812 The Id's data is [% item.data %]
814 Models do not have to be part of your Catalyst application; you
815 can always call an outside module that serves as your Model:
819 my ( $self, $c ) = @_;
821 $c->stash->{template} = 'list.tt';
823 use Some::Outside::DBIC::Module;
824 my @records = Some::Outside::DBIC::Module->search({
828 $c->stash->{records} = \@records;
831 But by using a Model that is part of your Catalyst application, you gain
832 several things: you don't have to C<use> each component, Catalyst will
833 find and load it automatically at compile-time; you can C<forward> to
834 the module, which can only be done to Catalyst components; and only
835 Catalyst components can be fetched with
836 C<$c-E<gt>model('SomeModel')>.
838 Happily, since many people have existing Model classes that they
839 would like to use with Catalyst (or, conversely, they want to
840 write Catalyst models that can be used outside of Catalyst, e.g.
841 in a cron job), it's trivial to write a simple component in
842 Catalyst that slurps in an outside Model:
844 package MyApp::Model::DB;
845 use base qw/Catalyst::Model::DBIC::Schema/;
847 schema_class => 'Some::DBIC::Schema',
848 connect_info => ['dbi:SQLite:foo.db', '', '', {AutoCommit=>1}]
852 and that's it! Now C<Some::DBIC::Schema> is part of your
853 Cat app as C<MyApp::Model::DB>.
857 Multiple controllers are a good way to separate logical domains of your
860 package MyApp::Controller::Login;
862 sub sign-in : Local { }
863 sub new-password : Local { }
864 sub sign-out : Local { }
866 package MyApp::Controller::Catalog;
871 package MyApp::Controller::Cart;
874 sub update : Local { }
875 sub order : Local { }
879 Catalyst has a built-in http server for testing! (Later, you can easily
880 use a more powerful server, e.g. Apache/mod_perl, in a production
883 Start your application on the command line...
885 script/myapp_server.pl
887 ...then visit http://localhost:3000/ in a browser to view the output.
889 You can also do it all from the command line:
891 script/myapp_test.pl http://localhost/
899 Join #catalyst on irc.perl.org.
903 http://lists.rawmode.org/mailman/listinfo/catalyst
904 http://lists.rawmode.org/mailman/listinfo/catalyst-dev
908 Sebastian Riedel, C<sri@oook.de>
909 David Naughton, C<naughton@umn.edu>
910 Marcus Ramberg, C<mramberg@cpan.org>
911 Jesse Sheidlower, C<jester@panix.com>
912 Danijel Milicevic, C<me@danijel.de>
916 This program is free software, you can redistribute it and/or modify it
917 under the same terms as Perl itself.