updated server.pl and cgi-server.pl
[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
57 MyApp->action( 'hello' => sub {
58 my ( $self, $context ) = @_;
59 $context->response->output('Hello World!');
60 });
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
4a6895ce 74=item * B<Building Block Interface>
fc7ec1d9 75
76Components 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.
77
4a6895ce 78=item * B<Component Auto-Discovery>
fc7ec1d9 79
80No need to C<use> all of your components. Catalyst automatically finds and loads them.
81
4a6895ce 82=item * B<Pre-Built Components for Popular Modules>
fc7ec1d9 83
84See 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>.
85
4a6895ce 86=item * B<Builtin Test Framework>
fc7ec1d9 87
88Catalyst comes with a builtin, lightweight http server and test framework, making it easy to test applications from the command line.
89
4a6895ce 90=item * B<Helper Scripts>
fc7ec1d9 91
92Catalyst provides helper scripts to quickly generate running starter code for components and unit tests.
93
94=head2 Quickstart
95
96Here's how to install Catalyst and get a simple application up and running, using the helper scripts described above.
97
98=head3 Install
99
100 $ perl -MCPAN -e 'install Bundle::Catalyst'
101
102=head3 Setup
103
91864987 104 $ catalyst.pl My::App
fc7ec1d9 105 $ cd My-App
91864987 106 $ script/create.pl controller My::Controller
fc7ec1d9 107
108=head3 Run
109
91864987 110 $ script/server.pl
fc7ec1d9 111
112Now visit these locations with your favorite browser or user agent to see Catalyst in action:
113
114=over 4
115
116=item http://localhost:3000/
117
118=item http://localhost:3000/my_controller/
119
120=back
121
122Dead easy!
123
124=head2 How It Works
125
126Let's see how Catalyst works, by taking a closer look at the components and other parts of a Catalyst application.
127
128=head3 Application Class
129
130In 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.
131
132 package MyApp;
133
134 use strict;
135 use Catalyst qw/-Debug/;
136
137 MyApp->config(
138 name => 'My Application',
139 root => '/home/joeuser/myapp/root',
140
141 # You can put whatever you want in here:
142 # my_param_name => $my_param_value,
143 );
144
145 MyApp->action( '!default' => sub {
146 my ( $self, $context ) = @_;
147 $context->response->output('Catalyst rockz!');
148 });
149
150 1;
151
152For most applications, Catalyst requires you to define only two config parameters:
153
154=over 4
155
4a6895ce 156=item * B<name>
fc7ec1d9 157
158Name of your application.
159
4a6895ce 160=item * B<root>
fc7ec1d9 161
162Path to additional files like templates, images or other static data.
163
164=back
165
4a6895ce 166However, 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 167
168=head3 Context
169
170Catalyst 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.
171
4a6895ce 172As 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 173
174 MyApp->action( 'hello' => sub {
175 my ( $self, $c ) = @_;
176 $c->res->output('Hello World!');
177 });
178
179The Context contains several important objects:
180
181=over 4
182
183=item * L<Catalyst::Request>
184
185 $c->request
186 $c->req # alias
187
4a6895ce 188The request contains all kinds of request-specific information, like query parameters, cookies, uploads, headers and more.
fc7ec1d9 189
190 $c->req->params->{foo};
191 $c->req->cookies->{sessionid};
192 $c->req->headers->content_type;
193 $c->req->base;
194
afdca3a3 195=item * L<Catalyst::Response>
fc7ec1d9 196
197 $c->response
198 $c->res # alias
199
4a6895ce 200The response is like the request, but contains just response-specific information.
fc7ec1d9 201
202 $c->res->output('Hello World');
203 $c->res->status(404);
204 $c->res->redirect('http://oook.de');
205
206=item * L<Catalyst::Config>
207
208 $c->config
209
210 $c->config->root;
211 $c->config->name;
212
213=item * L<Catalyst::Log>
214
215 $c->log
216
217 $c->log->debug('Something happened');
218 $c->log->info('Something you should know');
219
4a6895ce 220=item * B<Stash>
fc7ec1d9 221
222 $c->stash
223
224 $c->stash->{foo} = 'bar';
225
226=back
227
4a6895ce 228The 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 229
230 MyApp->action(
231
232 'hello' => sub {
233 my ( $self, $c ) = @_;
234 $c->stash->{message} = 'Hello World!';
235 $c->forward('!show-message');
236 },
237
238 '!show-message' => sub {
239 my ( $self, $c ) = @_;
240 $c->res->output( $c->stash->{message} );
241 },
242
243 );
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
d7c505f3 255 MyApp->action( 'foo/bar' => sub { } );
fc7ec1d9 256
257Matches only http://localhost:3000/foo/bar.
258
4a6895ce 259=item * B<Regex>
fc7ec1d9 260
3640f71c 261 MyApp->action( '/^foo(\d+)/bar(\d+)$/' => sub { } );
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;
d7c505f3 270 MyApp->action( '?foo' => sub { } );
fc7ec1d9 271
272Matches http://localhost:3000/my_controller/foo. The action key must be prefixed with '?'.
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
d7c505f3 278 MyApp->action( '!foo' => sub { } );
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
282 $c->forward('!foo');
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
4a6895ce 310 MyApp->action( '!?foo' => sub { } );
311 MyApp->action( '!?default' => sub { } );
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
319 MyApp->action( '/^foo$/' => sub { my ($self, $context, $bar, $baz) = @_; } );
320
321But what if you also defined actions for /foo/boo and /foo/boo/hoo ?
322
323 MyApp->action( '/foo/boo' => sub { .. } );
324 MyApp->action( '/foo/boo/hoo' => sub { .. } );
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
338 MyApp->action(
339
340 'hello' => sub {
341 my ( $self, $c ) = @_;
342 $c->stash->{message} = 'Hello World!';
343 $c->forward('!check-message');
344 },
345
346 '!check-message' => sub {
347 my ( $self, $c ) = @_;
348 return unless $c->stash->{message};
349 $c->forward('!show-message');
350 },
351
352 '!show-message' => sub {
353 my ( $self, $c ) = @_;
354 $c->res->output( $c->stash->{message} );
355 },
356
357 );
358
359You can also forward to classes and methods.
360
361 MyApp->action(
362
363 'hello' => sub {
364 my ( $self, $c ) = @_;
365 $c->forward(qw/MyApp::M::Hello say_hello/);
366 },
367
368 'bye' => sub {
369 my ( $self, $c ) = @_;
370 $c->forward('MyApp::M::Hello');
371 },
372
373 );
374
375 package MyApp::M::Hello;
376
377 sub say_hello {
378 my ( $self, $c ) = @_;
379 $c->res->output('Hello World!');
380 }
381
382 sub process {
383 my ( $self, $c ) = @_;
384 $c->res->output('Goodbye World!');
385 }
386
387Note that C<forward> returns after processing.
388Catalyst will automatically try to call process() if you omit the method.
389
390=head3 Components
391
4a6895ce 392Again, Catalyst has an uncommonly flexible component system. You can define as many L<Models>, L<Views> and L<Controllers> as you like.
fc7ec1d9 393
4a6895ce 394All 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 395
396 package MyApp::Controller::MyController;
397
398 use strict;
399 use base 'Catalyst::Base';
400
401 __PACKAGE__->config( foo => 'bar' );
402
403 1;
404
405You 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.
406
407=over 4
408
4a6895ce 409=item * B<MyApp/Model/>
fc7ec1d9 410
4a6895ce 411=item * B<MyApp/M/>
fc7ec1d9 412
4a6895ce 413=item * B<MyApp/View/>
fc7ec1d9 414
4a6895ce 415=item * B<MyApp/V/>
fc7ec1d9 416
4a6895ce 417=item * B<MyApp/Controller/>
fc7ec1d9 418
4a6895ce 419=item * B<MyApp/C/>
fc7ec1d9 420
421=back
422
423=head4 Views
424
425To 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:
426
427 package MyApp::V::TT;
428
429 use strict;
430 use base 'Catalyst::View::TT';
431
432 1;
433
434This 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/)>.
435
436 MyApp->action(
437
438 'hello' => sub {
439 my ( $self, $c ) = @_;
440 $c->stash->{template} = 'hello.tt';
441 },
442
443 '!end' => sub {
444 my ( $self, $c ) = @_;
445 $c->forward('MyApp::View::TT');
446 },
447
448 );
449
450You normally render templates at the end of a request, so it's a perfect use for the !end action.
451
452Also, 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. ;)
453
454=head4 Models
455
456To show how to define models, again we'll use an already-existing base class, this time for L<Class::DBI>: L<Catalyst::Model::CDBI>.
457
458But first, we need a database.
459
460 -- myapp.sql
461 CREATE TABLE foo (
462 id INTEGER PRIMARY KEY,
463 data TEXT
464 );
465
466 CREATE TABLE bar (
467 id INTEGER PRIMARY KEY,
468 foo INTEGER REFERENCES foo,
469 data TEXT
470 );
471
472 INSERT INTO foo (data) VALUES ('TEST!');
473
474
475 % sqlite /tmp/myapp.db < myapp.sql
476
477Now we can create a CDBI component for this database.
478
479 package MyApp::M::CDBI;
480
481 use strict;
482 use base 'Catalyst::Model::CDBI';
483
484 __PACKAGE__->config(
485 dsn => 'dbi:SQLite:/tmp/myapp.db',
486 relationships => 1
487 );
488
489 1;
490
491Catalyst automatically loads table layouts and relationships. Use the stash to pass data to your templates.
492
493 package MyApp;
494
495 use strict;
496 use Catalyst '-Debug';
497
498 __PACKAGE__->config(
499 name => 'My Application',
500 root => '/home/joeuser/myapp/root'
501 );
502
503 __PACKAGE__->action(
504
505 '!end' => sub {
506 my ( $self, $c ) = @_;
507 $c->stash->{template} ||= 'index.tt';
508 $c->forward('MyApp::V::TT');
509 },
510
511 'view' => sub {
512 my ( $self, $c, $id ) = @_;
513 $c->stash->{item} = MyApp::M::CDBI::Foo->retrieve($id);
514 }
515
516 );
517
518 1;
519
520 The id is [% item.data %]
521
522=head4 Controllers
523
afdca3a3 524Multiple Controllers are a good way to separate logical domains of your application.
fc7ec1d9 525
526 package MyApp::C::Login;
527
528 MyApp->action(
529 '?sign-in' => sub { },
530 '?new-password' => sub { },
531 '?sign-out' => sub { },
532 );
533
534 package MyApp::C::Catalog;
535
536 MyApp->action(
537 '?view' => sub { },
538 '?list' => sub { },
539 );
540
541 package MyApp::C::Cart;
542
543 MyApp->action(
544 '?add' => sub { },
545 '?update' => sub { },
546 '?order' => sub { },
547 );
548
549=head3 Testing
550
551Catalyst 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).
552
553Start your application on the command line...
554
fd0b84fe 555 script/server.pl
fc7ec1d9 556
557...then visit http://localhost:3000/ in a browser to view the output.
558
559You can also do it all from the command line:
560
fd0b84fe 561 script/test.pl http://localhost/
fc7ec1d9 562
563Have fun!
564
3cb1db8c 565=head1 SUPPORT
566
567IRC:
568
569 Join #catalyst on irc.perl.org.
570
571Mailing-Lists:
572
573 http://lists.rawmode.org/mailman/listinfo/catalyst
574 http://lists.rawmode.org/mailman/listinfo/catalyst-dev
575
fc7ec1d9 576=head1 AUTHOR
577
578Sebastian Riedel, C<sri@oook.de> and David Naughton, C<naughton@umn.edu>
579
580=head1 COPYRIGHT
581
582This program is free software, you can redistribute it and/or modify it under
583the same terms as Perl itself.