15f6ee8875a783f7061f4322bc0ffdd236b3be4c
[catagits/Catalyst-Runtime.git] / lib / Catalyst / Manual / Intro.pod
1 =head1 NAME
2
3 Catalyst::Manual::Intro - Introduction to Catalyst
4
5 =head1 DESCRIPTION
6
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.
8
9 =head2 What is Catalyst?
10
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.
12
13 =head3 MVC
14
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 re-use of existing Perl modules that already handle common web application concerns well.
16
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.
18
19 =over 4
20
21 =item * B<Model>
22
23 Access and modify content (data). L<Class::DBI>, L<Plucene>, L<Net::LDAP>...
24
25 =item * B<View>
26
27 Present content to the user. L<Template Toolkit|Template>, L<Mason|HTML::Mason>...
28
29 =item * B<Controller>
30
31 Control the whole request phase, check parameters, dispatch actions, flow control. Catalyst!
32
33 =back
34
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.
36
37 =head3 Flexibility
38
39 Catalyst is much more flexible than many other frameworks.
40
41 =over 4
42
43 =item * B<Multiple Models, Views and Controllers>
44
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.
46
47 =item * B<Re-Useable Components>
48
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.
50
51 =item * B<Unrestrained URL-to-Action Dispatching>
52
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 mod_rewrite or class and method names in URLs.
54
55 With 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
62 Now http://localhost:3000/hello prints "Hello World!".
63
64 =item * B<Support for CGI, mod_perl, Apache::Request>
65
66 Use L<Catalyst::Engine::Apache> or L<Catalyst::Engine::CGI>.
67
68 =back
69
70 =head3 Simplicity
71
72 The best part is that Catalyst implements all this flexibility in a very simple way.
73
74 =item * B<Building Block Interface>
75
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.
77
78 =item * B<Component Auto-Discovery>
79
80 No need to C<use> all of your components. Catalyst automatically finds and loads them.
81
82 =item * B<Pre-Built Components for Popular Modules>
83
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>.
85
86 =item * B<Builtin Test Framework>
87
88 Catalyst comes with a builtin, lightweight http server and test framework, making it easy to test applications from the command line.
89
90 =item * B<Helper Scripts>
91
92 Catalyst provides helper scripts to quickly generate running starter code for components and unit tests.
93
94 =head2 Quickstart
95
96 Here'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
104     $ catalyst.pl My::App
105     $ cd My-App
106     $ script/create.pl controller My::Controller
107
108 =head3 Run
109
110     $ script/server.pl
111
112 Now 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
122 Dead easy!
123
124 =head2 How It Works
125
126 Let'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
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.
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
152 For most applications, Catalyst requires you to define only two config parameters:
153
154 =over 4
155
156 =item * B<name>
157
158 Name of your application.
159
160 =item * B<root>
161
162 Path to additional files like templates, images or other static data.
163
164 =back
165
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 C<$context-E<gt>config-E<gt>{$param_name}>.
167
168 =head3 Context
169
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. 
171
172 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>:
173
174     MyApp->action( 'hello' => sub {
175         my ( $self, $c ) = @_;
176         $c->res->output('Hello World!');
177     });
178
179 The Context contains several important objects:
180
181 =over 4
182
183 =item * L<Catalyst::Request>
184
185     $c->request
186     $c->req # alias
187
188 The request contains all kinds of request-specific information, like query parameters, cookies, uploads, headers and more.
189
190     $c->req->params->{foo};
191     $c->req->cookies->{sessionid};
192     $c->req->headers->content_type;
193     $c->req->base;
194
195 =item * L<Catalyst::Response>
196
197     $c->response
198     $c->res # alias
199
200 The response is like the request, but contains just response-specific information.
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
220 =item * B<Stash>
221
222     $c->stash
223
224     $c->stash->{foo} = 'bar';
225
226 =back
227
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:
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
247 To 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).
248
249 Catalyst supports several ways to define Actions:
250
251 =over 4
252
253 =item * B<Literal>
254
255     MyApp->action( 'foo/bar' => sub { } );
256
257 Matches only http://localhost:3000/foo/bar.
258
259 =item * B<Regex>
260
261     MyApp->action( '/^foo(\d+)/bar(\d+)$/' => sub { } );
262
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/'.
264
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. If you want to pass arguments at the end of your URL, you must use regex action keys. See L</URL Argument Handling> below.
266
267 =item * B<Namespace-Prefixed>
268
269     package MyApp::Controller::My::Controller; 
270     MyApp->action( '?foo' => sub { } );
271
272 Matches http://localhost:3000/my_controller/foo. The action key must be prefixed with '?'.
273
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.
275
276 =item * B<Private>
277
278     MyApp->action( '!foo' => sub { } );
279
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:
281
282     $c->forward('!foo');
283
284 See L</Flow Control> for a full explanation of C<forward>.
285
286 =back
287
288 =head4 Builtin Private Actions
289
290 In response to specific application states, Catalyst will automatically call these built in private actions:
291
292 =over 4
293
294 =item * B<!default>
295
296 Called when no other action matches.
297
298 =item * B<!begin>
299
300 Called at the beginning of a request, before any matching actions are called.
301
302 =item * B<!end>
303
304 =back
305
306 Called at the end of a request, after all matching actions are called.
307
308 =head4 B<Namespace-Prefixed Private Actions>
309
310     MyApp->action( '!?foo' => sub { } );
311     MyApp->action( '!?default' => sub { } );
312
313 The 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
317 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:
318
319     MyApp->action( '/^foo$/' => sub { my ($self, $context, $bar, $baz) = @_; } ); 
320
321 But 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
326 Catalyst 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
332 So Catalyst would never mistakenly dispatch the first two URLs to the '/^foo$/' action.
333
334 =head3 Flow Control
335
336 Control 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
359 You 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
387 Note that C<forward> returns after processing.
388 Catalyst will automatically try to call process() if you omit the method.
389
390 =head3 Components
391
392 Again, Catalyst has an uncommonly flexible component system. You can define as many L<Models>, L<Views> and L<Controllers> as you like.
393
394 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).
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
405 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.
406
407 =over 4
408
409 =item * B<MyApp/Model/> 
410
411 =item * B<MyApp/M/>
412
413 =item * B<MyApp/View/>
414
415 =item * B<MyApp/V/>
416
417 =item * B<MyApp/Controller/>
418
419 =item * B<MyApp/C/>
420
421 =back
422
423 =head4 Views
424
425 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:
426
427     package MyApp::V::TT;
428
429     use strict;
430     use base 'Catalyst::View::TT';
431
432     1;
433
434 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/)>.
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
450 You normally render templates at the end of a request, so it's a perfect use for the !end action.
451
452 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. ;)
453
454 =head4 Models
455
456 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>.
457
458 But 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
477 Now 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
491 Catalyst 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
524 Multiple Controllers are a good way to separate logical domains of your application.
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
551 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).
552
553 Start your application on the command line...
554
555     script/server.pl
556
557 or
558
559     perl -I/home/joeuser/myapp/lib -MCatalyst::Test=MyApp -e1 3000
560
561 ...then visit http://localhost:3000/ in a browser to view the output.
562
563 You can also do it all from the command line:
564
565     script/test.pl http://localhost/
566
567 or
568
569     perl -I/home/joeuser/myapp/lib -MCatalyst::Test=MyApp -e1 http://localhost/
570
571 Have fun!
572
573 =head1 SUPPORT
574
575 IRC:
576
577     Join #catalyst on irc.perl.org.
578
579 Mailing-Lists:
580
581     http://lists.rawmode.org/mailman/listinfo/catalyst
582     http://lists.rawmode.org/mailman/listinfo/catalyst-dev
583
584 =head1 AUTHOR
585
586 Sebastian Riedel, C<sri@oook.de> and David Naughton, C<naughton@umn.edu>
587
588 =head1 COPYRIGHT
589
590 This program is free software, you can redistribute it and/or modify it under
591 the same terms as Perl itself.