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 tat 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 * 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 * 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 * 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 you to put class and method names in your 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 * 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 * 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 * Component Auto-Discovery
80 No need to C<use> all of your components. Catalyst automatically finds and loads them.
82 =item * 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 * 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 * 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'
106 $ bin/create 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 $context->config->{$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 itself. Previously we called it $context for clarity, but most Catalyst developers just call it $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 kind of request specific informations 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::Reponse>
200 The response is like the request but contais just response specific informations.
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 example:
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 applicaton 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 $c->action( 'foo/bar' => sub { } );
257 Matches only http://localhost:3000/foo/bar.
261 $c->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. Be sure to use ^ and $ if your action has arguments.
267 =item * Namespace-Prefixed
269 package MyApp::Controller::My::Controller;
270 $c->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 $c->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.
304 Called at the end of a request, after all matching actions are called.
306 =item * !?default, !?begin and !?end
308 Like their equivalents above but used to overload them from Controllers.
309 So each Controller can have their own !?default, !?begin and !?end.
315 Control the application flow with the C<forward> method, which accepts the key of an action to execute.
320 my ( $self, $c ) = @_;
321 $c->stash->{message} = 'Hello World!';
322 $c->forward('!check-message');
325 '!check-message' => sub {
326 my ( $self, $c ) = @_;
327 return unless $c->stash->{message};
328 $c->forward('!show-message');
331 '!show-message' => sub {
332 my ( $self, $c ) = @_;
333 $c->res->output( $c->stash->{message} );
338 You can also forward to classes and methods.
343 my ( $self, $c ) = @_;
344 $c->forward(qw/MyApp::M::Hello say_hello/);
348 my ( $self, $c ) = @_;
349 $c->forward('MyApp::M::Hello');
354 package MyApp::M::Hello;
357 my ( $self, $c ) = @_;
358 $c->res->output('Hello World!');
362 my ( $self, $c ) = @_;
363 $c->res->output('Goodbye World!');
366 Note that C<forward> returns after processing.
367 Catalyst will automatically try to call process() if you omit the method.
371 Again, Catalyst has an uncommonly flexible component system. You can define as many L<Models>, L<Views> and Controllers as you like.
373 All components are must inherit from L<Catalyst::Base>, which provides a simple class structure and some common class methods like C<config> and C<new> (constructor).
375 package MyApp::Controller::MyController;
378 use base 'Catalyst::Base';
380 __PACKAGE__->config( foo => 'bar' );
384 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.
396 =item * MyApp/Controller/
404 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:
406 package MyApp::V::TT;
409 use base 'Catalyst::View::TT';
413 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/)>.
418 my ( $self, $c ) = @_;
419 $c->stash->{template} = 'hello.tt';
423 my ( $self, $c ) = @_;
424 $c->forward('MyApp::View::TT');
429 You normally render templates at the end of a request, so it's a perfect use for the !end action.
431 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. ;)
435 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>.
437 But first, we need a database.
441 id INTEGER PRIMARY KEY,
446 id INTEGER PRIMARY KEY,
447 foo INTEGER REFERENCES foo,
451 INSERT INTO foo (data) VALUES ('TEST!');
454 % sqlite /tmp/myapp.db < myapp.sql
456 Now we can create a CDBI component for this database.
458 package MyApp::M::CDBI;
461 use base 'Catalyst::Model::CDBI';
464 dsn => 'dbi:SQLite:/tmp/myapp.db',
470 Catalyst automatically loads table layouts and relationships. Use the stash to pass data to your templates.
475 use Catalyst '-Debug';
478 name => 'My Application',
479 root => '/home/joeuser/myapp/root'
485 my ( $self, $c ) = @_;
486 $c->stash->{template} ||= 'index.tt';
487 $c->forward('MyApp::V::TT');
491 my ( $self, $c, $id ) = @_;
492 $c->stash->{item} = MyApp::M::CDBI::Foo->retrieve($id);
499 The id is [% item.data %]
503 Multiple Controllers are a good way to separate logical domains of your application and distribute tasks to different programmers in a teams.
505 package MyApp::C::Login;
508 '?sign-in' => sub { },
509 '?new-password' => sub { },
510 '?sign-out' => sub { },
513 package MyApp::C::Catalog;
520 package MyApp::C::Cart;
524 '?update' => sub { },
530 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).
532 Start your application on the command line...
534 perl -I/home/joeuser/myapp/lib -MCatalyst::Test=MyApp -e1 3000
536 ...then visit http://localhost:3000/ in a browser to view the output.
538 You can also do it all from the command line:
540 perl -I/home/joeuser/myapp/lib -MCatalyst::Test=MyApp -e1 http://localhost/
546 Sebastian Riedel, C<sri@oook.de> and David Naughton, C<naughton@umn.edu>
550 This program is free software, you can redistribute it and/or modify it under
551 the same terms as Perl itself.