Added deep recursion detection
[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
72d9bfc7 7This 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.
fc7ec1d9 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
72d9bfc7 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 the re-use of existing Perl modules that already handle common web application concerns well.
fc7ec1d9 16
72d9bfc7 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.
fc7ec1d9 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
cda8d1ac 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, 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.
fc7ec1d9 36
37=head3 Flexibility
38
72d9bfc7 39Catalyst 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.
fc7ec1d9 40
41=over 4
42
72d9bfc7 43=item * B<Multiple Models, Views, and Controllers>
fc7ec1d9 44
72d9bfc7 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 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.
fc7ec1d9 46
cda8d1ac 47=item * B<Reuseable Components>
fc7ec1d9 48
cda8d1ac 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.
fc7ec1d9 50
4a6895ce 51=item * B<Unrestrained URL-to-Action Dispatching>
fc7ec1d9 52
cda8d1ac 53Catalyst 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.
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
cda8d1ac 78Components 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.
fc7ec1d9 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
72d9bfc7 88=item * B<Built-in Test Framework>
fc7ec1d9 89
72d9bfc7 90Catalyst comes with a built-in, lightweight http server and test framework, making it easy to test applications from the command line.
fc7ec1d9 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
2feb6632 108 $ catalyst.pl MyApp
109 $ cd MyApp
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
bbcadec7 122=item http://localhost:3000/my/controller/
fc7ec1d9 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
72d9bfc7 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.
fc7ec1d9 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
72d9bfc7 166Path to additional files such as templates, images, or other static data.
fc7ec1d9 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
72d9bfc7 192The request object 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!';
4c6807d2 237 $c->forward('show_message');
5a8ed4fe 238 }
fc7ec1d9 239
4c6807d2 240 sub show_message : Private {
5a8ed4fe 241 my ( $self, $c ) = @_;
242 $c->res->output( $c->stash->{message} );
243 }
fc7ec1d9 244
dd25a192 245Note 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.
246
fc7ec1d9 247=head3 Actions
248
72d9bfc7 249A Catalyst controller is defined by its actions. An action is
250a sub with a special attribute. You've already seen some
251examples of actions in this document.
cda8d1ac 252
253Catalyst supports several types of actions:
fc7ec1d9 254
255=over 4
256
4a6895ce 257=item * B<Literal>
fc7ec1d9 258
e3dc9d78 259 sub bar : Path('/foo/bar') { }
fc7ec1d9 260
261Matches only http://localhost:3000/foo/bar.
262
4a6895ce 263=item * B<Regex>
fc7ec1d9 264
cda8d1ac 265 sub bar : Regex('^foo(\d+)/bar(\d+)$') { }
fc7ec1d9 266
cda8d1ac 267Matches 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. :)
fc7ec1d9 268
72d9bfc7 269If 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.
fc7ec1d9 270
72d9bfc7 271=item * B<Top-level>
cda8d1ac 272
273 package MyApp;
274 sub foo : Global { }
275
276Matches http://localhost:3000/foo. The function name is mapped
277directly to the application base.
278
4a6895ce 279=item * B<Namespace-Prefixed>
fc7ec1d9 280
2feb6632 281 package MyApp::C::My::Controller;
e3dc9d78 282 sub foo : Local { }
fc7ec1d9 283
cda8d1ac 284Matches http://localhost:3000/my/controller/foo.
fc7ec1d9 285
72d9bfc7 286This 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.
fc7ec1d9 287
4a6895ce 288=item * B<Private>
fc7ec1d9 289
5a8ed4fe 290 sub foo : Private { }
fc7ec1d9 291
292Matches 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:
293
5a8ed4fe 294 $c->forward('foo');
fc7ec1d9 295
296See L</Flow Control> for a full explanation of C<forward>.
297
298=back
299
72d9bfc7 300B<Note:> After seeing these examples, you probably wonder what the point is of defining names for regex and path actions. Actually, every public
301action is also a private one, so you have one unified way of addressing components in your C<forward>s.
cda8d1ac 302
72d9bfc7 303=head4 Built-in Private Actions
fc7ec1d9 304
72d9bfc7 305In response to specific application states, Catalyst will automatically call these built-in private actions:
fc7ec1d9 306
307=over 4
308
cda8d1ac 309=item * B<default : Private>
fc7ec1d9 310
311Called when no other action matches.
312
cda8d1ac 313=item * B<begin : Private>
fc7ec1d9 314
315Called at the beginning of a request, before any matching actions are called.
316
cda8d1ac 317=item * B<end : Private>
4a6895ce 318
319=back
fc7ec1d9 320
321Called at the end of a request, after all matching actions are called.
322
72d9bfc7 323=head4 B<Built-in actions in controllers/autochaining>
fc7ec1d9 324
cda8d1ac 325 Package MyApp::C::Foo;
326 sub begin : Private { }
5a8ed4fe 327 sub default : Private { }
fc7ec1d9 328
72d9bfc7 329You can define the Built-in Private Actions within your controllers as
80ef2e6d 330well. The actions will override the ones in lower level controllers/
331global.
332
72d9bfc7 333In addition to the normal built-ins, you have a special action for
334making inheritance chains, 'auto'. These will be run after C<begin>,
80ef2e6d 335but before your action is processed.
cda8d1ac 336
337=over 4
338
339=item for a request for /foo/foo
340
341 MyApp::begin
80ef2e6d 342 MyApp::auto
42a57832 343 MyApp::C::Foo::default
cda8d1ac 344 MyApp::end
345
346=item for a request for /foo/bar/foo
347
cda8d1ac 348 MyApp::C::Foo::Bar::begin
80ef2e6d 349 MyApp::auto
350 MyApp::C::Foo::auto
cda8d1ac 351 MyApp::C::Foo::Bar::default
352 MyApp::C::Foo::Bar::end
80ef2e6d 353
354=back
355
356Also, if you need to break out of the chain in one of your auto
357actions, you can return 0, if so, your action will not be processed,
358but the end will, so for the request above, if the first auto returns
359false, it would look like this:
360
361=over 4
362
363=item for a request for /foo/bar/foo where auto returns false
364
365 MyApp::C::Foo::Bar::begin
366 MyApp::auto
367 MyApp::C::Foo::Bar::end
cda8d1ac 368
369=back
4a6895ce 370
72d9bfc7 371B<Note:> auto actions have to return a true value to continue processing!
f32dff11 372You can also die in the autochain action, in that case,
03805733 373the request will go straight to the finalize stage, without processing
374further actions.
375
376
4a6895ce 377=head4 B<URL Argument Handling>
378
379If 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:
380
cda8d1ac 381 sub foo : Regex('^foo$') { my ($self, $context, $bar, $baz) = @_; }
4a6895ce 382
383But what if you also defined actions for /foo/boo and /foo/boo/hoo ?
384
e3dc9d78 385 sub boo : Path('/foo/boo') { .. }
386 sub hoo : Path('/foo/boo/hoo') { .. }
4a6895ce 387
388Catalyst matches actions in most specific to least specific order:
389
390 /foo/boo/hoo
391 /foo/boo
392 /foo # might be /foo/bar/baz
393
cda8d1ac 394So Catalyst would never mistakenly dispatch the first two URLs to the '^foo$' action.
fc7ec1d9 395
396=head3 Flow Control
397
cda8d1ac 398You control the application flow with the C<forward> method, which accepts the key of an action to execute.
fc7ec1d9 399
e3dc9d78 400 sub hello : Global {
5a8ed4fe 401 my ( $self, $c ) = @_;
402 $c->stash->{message} = 'Hello World!';
4c6807d2 403 $c->forward('check_message');
5a8ed4fe 404 }
fc7ec1d9 405
4c6807d2 406 sub check_message : Private {
5a8ed4fe 407 my ( $self, $c ) = @_;
408 return unless $c->stash->{message};
4c6807d2 409 $c->forward('show_message');
5a8ed4fe 410 }
fc7ec1d9 411
4c6807d2 412 sub show_message : Private {
5a8ed4fe 413 my ( $self, $c ) = @_;
414 $c->res->output( $c->stash->{message} );
415 }
cda8d1ac 416
72d9bfc7 417As 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.
cda8d1ac 418
419 $c->forward('/my/controller/action');
420 $c->forward('/default');
fc7ec1d9 421
422You can also forward to classes and methods.
423
e3dc9d78 424 sub hello : Global {
5a8ed4fe 425 my ( $self, $c ) = @_;
426 $c->forward(qw/MyApp::M::Hello say_hello/);
427 }
fc7ec1d9 428
e3dc9d78 429 sub bye : Global {
5a8ed4fe 430 my ( $self, $c ) = @_;
431 $c->forward('MyApp::M::Hello');
432 }
fc7ec1d9 433
434 package MyApp::M::Hello;
435
436 sub say_hello {
437 my ( $self, $c ) = @_;
438 $c->res->output('Hello World!');
439 }
440
441 sub process {
442 my ( $self, $c ) = @_;
443 $c->res->output('Goodbye World!');
444 }
445
cda8d1ac 446Note that C<forward> returns to the calling action and continues processing after the action finishes.
fc7ec1d9 447Catalyst will automatically try to call process() if you omit the method.
448
449=head3 Components
450
72d9bfc7 451Catalyst has an uncommonly flexible component system. You can define as many L<Models>, L<Views>, and L<Controllers> as you like.
fc7ec1d9 452
4a6895ce 453All 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 454
2feb6632 455 package MyApp::C::MyController;
fc7ec1d9 456
457 use strict;
458 use base 'Catalyst::Base';
459
460 __PACKAGE__->config( foo => 'bar' );
461
462 1;
463
72d9bfc7 464You 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.
fc7ec1d9 465
466=over 4
467
4a6895ce 468=item * B<MyApp/Model/>
fc7ec1d9 469
4a6895ce 470=item * B<MyApp/M/>
fc7ec1d9 471
4a6895ce 472=item * B<MyApp/View/>
fc7ec1d9 473
4a6895ce 474=item * B<MyApp/V/>
fc7ec1d9 475
4a6895ce 476=item * B<MyApp/Controller/>
fc7ec1d9 477
4a6895ce 478=item * B<MyApp/C/>
fc7ec1d9 479
480=back
481
482=head4 Views
483
484To 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:
485
486 package MyApp::V::TT;
487
488 use strict;
489 use base 'Catalyst::View::TT';
490
491 1;
492
493This 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/)>.
494
e3dc9d78 495 sub hello : Global {
5a8ed4fe 496 my ( $self, $c ) = @_;
497 $c->stash->{template} = 'hello.tt';
498 }
fc7ec1d9 499
5a8ed4fe 500 sub end : Private {
501 my ( $self, $c ) = @_;
2feb6632 502 $c->forward('MyApp::V::TT');
5a8ed4fe 503 }
fc7ec1d9 504
72d9bfc7 505You normally render templates at the end of a request, so it's a perfect use for the global C<end> action.
fc7ec1d9 506
72d9bfc7 507Also, 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. ;)
fc7ec1d9 508
509=head4 Models
510
511To show how to define models, again we'll use an already-existing base class, this time for L<Class::DBI>: L<Catalyst::Model::CDBI>.
512
513But first, we need a database.
514
515 -- myapp.sql
516 CREATE TABLE foo (
517 id INTEGER PRIMARY KEY,
518 data TEXT
519 );
520
521 CREATE TABLE bar (
522 id INTEGER PRIMARY KEY,
523 foo INTEGER REFERENCES foo,
524 data TEXT
525 );
526
527 INSERT INTO foo (data) VALUES ('TEST!');
528
529
530 % sqlite /tmp/myapp.db < myapp.sql
531
532Now we can create a CDBI component for this database.
533
534 package MyApp::M::CDBI;
535
536 use strict;
537 use base 'Catalyst::Model::CDBI';
538
539 __PACKAGE__->config(
540 dsn => 'dbi:SQLite:/tmp/myapp.db',
541 relationships => 1
542 );
543
544 1;
545
546Catalyst automatically loads table layouts and relationships. Use the stash to pass data to your templates.
547
548 package MyApp;
549
550 use strict;
551 use Catalyst '-Debug';
552
553 __PACKAGE__->config(
554 name => 'My Application',
555 root => '/home/joeuser/myapp/root'
556 );
cda8d1ac 557
558 __PACKAGE__->setup;
fc7ec1d9 559
5a8ed4fe 560 sub end : Private {
561 my ( $self, $c ) = @_;
562 $c->stash->{template} ||= 'index.tt';
563 $c->forward('MyApp::V::TT');
564 }
fc7ec1d9 565
e3dc9d78 566 sub view : Global {
5a8ed4fe 567 my ( $self, $c, $id ) = @_;
568 $c->stash->{item} = MyApp::M::CDBI::Foo->retrieve($id);
569 }
fc7ec1d9 570
571 1;
572
573 The id is [% item.data %]
574
575=head4 Controllers
576
72d9bfc7 577Multiple controllers are a good way to separate logical domains of your application.
fc7ec1d9 578
579 package MyApp::C::Login;
580
72d9bfc7 581 sign-in : Local { }
582 new-password : Local { }
583 sign-out : Local { }
fc7ec1d9 584
585 package MyApp::C::Catalog;
586
e3dc9d78 587 sub view : Local { }
588 sub list : Local { }
fc7ec1d9 589
590 package MyApp::C::Cart;
591
e3dc9d78 592 sub add : Local { }
593 sub update : Local { }
594 sub order : Local { }
fc7ec1d9 595
596=head3 Testing
597
72d9bfc7 598Catalyst 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.)
fc7ec1d9 599
600Start your application on the command line...
601
fd0b84fe 602 script/server.pl
fc7ec1d9 603
604...then visit http://localhost:3000/ in a browser to view the output.
605
606You can also do it all from the command line:
607
fd0b84fe 608 script/test.pl http://localhost/
fc7ec1d9 609
610Have fun!
611
3cb1db8c 612=head1 SUPPORT
613
614IRC:
615
616 Join #catalyst on irc.perl.org.
617
72d9bfc7 618Mailing-lists:
3cb1db8c 619
620 http://lists.rawmode.org/mailman/listinfo/catalyst
621 http://lists.rawmode.org/mailman/listinfo/catalyst-dev
622
fc7ec1d9 623=head1 AUTHOR
624
cda8d1ac 625Sebastian Riedel, C<sri@oook.de>
626David Naughton, C<naughton@umn.edu>
627Marcus Ramberg, C<mramberg@cpan.org>
f531dd37 628Jesse Sheidlower, C<jester@panix.com>
fc7ec1d9 629
630=head1 COPYRIGHT
631
632This program is free software, you can redistribute it and/or modify it under
633the same terms as Perl itself.