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 get a simple application up and running quickly.
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 the 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, also known as the Gang of Four (GoF). You can also just google it. Many, many web application frameworks are based on MVC, including all those listed above.
39 Catalyst is much more flexible than many other frameworks. We'll talk more about this later, but rest assured you can use your favorite Perl modules with Catalyst.
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 handles these components in a very flexible way. 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, and 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<Reuseable 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 through regular expressions! Unlike most 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:
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.
76 =item * B<Building Block Interface>
78 Components interoperate very smoothly. For example, Catalyst automatically makes a L<Context> object available to 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.
80 =item * B<Component Auto-Discovery>
82 No need to C<use> all of your components. Catalyst automatically finds and loads them.
84 =item * B<Pre-Built Components for Popular Modules>
86 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>.
88 =item * B<Built-in Test Framework>
90 Catalyst comes with a built-in, lightweight http server and test framework, making it easy to test applications from the command line.
92 =item * B<Helper Scripts>
94 Catalyst provides helper scripts to quickly generate running starter code for components and unit tests.
100 Here's how to install Catalyst and get a simple application up and running, using the helper scripts described above.
104 $ perl -MCPAN -e 'install Bundle::Catalyst'
110 $ script/create.pl controller My::Controller
116 Now visit these locations with your favorite browser or user agent to see Catalyst in action:
120 =item http://localhost:3000/
122 =item http://localhost:3000/my/controller/
130 Let's see how Catalyst works, by taking a closer look at the components and other parts of a Catalyst application.
132 =head3 Application Class
134 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.
139 use Catalyst qw/-Debug/;
142 name => 'My Application',
143 root => '/home/joeuser/myapp/root',
145 # You can put whatever you want in here:
146 # my_param_name => $my_param_value,
149 sub default : Private {
150 my ( $self, $context ) = @_;
151 $context->response->output('Catalyst rockz!');
156 For most applications, Catalyst requires you to define only two config parameters:
162 Name of your application.
166 Path to additional files such as templates, images, or other static data.
170 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}>.
174 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.
176 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>:
179 my ( $self, $c ) = @_;
180 $c->res->output('Hello World!');
183 The Context contains several important objects:
187 =item * L<Catalyst::Request>
192 The request object contains all kinds of request-specific information, like query parameters, cookies, uploads, headers, and more.
194 $c->req->params->{foo};
195 $c->req->cookies->{sessionid};
196 $c->req->headers->content_type;
199 =item * L<Catalyst::Response>
204 The response is like the request, but contains just response-specific information.
206 $c->res->output('Hello World');
207 $c->res->status(404);
208 $c->res->redirect('http://oook.de');
210 =item * L<Catalyst::Config>
217 =item * L<Catalyst::Log>
221 $c->log->debug('Something happened');
222 $c->log->info('Something you should know');
228 $c->stash->{foo} = 'bar';
232 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:
235 my ( $self, $c ) = @_;
236 $c->stash->{message} = 'Hello World!';
237 $c->forward('show_message');
240 sub show_message : Private {
241 my ( $self, $c ) = @_;
242 $c->res->output( $c->stash->{message} );
245 Note that the stash should be used only for passing data in an individual request cycle; it gets cleared at a new request. If you need to maintain more persistent data, use a session.
249 A Catalyst controller is defined by its actions. An action is
250 a sub with a special attribute. You've already seen some
251 examples of actions in this document.
253 Catalyst supports several types of actions:
259 sub bar : Path('/foo/bar') { }
261 Matches only http://localhost:3000/foo/bar.
265 sub bar : Regex('^foo(\d+)/bar(\d+)$') { }
267 Matches any URL that matches the pattern in the action key, e.g. http://localhost:3000/foo23/bar42. The '' around the regexp is optional, but perltidy likes it. :)
269 If you use capturing parentheses 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.
276 Matches http://localhost:3000/foo. The function name is mapped
277 directly to the application base.
279 =item * B<Namespace-Prefixed>
281 package MyApp::C::My::Controller;
284 Matches http://localhost:3000/my/controller/foo.
286 This action type 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::C" 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.
290 sub foo : Private { }
292 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:
296 See L</Flow Control> for a full explanation of C<forward>.
300 B<Note:> After seeing these examples, you probably wonder what the point is of defining names for regex and path actions. Actually, every public
301 action is also a private one, so you have one unified way of addressing components in your C<forward>s.
303 =head4 Built-in Private Actions
305 In response to specific application states, Catalyst will automatically call these built-in private actions:
309 =item * B<default : Private>
311 Called when no other action matches.
313 =item * B<begin : Private>
315 Called at the beginning of a request, before any matching actions are called.
317 =item * B<end : Private>
321 Called at the end of a request, after all matching actions are called.
323 =head4 B<Built-in actions in controllers/autochaining>
325 Package MyApp::C::Foo;
326 sub begin : Private { }
327 sub default : Private { }
329 You can define the Built-in Private Actions within your controllers as
330 well. The actions will override the ones in lower level controllers/
333 In addition to the normal built-ins, you have a special action for
334 making inheritance chains, 'auto'. These will be run after C<begin>,
335 but before your action is processed.
339 =item for a request for /foo/foo
343 MyApp::C::Foo::default
346 =item for a request for /foo/bar/foo
348 MyApp::C::Foo::Bar::begin
351 MyApp::C::Foo::Bar::default
352 MyApp::C::Foo::Bar::end
356 Also, if you need to break out of the chain in one of your auto
357 actions, you can return 0, if so, your action will not be processed,
358 but the end will, so for the request above, if the first auto returns
359 false, it would look like this:
363 =item for a request for /foo/bar/foo where auto returns false
365 MyApp::C::Foo::Bar::begin
367 MyApp::C::Foo::Bar::end
371 B<Note:> auto actions have to return a true value to continue processing!
372 You can also die in the autochain action, in that case,
373 the request will go straight to the finalize stage, without processing
377 =head4 B<URL Argument Handling>
379 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:
381 sub foo : Regex('^foo$') { my ($self, $context, $bar, $baz) = @_; }
383 But what if you also defined actions for /foo/boo and /foo/boo/hoo ?
385 sub boo : Path('/foo/boo') { .. }
386 sub hoo : Path('/foo/boo/hoo') { .. }
388 Catalyst matches actions in most specific to least specific order:
392 /foo # might be /foo/bar/baz
394 So Catalyst would never mistakenly dispatch the first two URLs to the '^foo$' action.
398 You control the application flow with the C<forward> method, which accepts the key of an action to execute.
401 my ( $self, $c ) = @_;
402 $c->stash->{message} = 'Hello World!';
403 $c->forward('check_message');
406 sub check_message : Private {
407 my ( $self, $c ) = @_;
408 return unless $c->stash->{message};
409 $c->forward('show_message');
412 sub show_message : Private {
413 my ( $self, $c ) = @_;
414 $c->res->output( $c->stash->{message} );
417 As you can see from these examples, you can just use the method name as long as you are referring to methods in the same controller. If you want to forward to a method in another controller, or the main application, you will have to refer to the method by absolute path.
419 $c->forward('/my/controller/action');
420 $c->forward('/default');
422 You can also forward to classes and methods.
425 my ( $self, $c ) = @_;
426 $c->forward(qw/MyApp::M::Hello say_hello/);
430 my ( $self, $c ) = @_;
431 $c->forward('MyApp::M::Hello');
434 package MyApp::M::Hello;
437 my ( $self, $c ) = @_;
438 $c->res->output('Hello World!');
442 my ( $self, $c ) = @_;
443 $c->res->output('Goodbye World!');
446 Note that C<forward> returns to the calling action and continues processing after the action finishes.
447 Catalyst will automatically try to call process() if you omit the method.
451 Catalyst has an uncommonly flexible component system. You can define as many L<Models>, L<Views>, and L<Controllers> as you like.
453 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).
455 package MyApp::C::MyController;
458 use base 'Catalyst::Base';
460 __PACKAGE__->config( foo => 'bar' );
464 You don't have to C<use> or otherwise register Models, Views, and Controllers. Catalyst automatically discovers and instantiates them when you call C<setup> in the main application. 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.
468 =item * B<MyApp/Model/>
472 =item * B<MyApp/View/>
476 =item * B<MyApp/Controller/>
484 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:
486 package MyApp::V::TT;
489 use base 'Catalyst::View::TT';
493 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/)>.
496 my ( $self, $c ) = @_;
497 $c->stash->{template} = 'hello.tt';
501 my ( $self, $c ) = @_;
502 $c->forward('MyApp::V::TT');
505 You normally render templates at the end of a request, so it's a perfect use for the global C<end> action.
507 Also, be sure to put the template under the directory specified in C<$c-E<gt>config-E<lt>{root}>, or you'll be forced to look at our eyecandy debug screen. ;)
511 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>.
513 But first, we need a database.
517 id INTEGER PRIMARY KEY,
522 id INTEGER PRIMARY KEY,
523 foo INTEGER REFERENCES foo,
527 INSERT INTO foo (data) VALUES ('TEST!');
530 % sqlite /tmp/myapp.db < myapp.sql
532 Now we can create a CDBI component for this database.
534 package MyApp::M::CDBI;
537 use base 'Catalyst::Model::CDBI';
540 dsn => 'dbi:SQLite:/tmp/myapp.db',
546 Catalyst automatically loads table layouts and relationships. Use the stash to pass data to your templates.
551 use Catalyst '-Debug';
554 name => 'My Application',
555 root => '/home/joeuser/myapp/root'
561 my ( $self, $c ) = @_;
562 $c->stash->{template} ||= 'index.tt';
563 $c->forward('MyApp::V::TT');
567 my ( $self, $c, $id ) = @_;
568 $c->stash->{item} = MyApp::M::CDBI::Foo->retrieve($id);
573 The id is [% item.data %]
577 Multiple controllers are a good way to separate logical domains of your application.
579 package MyApp::C::Login;
582 new-password : Local { }
585 package MyApp::C::Catalog;
590 package MyApp::C::Cart;
593 sub update : Local { }
594 sub order : Local { }
598 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.)
600 Start your application on the command line...
604 ...then visit http://localhost:3000/ in a browser to view the output.
606 You can also do it all from the command line:
608 script/test.pl http://localhost/
616 Join #catalyst on irc.perl.org.
620 http://lists.rawmode.org/mailman/listinfo/catalyst
621 http://lists.rawmode.org/mailman/listinfo/catalyst-dev
625 Sebastian Riedel, C<sri@oook.de>
626 David Naughton, C<naughton@umn.edu>
627 Marcus Ramberg, C<mramberg@cpan.org>
628 Jesse Sheidlower, C<jester@panix.com>
632 This program is free software, you can redistribute it and/or modify it under
633 the same terms as Perl itself.