3 Catalyst::Manual::Intro - Introduction to Catalyst
7 This is a brief overview of why and how to use Catalyst. It explains how
8 Catalyst works and shows how to get a simple application up and running quickly.
10 =head2 What is Catalyst?
12 Catalyst is an elegant web application framework, extremely flexible yet
13 extremely simple. It's similar to Ruby on Rails, Spring (Java) and L<Maypole>,
14 upon which it was originally based.
18 Catalyst follows the Model-View-Controller (MVC) design pattern, allowing you to
19 easily separate concerns, like content, presentation, and flow control, into
20 separate modules. This separation allows you to modify code that handles one
21 concern without affecting code that handles the others. Catalyst promotes the
22 re-use of existing Perl modules that already handle common web application
25 Here's how the M, V, and C map to those concerns, with examples of well-known
26 Perl modules you may want to use for each.
32 Access and modify content (data). L<Class::DBI>, L<Plucene>, L<Net::LDAP>...
36 Present content to the user. L<Template Toolkit|Template>, L<Mason|HTML::Mason>,
41 Control the whole request phase, check parameters, dispatch actions, flow
46 If you're unfamiliar with MVC and design patterns, you may want to check out the
47 original book on the subject, I<Design Patterns>, by Gamma, Helm, Johson and
48 Vlissides, also known as the Gang of Four (GoF). You can also just google it.
49 Many, many web application frameworks are based on MVC, including all those
54 Catalyst is much more flexible than many other frameworks. We'll talk more about
55 this later, but rest assured you can use your favorite Perl modules with
60 =item * B<Multiple Models, Views, and Controllers>
62 To build a Catalyst application, you handle each type of concern inside special
63 modules called L</Components>. Often this code will be very simple, just calling
64 out to Perl modules like those listed above under L</MVC>. Catalyst handles
65 these components in a very flexible way. Use as many Models, Views, and
66 Controllers as you like, using as many different Perl modules as you like, all
67 in the same application. Want to manipulate multiple databases, and retrieve
68 some data via LDAP? No problem. Want to present data from the same Model using
69 L<Template Toolkit|Template> and L<PDF::Template>? Easy.
71 =item * B<Reuseable Components>
73 Not only does Catalyst promote the re-use of already existing Perl modules, it
74 also allows you to re-use your Catalyst components in multiple Catalyst
77 =item * B<Unrestrained URL-to-Action Dispatching>
79 Catalyst allows you to dispatch any URLs to any application L<Actions>, even
80 through regular expressions! Unlike most other frameworks, it doesn't require
81 mod_rewrite or class and method names in URLs.
83 With Catalyst you register your actions and address them directly. For example:
86 my ( $self, $context ) = @_;
87 $context->response->output('Hello World!');
90 Now http://localhost:3000/hello prints "Hello World!".
92 =item * B<Support for CGI, mod_perl, Apache::Request>
94 Use L<Catalyst::Engine::Apache> or L<Catalyst::Engine::CGI>.
100 The best part is that Catalyst implements all this flexibility in a very simple
105 =item * B<Building Block Interface>
107 Components interoperate very smoothly. For example, Catalyst automatically makes
108 a L<Context> object available to every component. Via the context, you can
109 access the request object, share data between components, and control the flow
110 of your application. Building a Catalyst application feels a lot like snapping
111 together toy building blocks, and everything just works.
113 =item * B<Component Auto-Discovery>
115 No need to C<use> all of your components. Catalyst automatically finds and loads
118 =item * B<Pre-Built Components for Popular Modules>
120 See L<Catalyst::Model::CDBI> for L<Class::DBI>, or L<Catalyst::View::TT> for
121 L<Template Toolkit|Template>. You can even get an instant web database front end
122 with L<Catalyst::Model::CDBI::CRUD>.
124 =item * B<Built-in Test Framework>
126 Catalyst comes with a built-in, lightweight http server and test framework,
127 making it easy to test applications from the command line.
129 =item * B<Helper Scripts>
131 Catalyst provides helper scripts to quickly generate running starter code for
132 components and unit tests.
138 Here's how to install Catalyst and get a simple application up and running,
139 using the helper scripts described above.
143 $ perl -MCPAN -e 'install Bundle::Catalyst'
150 $ script/myapp_create.pl controller Library::Login
154 $ script/myapp_server.pl
156 Now visit these locations with your favorite browser or user agent to see
161 =item http://localhost:3000/
163 =item http://localhost:3000/library/login/
171 Let's see how Catalyst works, by taking a closer look at the components and
172 other parts of a Catalyst application.
174 =head3 Application Class
176 In addition to the Model, View, and Controller components, there's a single
177 class that represents your application itself. This is where you configure your
178 application, load plugins, define application-wide actions, and extend Catalyst.
183 use Catalyst qw/-Debug/;
186 name => 'My Application',
187 root => '/home/joeuser/myapp/root',
189 # You can put anything else you want in here:
190 my_configuration_variable => 'something',
193 sub default : Private {
194 my ( $self, $context ) = @_;
195 $context->response->output('Catalyst rockz!');
200 For most applications, Catalyst requires you to define only two config
207 Name of your application.
211 Path to additional files such as templates, images, or other static data.
215 However, you can define as many parameters as you want for plugins or whatever
216 you need. You can access them anywhere in your application via
217 C<$context-E<gt>config-E<gt>{$param_name}>.
221 Catalyst automatically blesses a Context object into your application class and
222 makes it available everywhere in your application. Use the Context to directly
223 interact with Catalyst and glue your L<Components> together. For example, if you
224 need to use the Context from within a Template Toolkit template, it's already
227 <h1>Welcome to [% c.config.name %]!</h1>
229 As illustrated earlier in our URL-to-Action dispatching example, the Context is
230 always the second method parameter, behind the Component object reference or
231 class name itself. Previously we called it C<$context> for clarity, but most
232 Catalyst developers just call it C<$c>:
235 my ( $self, $c ) = @_;
236 $c->res->output('Hello World!');
239 The Context contains several important objects:
243 =item * L<Catalyst::Request>
248 The request object contains all kinds of request-specific information, like
249 query parameters, cookies, uploads, headers, and more.
251 $c->req->params->{foo};
252 $c->req->cookies->{sessionid};
253 $c->req->headers->content_type;
256 =item * L<Catalyst::Response>
261 The response is like the request, but contains just response-specific
264 $c->res->output('Hello World');
265 $c->res->status(404);
266 $c->res->redirect('http://oook.de');
268 =item * L<Catalyst::Config>
275 =item * L<Catalyst::Log>
279 $c->log->debug('Something happened');
280 $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->output( $c->stash->{message} );
304 Note that the stash should be used only for passing data in an individual
305 request cycle; it gets cleared at a new request. If you need to maintain more
306 persistent data, use a session.
310 A Catalyst controller is defined by its actions. An action is a sub with a
311 special attribute. You've already seen some examples of actions in this
312 document. The URL (for example http://localhost.3000/foo/bar) consists of two
313 parts, the base (http://localhost:3000/ in this example) and the path (foo/bar).
314 Please note that the trailing slash after the hostname[:port] always belongs to
315 base and not to the action.
317 Catalyst supports several types of actions:
323 sub bar : Path('foo/bar') { }
325 Matches only http://localhost:3000/foo/bar.
329 sub bar : Regex('^item(\d+)/order(\d+)$') { }
331 Matches any URL that matches the pattern in the action key, e.g.
332 http://localhost:3000/item23/order42. The '' around the regexp is optional, but
333 perltidy likes it. :)
335 Regex matches act globally, i.e. without reference to the namespace from which
336 it is called, so that a C<bar> method in the
337 C<MyApp::Controller::Catalog::Order::Process> namespace won't match any form of
338 C<bar>, C<Catalog>, C<Order>, or C<Process> unless you explicitly put this in
341 If you use capturing parentheses to extract values within the matching URL (23,
342 42 in the above example), those values are available in the $c->req->snippets
343 array. If you want to pass arguments at the end of your URL, you must use regex
344 action keys. See L</URL Argument Handling> below.
351 Matches http://localhost:3000/foo. The function name is mapped directly
352 to the application base.
354 =item * B<Namespace-Prefixed>
356 package MyApp::C::My::Controller;
359 Matches http://localhost:3000/my/controller/foo.
361 This action type indicates that the matching URL must be prefixed with a
362 modified form of the component's class (package) name. This modified class name
363 excludes the parts that have a pre-defined meaning in Catalyst ("MyApp::C" in
364 the above example), replaces "::" with "/", and converts the name to lower case.
365 See L</Components> for a full explanation of the pre-defined meaning of Catalyst
366 component class names.
370 sub foo : Private { }
372 Matches no URL, and cannot be executed by requesting a URL that corresponds to
373 the action key. Private actions can be executed only inside a Catalyst
374 application, by calling the C<forward> method:
378 See L</Flow Control> for a full explanation of C<forward>. Note that, as
379 discussed there, when forwarding from another component, you must use
380 the absolute path to the method, so that a private C<bar> method in your
381 C<MyApp::Controller::Catalog::Order::Process> controller must, if called
382 from elsewhere, be reached with
383 C<$c-E<gt>forward('/catalog/order/process/bar')>.
387 B<Note:> After seeing these examples, you probably wonder what the point
388 is of defining names for regex and path actions. Actually, every public
389 action is also a private one, so you have one unified way of addressing
390 components in your C<forward>s.
392 =head4 Built-in Private Actions
394 In response to specific application states, Catalyst will automatically
395 call these built-in private actions in your application class:
399 =item * B<default : Private>
401 Called when no other action matches. Could be used, for example, for
402 displaying a generic frontpage for the main app, or an error page for
403 individual controllers.
405 =item * B<begin : Private>
407 Called at the beginning of a request, before any matching actions are
410 =item * B<end : Private>
412 Called at the end of a request, after all matching actions are called.
416 =head4 Built-in actions in controllers/autochaining
418 Package MyApp::C::Foo;
419 sub begin : Private { }
420 sub default : Private { }
421 sub auto : Private { }
423 You can define built-in private actions within your controllers as
424 well. The actions will override the ones in less-specific controllers,
425 or your application class. In other words, for each of the three
426 built-in private actions, only one will be run in any request
427 cycle. Thus, if C<MyApp::C::Catalog::begin> exists, it will be run in
428 place of C<MyApp::begin> if you're in the C<catalog> namespace, and
429 C<MyApp::C::Catalog::Order::begin> would override this in turn.
431 In addition to the normal built-in actions, you have a special action
432 for making chains, C<auto>. Such C<auto> actions will be run after any
433 C<begin>, but before your action is processed. Unlike the other
434 built-ins, C<auto> actions I<do not> override each other; they will be
435 called in turn, starting with the application class and going through to
436 the I<most> specific class. I<This is the reverse of the order in which
437 the normal built-ins override each other>.
439 Here are some examples of the order in which the various built-ins
444 =item for a request for C</foo/foo>
448 MyApp::C::Foo::default # in the absence of MyApp::C::Foo::Foo
451 =item for a request for C</foo/bar/foo>
453 MyApp::C::Foo::Bar::begin
456 MyApp::C::Foo::Bar::auto
457 MyApp::C::Foo::Bar::default # for MyApp::C::Foo::Bar::foo
458 MyApp::C::Foo::Bar::end
462 The C<auto> action is also distinguished by the fact that you can break
463 out of the processing chain by returning 0. If an C<auto> action returns
464 0, any remaining actions will be skipped, except for C<end>. So, for the
465 request above, if the first auto returns false, the chain would look
470 =item for a request for C</foo/bar/foo> where first C<auto> returns
473 MyApp::C::Foo::Bar::begin
475 MyApp::C::Foo::Bar::end
479 An example of why one might use this is an authentication action: you
480 could set up a C<auto> action to handle authentication in your
481 application class (which will always be called first), and if
482 authentication fails, returning 0 would skip any remaining methods
485 B<Note:> Looking at it another way, C<auto> actions have to return a
486 true value to continue processing! You can also C<die> in the autochain
487 action; in that case, the request will go straight to the finalize
488 stage, without processing further actions.
490 =head4 URL Path Handling
492 You can pass variable arguments as part of the URL path. In this case,
493 you must use regex action keys with '^' and '$' anchors, and the
494 arguments must be separated with forward slashes (/) in the URL. For
495 example, suppose you want to handle C</foo/$bar/$baz>, where C<$bar> and
498 sub foo : Regex('^foo$') { my ($self, $context, $bar, $baz) = @_; }
500 But what if you also defined actions for C</foo/boo> and C</foo/boo/hoo>?
502 sub boo : Path('foo/boo') { .. }
503 sub hoo : Path('foo/boo/hoo') { .. }
505 Catalyst matches actions in most specific to least specific order:
509 /foo # might be /foo/bar/baz but won't be /foo/boo/hoo
511 So Catalyst would never mistakenly dispatch the first two URLs to the
514 =head4 Parameter Processing
516 Parameters passed in the URL query string are handled with methods in
517 the L<Catalyst::Request> class. The C<param> method is functionally
518 equivalent to the C<param> method of C<CGI.pm> and can be used in
519 modules that require this.
521 # http://localhost:3000/catalog/view/?category=hardware&page=3
522 my $category = $c->req->param('category');
523 my $current_page = $c->req->param('page') || 1;
525 # multiple values for single parameter name
526 my @values = $c->req->param('scrolling_list');
528 # DFV requires a CGI.pm-like input hash
529 my $results = Data::FormValidator->check($c->req->params, \%dfv_profile);
533 You control the application flow with the C<forward> method, which
534 accepts the key of an action to execute. This can be an action in the
535 same or another Catalyst controller, or a Class name, optionally
536 followed by a method name. After a C<forward>, the control flow will
537 return to the method from which the C<forward> was issued.
539 A C<forward> is similar to a method call. The main differences are that
540 it wraps the call in an C<eval> to allow exception handling; it
541 automatically passes along the context object (C<$c> or C<$context>);
542 and it allows profiling of each call (displayed in the log with
546 my ( $self, $c ) = @_;
547 $c->stash->{message} = 'Hello World!';
548 $c->forward('check_message'); # $c is automatically included
551 sub check_message : Private {
552 my ( $self, $c ) = @_;
553 return unless $c->stash->{message};
554 $c->forward('show_message');
557 sub show_message : Private {
558 my ( $self, $c ) = @_;
559 $c->res->output( $c->stash->{message} );
562 A C<forward> does not create a new request, so your request
563 object (C<$c-E<gt>req>) will remain unchanged. This is a
564 key difference between using C<forward> and issuing a
567 You can pass new arguments to a C<forward> by adding them
568 in an anonymous array. In this case C<$c-E<gt>req-E<gt>args>
569 will be changed for the duration of the C<forward> only; upon
570 return, the original value of C<$c-E<gt>req-E<gt>args> will
574 my ( $self, $c ) = @_;
575 $c->stash->{message} = 'Hello World!';
576 $c->forward('check_message',[qw/test1/]);
577 # now $c->req->args is back to what it was before
580 sub check_message : Private {
581 my ( $self, $c ) = @_;
582 my $first_argument = $c->req->args[0]; # now = 'test1'
586 As you can see from these examples, you can just use the method name as
587 long as you are referring to methods in the same controller. If you want
588 to forward to a method in another controller, or the main application,
589 you will have to refer to the method by absolute path.
591 $c->forward('/my/controller/action');
592 $c->forward('/default'); # calls default in main application
594 Here are some examples of how to forward to classes and methods.
597 my ( $self, $c ) = @_;
598 $c->forward(qw/MyApp::M::Hello say_hello/);
602 my ( $self, $c ) = @_;
603 $c->forward('MyApp::M::Hello'); # no method: will try 'process'
606 package MyApp::M::Hello;
609 my ( $self, $c ) = @_;
610 $c->res->output('Hello World!');
614 my ( $self, $c ) = @_;
615 $c->res->output('Goodbye World!');
618 Note that C<forward> returns to the calling action and continues
619 processing after the action finishes. If you want all further processing
620 in the calling action to stop, use C<detach> instead, which will execute
621 the C<detach>ed action and not return to the calling sub. In both cases,
622 Catalyst will automatically try to call process() if you omit the
627 Catalyst has an uncommonly flexible component system. You can define as many
628 L<Models>, L<Views>, and L<Controllers> as you like.
630 All components must inherit from L<Catalyst::Base>, which provides a simple
631 class structure and some common class methods like C<config> and C<new>
634 package MyApp::C::Catalog;
637 use base 'Catalyst::Base';
639 __PACKAGE__->config( foo => 'bar' );
643 You don't have to C<use> or otherwise register Models, Views, and
644 Controllers. Catalyst automatically discovers and instantiates them
645 when you call C<setup> in the main application. All you need to do is
646 put them in directories named for each Component type. Notice that you
647 can use some very terse aliases for each one.
651 =item * B<MyApp/Model/>
655 =item * B<MyApp/View/>
659 =item * B<MyApp/Controller/>
667 To show how to define views, we'll use an already-existing base class for the
668 L<Template Toolkit|Template>, L<Catalyst::View::TT>. All we need to do is
669 inherit from this class:
671 package MyApp::V::TT;
674 use base 'Catalyst::View::TT';
678 (You can also generate this automatically by using the helper script:
680 script/myapp_create.pl view TT TT
682 where the first C<TT> tells the script that the name of the view should
683 be C<TT>, and the second that it should be a Template Toolkit view.)
685 This gives us a process() method and we can now just do
686 $c->forward('MyApp::V::TT') to render our templates. The base class makes
687 process() implicit, so we don't have to say C<$c-E<gt>forward(qw/MyApp::V::TT
691 my ( $self, $c ) = @_;
692 $c->stash->{template} = 'hello.tt';
696 my ( $self, $c ) = @_;
697 $c->forward('MyApp::V::TT');
700 You normally render templates at the end of a request, so it's a perfect
701 use for the global C<end> action.
703 Also, be sure to put the template under the directory specified in
704 C<$c-E<gt>config-E<gt>{root}>, or you'll be forced to look at our
705 eyecandy debug screen. ;)
709 To show how to define models, again we'll use an already-existing base class,
710 this time for L<Class::DBI>: L<Catalyst::Model::CDBI>.
712 But first, we need a database.
716 id INTEGER PRIMARY KEY,
721 id INTEGER PRIMARY KEY,
722 foo INTEGER REFERENCES foo,
726 INSERT INTO foo (data) VALUES ('TEST!');
729 % sqlite /tmp/myapp.db < myapp.sql
731 Now we can create a CDBI component for this database.
733 package MyApp::M::CDBI;
736 use base 'Catalyst::Model::CDBI';
739 dsn => 'dbi:SQLite:/tmp/myapp.db',
745 Catalyst automatically loads table layouts and relationships. Use the stash to
746 pass data to your templates.
751 use Catalyst '-Debug';
754 name => 'My Application',
755 root => '/home/joeuser/myapp/root'
761 my ( $self, $c ) = @_;
762 $c->stash->{template} ||= 'index.tt';
763 $c->forward('MyApp::V::TT');
767 my ( $self, $c, $id ) = @_;
768 $c->stash->{item} = MyApp::M::CDBI::Foo->retrieve($id);
773 # Then, in a TT template:
774 The id is [% item.data %]
776 Models do not have to be part of your Catalyst application; you
777 can always call an outside module that serves as your Model:
781 my ( $self, $c ) = @_;
782 $c->stash->{template} = 'list.tt';
783 use Some::Outside::CDBI::Module;
784 my @records = Some::Outside::CDBI::Module->retrieve_all;
785 $c->stash->{records} = \@records;
788 But by using a Model that is part of your Catalyst application, you gain
789 several things: you don't have to C<use> each component, Catalyst will
790 find and load it automatically at compile-time; you can C<forward> to
791 the module, which can only be done to Catalyst componenents; and only
792 Catalyst components can be fetched with
793 C<$c-E<gt>comp('MyApp::M::SomeModel')>.
795 Happily, since many people have existing Model classes that they
796 would like to use with Catalyst (or, conversely, they want to
797 write Catalyst models that can be used outside of Catalyst, e.g.
798 in a cron job), it's trivial to write a simple component in
799 Catalyst that slurps in an outside Model:
801 package MyApp::M::Catalog;
802 use base qw/Catalyst::Base Some::Other::CDBI::Module::Catalog/;
805 and that's it! Now C<Some::Other::CDBI::Module::Catalog> is part of your
806 Cat app as C<MyApp::M::Catalog>.
810 Multiple controllers are a good way to separate logical domains of your
813 package MyApp::C::Login;
815 sub sign-in : Local { }
816 sub new-password : Local { }
817 sub sign-out : Local { }
819 package MyApp::C::Catalog;
824 package MyApp::C::Cart;
827 sub update : Local { }
828 sub order : Local { }
832 Catalyst has a built-in http server for testing! (Later, you can easily use a
833 more powerful server, e.g. Apache/mod_perl, in a production environment.)
835 Start your application on the command line...
837 script/myapp_server.pl
839 ...then visit http://localhost:3000/ in a browser to view the output.
841 You can also do it all from the command line:
843 script/myapp_test.pl http://localhost/
851 Join #catalyst on irc.perl.org.
855 http://lists.rawmode.org/mailman/listinfo/catalyst
856 http://lists.rawmode.org/mailman/listinfo/catalyst-dev
860 Sebastian Riedel, C<sri@oook.de>
861 David Naughton, C<naughton@umn.edu>
862 Marcus Ramberg, C<mramberg@cpan.org>
863 Jesse Sheidlower, C<jester@panix.com>
864 Danijel Milicevic, C<me@danijel.de>
868 This program is free software, you can redistribute it and/or modify it under
869 the same terms as Perl itself.