3 Catalyst::Manual::Intro - Introduction to Catalyst
7 This is a brief overview of why and how to use Catalyst. It explains how Catalyst works and shows how to quickly get a simple application up and running.
9 =head2 What is Catalyst?
11 Catalyst is an elegant web application framework, extremely flexible yet extremely simple. It's similar to Ruby on Rails, Spring (Java) and L<Maypole>, upon which it was originally based.
15 Catalyst follows the Model-View-Controller (MVC) design pattern, allowing you to easily separate concerns, like content, presentation and flow control, into separate modules. This separation allows you to modify code that handles one concern without affecting code that handles the others. Catalyst promotes re-use of existing Perl modules that already handle common web application concerns well.
17 Here's how the M, V and C map to those concerns, with examples of well-known Perl modules you may want to use for each.
23 Access and modify content (data). L<Class::DBI>, L<Plucene>, L<Net::LDAP>...
27 Present content to the user. L<Template Toolkit|Template>, L<Mason|HTML::Mason>...
31 Control the whole request phase, check parameters, dispatch actions, flow control. Catalyst!
35 If you're unfamiliar with MVC and design patterns, you may want to check out the original book on the subject, I<Design Patterns>, by Gamma, Helm, Johson and Vlissides, a.k.a. the Gang of Four (GoF). Or just search the web. Many, many web application frameworks follow MVC, including all those listed above.
39 Catalyst is much more flexible than many other frameworks.
43 =item * B<Multiple Models, Views and Controllers>
45 To build a Catalyst application, you handle each type of concern inside special modules called L</Components>. Often this code will be very simple, just calling out to Perl modules like those listed above under L</MVC>. Catalyst is very flexible about these Components. Use as many Models, Views and Controllers as you like, using as many different Perl modules as you like, all in the same application. Want to manipulate multiple databases, plus retrieve some data via LDAP? No problem. Want to present data from the same Model using L<Template Toolkit|Template> and L<PDF::Template>? Easy.
47 =item * B<Re-Useable Components>
49 Not only does Catalyst promote the re-use of already-existing Perl modules, it also allows you to re-use your Catalyst components in multiple Catalyst applications.
51 =item * B<Unrestrained URL-to-Action Dispatching>
53 Catalyst allows you to dispatch any URLs to any application L<Actions>, even via regular expressions! Unlike some other frameworks, it doesn't require mod_rewrite or class and method names in URLs.
55 With Catalyst you register your actions and address them directly. For example:
57 MyApp->action( 'hello' => sub {
58 my ( $self, $context ) = @_;
59 $context->response->output('Hello World!');
62 Now http://localhost:3000/hello prints "Hello World!".
64 =item * B<Support for CGI, mod_perl, Apache::Request>
66 Use L<Catalyst::Engine::Apache> or L<Catalyst::Engine::CGI>.
72 The best part is that Catalyst implements all this flexibility in a very simple way.
74 =item * B<Building Block Interface>
76 Components interoperate very smoothly. For example, Catalyst automatically makes a L<Context> object available in every component. Via the context, you can access the request object, share data between components, and control the flow of your application. Building a Catalyst application feels a lot like snapping together toy building blocks, and everything just works.
78 =item * B<Component Auto-Discovery>
80 No need to C<use> all of your components. Catalyst automatically finds and loads them.
82 =item * B<Pre-Built Components for Popular Modules>
84 See L<Catalyst::Model::CDBI> for L<Class::DBI>, or L<Catalyst::View::TT> for L<Template Toolkit|Template>. You can even get an instant web database front end with L<Catalyst::Model::CDBI::CRUD>.
86 =item * B<Builtin Test Framework>
88 Catalyst comes with a builtin, lightweight http server and test framework, making it easy to test applications from the command line.
90 =item * B<Helper Scripts>
92 Catalyst provides helper scripts to quickly generate running starter code for components and unit tests.
96 Here's how to install Catalyst and get a simple application up and running, using the helper scripts described above.
100 $ perl -MCPAN -e 'install Bundle::Catalyst'
104 $ catalyst.pl My::App
106 $ script/create.pl controller My::Controller
112 Now visit these locations with your favorite browser or user agent to see Catalyst in action:
116 =item http://localhost:3000/
118 =item http://localhost:3000/my_controller/
126 Let's see how Catalyst works, by taking a closer look at the components and other parts of a Catalyst application.
128 =head3 Application Class
130 In addition to the Model, View and Controller components, there's a single class that represents your application itself. This is where you configure your application, load plugins, define application-wide actions and extend Catalyst.
135 use Catalyst qw/-Debug/;
138 name => 'My Application',
139 root => '/home/joeuser/myapp/root',
141 # You can put whatever you want in here:
142 # my_param_name => $my_param_value,
145 MyApp->action( '!default' => sub {
146 my ( $self, $context ) = @_;
147 $context->response->output('Catalyst rockz!');
152 For most applications, Catalyst requires you to define only two config parameters:
158 Name of your application.
162 Path to additional files like templates, images or other static data.
166 However, you can define as many parameters as you want for plugins or whatever you need. You can access them anywhere in your application via C<$context-E<gt>config-E<gt>{$param_name}>.
170 Catalyst automatically blesses a Context object into your application class and makes it available everywhere in your application. Use the Context to directly interact with Catalyst and glue your L<Components> together.
172 As illustrated earlier in our URL-to-Action dispatching example, the Context is always the second method parameter, behind the Component object reference or class name itself. Previously we called it C<$context> for clarity, but most Catalyst developers just call it C<$c>:
174 MyApp->action( 'hello' => sub {
175 my ( $self, $c ) = @_;
176 $c->res->output('Hello World!');
179 The Context contains several important objects:
183 =item * L<Catalyst::Request>
188 The request contains all kinds of request-specific information, like query parameters, cookies, uploads, headers and more.
190 $c->req->params->{foo};
191 $c->req->cookies->{sessionid};
192 $c->req->headers->content_type;
195 =item * L<Catalyst::Response>
200 The response is like the request, but contains just response-specific information.
202 $c->res->output('Hello World');
203 $c->res->status(404);
204 $c->res->redirect('http://oook.de');
206 =item * L<Catalyst::Config>
213 =item * L<Catalyst::Log>
217 $c->log->debug('Something happened');
218 $c->log->info('Something you should know');
224 $c->stash->{foo} = 'bar';
228 The last of these, the stash, is a universal hash for sharing data among application components. For an example, we return to our 'hello' action:
233 my ( $self, $c ) = @_;
234 $c->stash->{message} = 'Hello World!';
235 $c->forward('!show-message');
238 '!show-message' => sub {
239 my ( $self, $c ) = @_;
240 $c->res->output( $c->stash->{message} );
247 To define a Catalyst action, register it into your application with the C<action> method. C<action> accepts a key-value pair, where the key represents one or more URLs or application states and the value is a code reference, the action to execute in reponse to the URL(s) or application state(s).
249 Catalyst supports several ways to define Actions:
255 MyApp->action( 'foo/bar' => sub { } );
257 Matches only http://localhost:3000/foo/bar.
261 MyApp->action( '/^foo(\d+)/bar(\d+)$/' => sub { } );
263 Matches any URL that matches the pattern in the action key, e.g. http://localhost:3000/foo23/bar42. The pattern must be enclosed with forward slashes, i.e. '/$pattern/'.
265 If you use capturing parantheses to extract values within the matching URL (23, 42 in the above example), those values are available in the $c->req->snippets array. If you want to pass arguments at the end of your URL, you must use regex action keys. See L</URL Argument Handling> below.
267 =item * B<Namespace-Prefixed>
269 package MyApp::Controller::My::Controller;
270 MyApp->action( '?foo' => sub { } );
272 Matches http://localhost:3000/my_controller/foo. The action key must be prefixed with '?'.
274 Prefixing the action key with '?' indicates that the matching URL must be prefixed with a modified form of the component's class (package) name. This modified class name excludes the parts that have a pre-defined meaning in Catalyst ("MyApp::Controller" in the above example), replaces "::" with "_" and converts the name to lower case. See L</Components> for a full explanation of the pre-defined meaning of Catalyst component class names.
278 MyApp->action( '!foo' => sub { } );
280 Matches no URL, and cannot be executed by requesting a URL that corresponds to the action key. Private actions can be executed only inside a Catalyst application, by calling the C<forward> method:
284 See L</Flow Control> for a full explanation of C<forward>.
288 =head4 Builtin Private Actions
290 In response to specific application states, Catalyst will automatically call these built in private actions:
296 Called when no other action matches.
300 Called at the beginning of a request, before any matching actions are called.
306 Called at the end of a request, after all matching actions are called.
308 =head4 B<Namespace-Prefixed Private Actions>
310 MyApp->action( '!?foo' => sub { } );
311 MyApp->action( '!?default' => sub { } );
313 The leading '!?' indicates that these are namespace-prefixed private actions. These override any application-wide private actions with the same names, and can be called only from within the namespace in which they are defined. Any private action can be namespace-prefixed, including the builtins. One use for this might be to give a Controller its own !?default, !?begin and !?end.
315 =head4 B<URL Argument Handling>
317 If you want to pass variable arguments at the end of a URL, you must use regex actions keys with '^' and '$' anchors, and the arguments must be separated with forward slashes (/) in the URL. For example, suppose you want to handle /foo/$bar/$baz, where $bar and $baz may vary:
319 MyApp->action( '/^foo$/' => sub { my ($self, $context, $bar, $baz) = @_; } );
321 But what if you also defined actions for /foo/boo and /foo/boo/hoo ?
323 MyApp->action( '/foo/boo' => sub { .. } );
324 MyApp->action( '/foo/boo/hoo' => sub { .. } );
326 Catalyst matches actions in most specific to least specific order:
330 /foo # might be /foo/bar/baz
332 So Catalyst would never mistakenly dispatch the first two URLs to the '/^foo$/' action.
336 Control the application flow with the C<forward> method, which accepts the key of an action to execute.
341 my ( $self, $c ) = @_;
342 $c->stash->{message} = 'Hello World!';
343 $c->forward('!check-message');
346 '!check-message' => sub {
347 my ( $self, $c ) = @_;
348 return unless $c->stash->{message};
349 $c->forward('!show-message');
352 '!show-message' => sub {
353 my ( $self, $c ) = @_;
354 $c->res->output( $c->stash->{message} );
359 You can also forward to classes and methods.
364 my ( $self, $c ) = @_;
365 $c->forward(qw/MyApp::M::Hello say_hello/);
369 my ( $self, $c ) = @_;
370 $c->forward('MyApp::M::Hello');
375 package MyApp::M::Hello;
378 my ( $self, $c ) = @_;
379 $c->res->output('Hello World!');
383 my ( $self, $c ) = @_;
384 $c->res->output('Goodbye World!');
387 Note that C<forward> returns after processing.
388 Catalyst will automatically try to call process() if you omit the method.
392 Again, Catalyst has an uncommonly flexible component system. You can define as many L<Models>, L<Views> and L<Controllers> as you like.
394 All components must inherit from L<Catalyst::Base>, which provides a simple class structure and some common class methods like C<config> and C<new> (constructor).
396 package MyApp::Controller::MyController;
399 use base 'Catalyst::Base';
401 __PACKAGE__->config( foo => 'bar' );
405 You don't have to C<use> or otherwise register Models, Views and Controllers. Catalyst automatically discovers and instantiates them, at startup. All you need to do is put them in directories named for each Component type. Notice that you can use some very terse aliases for each one.
409 =item * B<MyApp/Model/>
413 =item * B<MyApp/View/>
417 =item * B<MyApp/Controller/>
425 To show how to define views, we'll use an already-existing base class for the L<Template Toolkit|Template>, L<Catalyst::View::TT>. All we need to do is inherit from this class:
427 package MyApp::V::TT;
430 use base 'Catalyst::View::TT';
434 This gives us a process() method and we can now just do $c->forward('MyApp::V::TT') to render our templates. The base class makes process() implicit, so we don't have to say C<$c-E<gt>forward(qw/MyApp::V::TT process/)>.
439 my ( $self, $c ) = @_;
440 $c->stash->{template} = 'hello.tt';
444 my ( $self, $c ) = @_;
445 $c->forward('MyApp::View::TT');
450 You normally render templates at the end of a request, so it's a perfect use for the !end action.
452 Also, be sure to put the template under the directory specified in C<$c-E<gt>config->{root}>, or you'll be forced to look at our eyecandy debug screen. ;)
456 To show how to define models, again we'll use an already-existing base class, this time for L<Class::DBI>: L<Catalyst::Model::CDBI>.
458 But first, we need a database.
462 id INTEGER PRIMARY KEY,
467 id INTEGER PRIMARY KEY,
468 foo INTEGER REFERENCES foo,
472 INSERT INTO foo (data) VALUES ('TEST!');
475 % sqlite /tmp/myapp.db < myapp.sql
477 Now we can create a CDBI component for this database.
479 package MyApp::M::CDBI;
482 use base 'Catalyst::Model::CDBI';
485 dsn => 'dbi:SQLite:/tmp/myapp.db',
491 Catalyst automatically loads table layouts and relationships. Use the stash to pass data to your templates.
496 use Catalyst '-Debug';
499 name => 'My Application',
500 root => '/home/joeuser/myapp/root'
506 my ( $self, $c ) = @_;
507 $c->stash->{template} ||= 'index.tt';
508 $c->forward('MyApp::V::TT');
512 my ( $self, $c, $id ) = @_;
513 $c->stash->{item} = MyApp::M::CDBI::Foo->retrieve($id);
520 The id is [% item.data %]
524 Multiple Controllers are a good way to separate logical domains of your application.
526 package MyApp::C::Login;
529 '?sign-in' => sub { },
530 '?new-password' => sub { },
531 '?sign-out' => sub { },
534 package MyApp::C::Catalog;
541 package MyApp::C::Cart;
545 '?update' => sub { },
551 Catalyst has a built in http server for testing! (Later, you can easily use a more powerful server, e.g. Apache/mod_perl, in a production environment).
553 Start your application on the command line...
559 perl -I/home/joeuser/myapp/lib -MCatalyst::Test=MyApp -e1 3000
561 ...then visit http://localhost:3000/ in a browser to view the output.
563 You can also do it all from the command line:
565 script/test.pl http://localhost/
569 perl -I/home/joeuser/myapp/lib -MCatalyst::Test=MyApp -e1 http://localhost/
577 Join #catalyst on irc.perl.org.
581 http://lists.rawmode.org/mailman/listinfo/catalyst
582 http://lists.rawmode.org/mailman/listinfo/catalyst-dev
586 Sebastian Riedel, C<sri@oook.de> and David Naughton, C<naughton@umn.edu>
590 This program is free software, you can redistribute it and/or modify it under
591 the same terms as Perl itself.