doc fixes
[catagits/Catalyst-Runtime.git] / lib / Catalyst / Manual / Intro.pod
CommitLineData
fc7ec1d9 1=head1 NAME
2
3Catalyst::Manual::Intro - Introduction to Catalyst
4
5=head1 DESCRIPTION
6
7This 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.
8
9=head2 What is Catalyst?
10
11Catalyst 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.
12
13=head3 MVC
14
afdca3a3 15Catalyst 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.
fc7ec1d9 16
17Here'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.
18
19=over 4
20
4a6895ce 21=item * B<Model>
fc7ec1d9 22
23Access and modify content (data). L<Class::DBI>, L<Plucene>, L<Net::LDAP>...
24
4a6895ce 25=item * B<View>
fc7ec1d9 26
27Present content to the user. L<Template Toolkit|Template>, L<Mason|HTML::Mason>...
28
4a6895ce 29=item * B<Controller>
fc7ec1d9 30
31Control the whole request phase, check parameters, dispatch actions, flow control. Catalyst!
32
33=back
34
35If 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.
36
37=head3 Flexibility
38
39Catalyst is much more flexible than many other frameworks.
40
41=over 4
42
4a6895ce 43=item * B<Multiple Models, Views and Controllers>
fc7ec1d9 44
45To 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.
46
4a6895ce 47=item * B<Re-Useable Components>
fc7ec1d9 48
49Not 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.
50
4a6895ce 51=item * B<Unrestrained URL-to-Action Dispatching>
fc7ec1d9 52
4a6895ce 53Catalyst 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.
fc7ec1d9 54
55With Catalyst you register your actions and address them directly. For example:
56
e3dc9d78 57 sub hello : Global {
fc7ec1d9 58 my ( $self, $context ) = @_;
59 $context->response->output('Hello World!');
5a8ed4fe 60 }
fc7ec1d9 61
62Now http://localhost:3000/hello prints "Hello World!".
63
4a6895ce 64=item * B<Support for CGI, mod_perl, Apache::Request>
fc7ec1d9 65
66Use L<Catalyst::Engine::Apache> or L<Catalyst::Engine::CGI>.
67
68=back
69
70=head3 Simplicity
71
72The best part is that Catalyst implements all this flexibility in a very simple way.
73
6f4e1683 74=over 4
75
4a6895ce 76=item * B<Building Block Interface>
fc7ec1d9 77
78Components 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.
79
4a6895ce 80=item * B<Component Auto-Discovery>
fc7ec1d9 81
82No need to C<use> all of your components. Catalyst automatically finds and loads them.
83
4a6895ce 84=item * B<Pre-Built Components for Popular Modules>
fc7ec1d9 85
86See 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>.
87
4a6895ce 88=item * B<Builtin Test Framework>
fc7ec1d9 89
90Catalyst comes with a builtin, lightweight http server and test framework, making it easy to test applications from the command line.
91
4a6895ce 92=item * B<Helper Scripts>
fc7ec1d9 93
94Catalyst provides helper scripts to quickly generate running starter code for components and unit tests.
95
6f4e1683 96=back
97
fc7ec1d9 98=head2 Quickstart
99
100Here's how to install Catalyst and get a simple application up and running, using the helper scripts described above.
101
102=head3 Install
103
104 $ perl -MCPAN -e 'install Bundle::Catalyst'
105
106=head3 Setup
107
91864987 108 $ catalyst.pl My::App
fc7ec1d9 109 $ cd My-App
91864987 110 $ script/create.pl controller My::Controller
fc7ec1d9 111
112=head3 Run
113
91864987 114 $ script/server.pl
fc7ec1d9 115
116Now visit these locations with your favorite browser or user agent to see Catalyst in action:
117
118=over 4
119
120=item http://localhost:3000/
121
122=item http://localhost:3000/my_controller/
123
124=back
125
126Dead easy!
127
128=head2 How It Works
129
130Let's see how Catalyst works, by taking a closer look at the components and other parts of a Catalyst application.
131
132=head3 Application Class
133
134In 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
136 package MyApp;
137
138 use strict;
139 use Catalyst qw/-Debug/;
140
141 MyApp->config(
142 name => 'My Application',
143 root => '/home/joeuser/myapp/root',
144
145 # You can put whatever you want in here:
146 # my_param_name => $my_param_value,
147 );
148
5a8ed4fe 149 sub default : Private {
fc7ec1d9 150 my ( $self, $context ) = @_;
151 $context->response->output('Catalyst rockz!');
5a8ed4fe 152 }
fc7ec1d9 153
154 1;
155
156For most applications, Catalyst requires you to define only two config parameters:
157
158=over 4
159
4a6895ce 160=item * B<name>
fc7ec1d9 161
162Name of your application.
163
4a6895ce 164=item * B<root>
fc7ec1d9 165
166Path to additional files like templates, images or other static data.
167
168=back
169
4a6895ce 170However, 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}>.
fc7ec1d9 171
172=head3 Context
173
174Catalyst 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.
175
4a6895ce 176As 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>:
fc7ec1d9 177
e3dc9d78 178 sub hello : Global {
fc7ec1d9 179 my ( $self, $c ) = @_;
180 $c->res->output('Hello World!');
5a8ed4fe 181 }
fc7ec1d9 182
183The Context contains several important objects:
184
185=over 4
186
187=item * L<Catalyst::Request>
188
189 $c->request
190 $c->req # alias
191
4a6895ce 192The request contains all kinds of request-specific information, like query parameters, cookies, uploads, headers and more.
fc7ec1d9 193
194 $c->req->params->{foo};
195 $c->req->cookies->{sessionid};
196 $c->req->headers->content_type;
197 $c->req->base;
198
afdca3a3 199=item * L<Catalyst::Response>
fc7ec1d9 200
201 $c->response
202 $c->res # alias
203
4a6895ce 204The response is like the request, but contains just response-specific information.
fc7ec1d9 205
206 $c->res->output('Hello World');
207 $c->res->status(404);
208 $c->res->redirect('http://oook.de');
209
210=item * L<Catalyst::Config>
211
212 $c->config
213
214 $c->config->root;
215 $c->config->name;
216
217=item * L<Catalyst::Log>
218
219 $c->log
220
221 $c->log->debug('Something happened');
222 $c->log->info('Something you should know');
223
4a6895ce 224=item * B<Stash>
fc7ec1d9 225
226 $c->stash
227
228 $c->stash->{foo} = 'bar';
229
230=back
231
4a6895ce 232The last of these, the stash, is a universal hash for sharing data among application components. For an example, we return to our 'hello' action:
fc7ec1d9 233
e3dc9d78 234 sub hello : Global {
5a8ed4fe 235 my ( $self, $c ) = @_;
236 $c->stash->{message} = 'Hello World!';
237 $c->forward('show-message');
238 }
fc7ec1d9 239
5a8ed4fe 240 show-message : Private {
241 my ( $self, $c ) = @_;
242 $c->res->output( $c->stash->{message} );
243 }
fc7ec1d9 244
245=head3 Actions
246
afdca3a3 247To 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).
fc7ec1d9 248
249Catalyst supports several ways to define Actions:
250
251=over 4
252
4a6895ce 253=item * B<Literal>
fc7ec1d9 254
e3dc9d78 255 sub bar : Path('/foo/bar') { }
fc7ec1d9 256
257Matches only http://localhost:3000/foo/bar.
258
4a6895ce 259=item * B<Regex>
fc7ec1d9 260
5a8ed4fe 261 sub bar : Regex('/^foo(\d+)/bar(\d+)$/') { }
fc7ec1d9 262
263Matches 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/'.
264
4a6895ce 265If 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.
fc7ec1d9 266
4a6895ce 267=item * B<Namespace-Prefixed>
fc7ec1d9 268
269 package MyApp::Controller::My::Controller;
e3dc9d78 270 sub foo : Local { }
fc7ec1d9 271
5a8ed4fe 272Matches http://localhost:3000/my/controller/foo. The action key must be prefixed with '?'.
fc7ec1d9 273
274Prefixing 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.
275
4a6895ce 276=item * B<Private>
fc7ec1d9 277
5a8ed4fe 278 sub foo : Private { }
fc7ec1d9 279
280Matches 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:
281
5a8ed4fe 282 $c->forward('foo');
fc7ec1d9 283
284See L</Flow Control> for a full explanation of C<forward>.
285
286=back
287
288=head4 Builtin Private Actions
289
290In response to specific application states, Catalyst will automatically call these built in private actions:
291
292=over 4
293
4a6895ce 294=item * B<!default>
fc7ec1d9 295
296Called when no other action matches.
297
4a6895ce 298=item * B<!begin>
fc7ec1d9 299
300Called at the beginning of a request, before any matching actions are called.
301
4a6895ce 302=item * B<!end>
303
304=back
fc7ec1d9 305
306Called at the end of a request, after all matching actions are called.
307
4a6895ce 308=head4 B<Namespace-Prefixed Private Actions>
fc7ec1d9 309
5a8ed4fe 310 sub foo : Private { }
311 sub default : Private { }
fc7ec1d9 312
4a6895ce 313The 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.
314
315=head4 B<URL Argument Handling>
316
317If 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:
318
5a8ed4fe 319 sub foo : Regex('/^foo$/') { my ($self, $context, $bar, $baz) = @_; }
4a6895ce 320
321But what if you also defined actions for /foo/boo and /foo/boo/hoo ?
322
e3dc9d78 323 sub boo : Path('/foo/boo') { .. }
324 sub hoo : Path('/foo/boo/hoo') { .. }
4a6895ce 325
326Catalyst matches actions in most specific to least specific order:
327
328 /foo/boo/hoo
329 /foo/boo
330 /foo # might be /foo/bar/baz
331
332So Catalyst would never mistakenly dispatch the first two URLs to the '/^foo$/' action.
fc7ec1d9 333
334=head3 Flow Control
335
336Control the application flow with the C<forward> method, which accepts the key of an action to execute.
337
e3dc9d78 338 sub hello : Global {
5a8ed4fe 339 my ( $self, $c ) = @_;
340 $c->stash->{message} = 'Hello World!';
341 $c->forward('check-message');
342 }
fc7ec1d9 343
5a8ed4fe 344 sub check-message : Private {
345 my ( $self, $c ) = @_;
346 return unless $c->stash->{message};
347 $c->forward('show-message');
348 }
fc7ec1d9 349
5a8ed4fe 350 sub show-message : Private {
351 my ( $self, $c ) = @_;
352 $c->res->output( $c->stash->{message} );
353 }
fc7ec1d9 354
355You can also forward to classes and methods.
356
e3dc9d78 357 sub hello : Global {
5a8ed4fe 358 my ( $self, $c ) = @_;
359 $c->forward(qw/MyApp::M::Hello say_hello/);
360 }
fc7ec1d9 361
e3dc9d78 362 sub bye : Global {
5a8ed4fe 363 my ( $self, $c ) = @_;
364 $c->forward('MyApp::M::Hello');
365 }
fc7ec1d9 366
367 package MyApp::M::Hello;
368
369 sub say_hello {
370 my ( $self, $c ) = @_;
371 $c->res->output('Hello World!');
372 }
373
374 sub process {
375 my ( $self, $c ) = @_;
376 $c->res->output('Goodbye World!');
377 }
378
379Note that C<forward> returns after processing.
380Catalyst will automatically try to call process() if you omit the method.
381
382=head3 Components
383
4a6895ce 384Again, Catalyst has an uncommonly flexible component system. You can define as many L<Models>, L<Views> and L<Controllers> as you like.
fc7ec1d9 385
4a6895ce 386All 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).
fc7ec1d9 387
388 package MyApp::Controller::MyController;
389
390 use strict;
391 use base 'Catalyst::Base';
392
393 __PACKAGE__->config( foo => 'bar' );
394
395 1;
396
397You 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.
398
399=over 4
400
4a6895ce 401=item * B<MyApp/Model/>
fc7ec1d9 402
4a6895ce 403=item * B<MyApp/M/>
fc7ec1d9 404
4a6895ce 405=item * B<MyApp/View/>
fc7ec1d9 406
4a6895ce 407=item * B<MyApp/V/>
fc7ec1d9 408
4a6895ce 409=item * B<MyApp/Controller/>
fc7ec1d9 410
4a6895ce 411=item * B<MyApp/C/>
fc7ec1d9 412
413=back
414
415=head4 Views
416
417To 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:
418
419 package MyApp::V::TT;
420
421 use strict;
422 use base 'Catalyst::View::TT';
423
424 1;
425
426This 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/)>.
427
e3dc9d78 428 sub hello : Global {
5a8ed4fe 429 my ( $self, $c ) = @_;
430 $c->stash->{template} = 'hello.tt';
431 }
fc7ec1d9 432
5a8ed4fe 433 sub end : Private {
434 my ( $self, $c ) = @_;
435 $c->forward('MyApp::View::TT');
436 }
fc7ec1d9 437
438You normally render templates at the end of a request, so it's a perfect use for the !end action.
439
440Also, 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. ;)
441
442=head4 Models
443
444To show how to define models, again we'll use an already-existing base class, this time for L<Class::DBI>: L<Catalyst::Model::CDBI>.
445
446But first, we need a database.
447
448 -- myapp.sql
449 CREATE TABLE foo (
450 id INTEGER PRIMARY KEY,
451 data TEXT
452 );
453
454 CREATE TABLE bar (
455 id INTEGER PRIMARY KEY,
456 foo INTEGER REFERENCES foo,
457 data TEXT
458 );
459
460 INSERT INTO foo (data) VALUES ('TEST!');
461
462
463 % sqlite /tmp/myapp.db < myapp.sql
464
465Now we can create a CDBI component for this database.
466
467 package MyApp::M::CDBI;
468
469 use strict;
470 use base 'Catalyst::Model::CDBI';
471
472 __PACKAGE__->config(
473 dsn => 'dbi:SQLite:/tmp/myapp.db',
474 relationships => 1
475 );
476
477 1;
478
479Catalyst automatically loads table layouts and relationships. Use the stash to pass data to your templates.
480
481 package MyApp;
482
483 use strict;
484 use Catalyst '-Debug';
485
486 __PACKAGE__->config(
487 name => 'My Application',
488 root => '/home/joeuser/myapp/root'
489 );
490
5a8ed4fe 491 sub end : Private {
492 my ( $self, $c ) = @_;
493 $c->stash->{template} ||= 'index.tt';
494 $c->forward('MyApp::V::TT');
495 }
fc7ec1d9 496
e3dc9d78 497 sub view : Global {
5a8ed4fe 498 my ( $self, $c, $id ) = @_;
499 $c->stash->{item} = MyApp::M::CDBI::Foo->retrieve($id);
500 }
fc7ec1d9 501
502 1;
503
504 The id is [% item.data %]
505
506=head4 Controllers
507
afdca3a3 508Multiple Controllers are a good way to separate logical domains of your application.
fc7ec1d9 509
510 package MyApp::C::Login;
511
5a8ed4fe 512 sign-in : Relative { }
513 new-password :Relative { }
514 sign-out : Relative { }
fc7ec1d9 515
516 package MyApp::C::Catalog;
517
e3dc9d78 518 sub view : Local { }
519 sub list : Local { }
fc7ec1d9 520
521 package MyApp::C::Cart;
522
e3dc9d78 523 sub add : Local { }
524 sub update : Local { }
525 sub order : Local { }
fc7ec1d9 526
527=head3 Testing
528
529Catalyst 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).
530
531Start your application on the command line...
532
fd0b84fe 533 script/server.pl
fc7ec1d9 534
535...then visit http://localhost:3000/ in a browser to view the output.
536
537You can also do it all from the command line:
538
fd0b84fe 539 script/test.pl http://localhost/
fc7ec1d9 540
541Have fun!
542
3cb1db8c 543=head1 SUPPORT
544
545IRC:
546
547 Join #catalyst on irc.perl.org.
548
549Mailing-Lists:
550
551 http://lists.rawmode.org/mailman/listinfo/catalyst
552 http://lists.rawmode.org/mailman/listinfo/catalyst-dev
553
fc7ec1d9 554=head1 AUTHOR
555
556Sebastian Riedel, C<sri@oook.de> and David Naughton, C<naughton@umn.edu>
557
558=head1 COPYRIGHT
559
560This program is free software, you can redistribute it and/or modify it under
561the same terms as Perl itself.