initial import of catalyst.
[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 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.
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 * Model
22
23 Access and modify content (data). L<Class::DBI>, L<Plucene>, L<Net::LDAP>...
24
25 =item * View
26
27 Present content to the user. L<Template Toolkit|Template>, L<Mason|HTML::Mason>...
28
29 =item * 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 * 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 * 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 * 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 you to put class and method names in your 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 * 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 * 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 * Component Auto-Discovery
79
80 No need to C<use> all of your components. Catalyst automatically finds and loads them.
81
82 =item * 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 * 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 * 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 My::App
105     $ cd My-App
106     $ bin/create controller My::Controller
107
108 =head3 Run
109
110     $ bin/server
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 * name
157
158 Name of your application.
159
160 =item * 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 $context->config->{$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 itself. Previously we called it $context for clarity, but most Catalyst developers just call it $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 kind of request specific informations 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::Reponse>
196
197     $c->response
198     $c->res # alias
199
200 The response is like the request but contais just response specific informations.
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 * 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 example:
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 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).
248
249 Catalyst supports several ways to define Actions:
250
251 =over 4
252
253 =item * Literal
254
255     $c->action( 'foo/bar' => sub { } );
256
257 Matches only http://localhost:3000/foo/bar.
258
259 =item * Regex
260
261     $c->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. Be sure to use ^ and $ if your action has arguments.
266
267 =item * Namespace-Prefixed
268
269     package MyApp::Controller::My::Controller; 
270     $c->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 * Private
277
278     $c->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 * !default 
295
296 Called when no other action matches.
297
298 =item * !begin
299
300 Called at the beginning of a request, before any matching actions are called.
301
302 =item * !end
303
304 Called at the end of a request, after all matching actions are called.
305
306 =item * !?default, !?begin and !?end
307
308 Like their equivalents above but used to overload them from Controllers.
309 So each Controller can have their own !?default, !?begin and !?end.
310
311 =back
312
313 =head3 Flow Control
314
315 Control the application flow with the C<forward> method, which accepts the key of an action to execute.
316
317     MyApp->action(
318
319         'hello' => sub {
320             my ( $self, $c ) = @_;
321             $c->stash->{message} = 'Hello World!';
322             $c->forward('!check-message');
323         },
324
325         '!check-message' => sub {
326             my ( $self, $c ) = @_;
327             return unless $c->stash->{message};
328             $c->forward('!show-message');
329         },
330
331         '!show-message' => sub {
332             my ( $self, $c ) = @_;
333             $c->res->output( $c->stash->{message} );
334         },
335
336     );
337
338 You can also forward to classes and methods.
339
340     MyApp->action(
341
342         'hello' => sub {
343             my ( $self, $c ) = @_;
344             $c->forward(qw/MyApp::M::Hello say_hello/);
345         },
346
347         'bye' => sub {
348             my ( $self, $c ) = @_;
349             $c->forward('MyApp::M::Hello');
350         },
351
352     );
353
354     package MyApp::M::Hello;
355
356     sub say_hello {
357         my ( $self, $c ) = @_;
358         $c->res->output('Hello World!');
359     }
360
361     sub process {
362         my ( $self, $c ) = @_;
363         $c->res->output('Goodbye World!');
364     }
365
366 Note that C<forward> returns after processing.
367 Catalyst will automatically try to call process() if you omit the method.
368
369 =head3 Components
370
371 Again, Catalyst has an uncommonly flexible component system. You can define as many L<Models>, L<Views> and Controllers as you like.
372
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).
374
375     package MyApp::Controller::MyController;
376
377     use strict;
378     use base 'Catalyst::Base';
379
380     __PACKAGE__->config( foo => 'bar' );
381
382     1;
383
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.
385
386 =over 4
387
388 =item * MyApp/Model/ 
389
390 =item * MyApp/M/
391
392 =item * MyApp/View/
393
394 =item * MyApp/V/
395
396 =item * MyApp/Controller/
397
398 =item * MyApp/C/
399
400 =back
401
402 =head4 Views
403
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:
405
406     package MyApp::V::TT;
407
408     use strict;
409     use base 'Catalyst::View::TT';
410
411     1;
412
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/)>.
414
415     MyApp->action(
416
417         'hello' => sub {
418             my ( $self, $c ) = @_;
419             $c->stash->{template} = 'hello.tt';
420         },
421
422         '!end' => sub {
423             my ( $self, $c ) = @_;
424             $c->forward('MyApp::View::TT');
425         },
426
427     );
428
429 You normally render templates at the end of a request, so it's a perfect use for the !end action.
430
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. ;)
432
433 =head4 Models
434
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>.
436
437 But first, we need a database.
438
439     -- myapp.sql
440     CREATE TABLE foo (
441         id INTEGER PRIMARY KEY,
442         data TEXT
443     );
444
445     CREATE TABLE bar (
446         id INTEGER PRIMARY KEY,
447         foo INTEGER REFERENCES foo,
448         data TEXT
449     );
450
451     INSERT INTO foo (data) VALUES ('TEST!');
452
453
454     % sqlite /tmp/myapp.db < myapp.sql
455
456 Now we can create a CDBI component for this database.
457
458     package MyApp::M::CDBI;
459
460     use strict;
461     use base 'Catalyst::Model::CDBI';
462
463     __PACKAGE__->config(
464         dsn           => 'dbi:SQLite:/tmp/myapp.db',
465         relationships => 1
466     );
467
468     1;
469
470 Catalyst automatically loads table layouts and relationships. Use the stash to pass data to your templates.
471
472     package MyApp;
473
474     use strict;
475     use Catalyst '-Debug';
476
477     __PACKAGE__->config(
478         name => 'My Application',
479         root => '/home/joeuser/myapp/root'
480     );
481
482     __PACKAGE__->action(
483
484         '!end' => sub {
485             my ( $self, $c ) = @_;
486             $c->stash->{template} ||= 'index.tt';
487             $c->forward('MyApp::V::TT');
488         },
489
490         'view' => sub {
491             my ( $self, $c, $id ) = @_;
492             $c->stash->{item} = MyApp::M::CDBI::Foo->retrieve($id);
493         }
494
495     );
496
497     1;
498
499     The id is [% item.data %]
500
501 =head4 Controllers
502
503 Multiple Controllers are a good way to separate logical domains of your application and distribute tasks to different programmers in a teams.
504
505     package MyApp::C::Login;
506
507     MyApp->action(
508         '?sign-in' => sub { },
509         '?new-password' => sub { },
510         '?sign-out' => sub { },
511     );
512
513     package MyApp::C::Catalog;
514
515     MyApp->action(
516         '?view' => sub { },
517         '?list' => sub { },
518     );
519
520     package MyApp::C::Cart;
521
522     MyApp->action(
523         '?add' => sub { },
524         '?update' => sub { },
525         '?order' => sub { },
526     );
527
528 =head3 Testing
529
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).
531
532 Start your application on the command line...
533
534     perl -I/home/joeuser/myapp/lib -MCatalyst::Test=MyApp -e1 3000
535
536 ...then visit http://localhost:3000/ in a browser to view the output.
537
538 You can also do it all from the command line:
539
540     perl -I/home/joeuser/myapp/lib -MCatalyst::Test=MyApp -e1 http://localhost/
541
542 Have fun!
543
544 =head1 AUTHOR
545
546 Sebastian Riedel, C<sri@oook.de> and David Naughton, C<naughton@umn.edu>
547
548 =head1 COPYRIGHT
549
550 This program is free software, you can redistribute it and/or modify it under
551 the same terms as Perl itself.