rename C::E::HTTP.pm to C::E::LWP.pm
[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 =over 4
75
76 =item * B<Building Block Interface>
77
78 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.
79
80 =item * B<Component Auto-Discovery>
81
82 No need to C<use> all of your components. Catalyst automatically finds and loads them.
83
84 =item * B<Pre-Built Components for Popular Modules>
85
86 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>.
87
88 =item * B<Builtin Test Framework>
89
90 Catalyst comes with a builtin, lightweight http server and test framework, making it easy to test applications from the command line.
91
92 =item * B<Helper Scripts>
93
94 Catalyst provides helper scripts to quickly generate running starter code for components and unit tests.
95
96 =back
97
98 =head2 Quickstart
99
100 Here'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
108     $ catalyst.pl My::App
109     $ cd My-App
110     $ script/create.pl controller My::Controller
111
112 =head3 Run
113
114     $ script/server.pl
115
116 Now 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
126 Dead easy!
127
128 =head2 How It Works
129
130 Let'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
134 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.
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
149     MyApp->action( '!default' => sub {
150         my ( $self, $context ) = @_;
151         $context->response->output('Catalyst rockz!');
152     });
153
154     1;
155
156 For most applications, Catalyst requires you to define only two config parameters:
157
158 =over 4
159
160 =item * B<name>
161
162 Name of your application.
163
164 =item * B<root>
165
166 Path to additional files like templates, images or other static data.
167
168 =back
169
170 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}>.
171
172 =head3 Context
173
174 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. 
175
176 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>:
177
178     MyApp->action( 'hello' => sub {
179         my ( $self, $c ) = @_;
180         $c->res->output('Hello World!');
181     });
182
183 The Context contains several important objects:
184
185 =over 4
186
187 =item * L<Catalyst::Request>
188
189     $c->request
190     $c->req # alias
191
192 The request contains all kinds of request-specific information, like query parameters, cookies, uploads, headers and more.
193
194     $c->req->params->{foo};
195     $c->req->cookies->{sessionid};
196     $c->req->headers->content_type;
197     $c->req->base;
198
199 =item * L<Catalyst::Response>
200
201     $c->response
202     $c->res # alias
203
204 The response is like the request, but contains just response-specific information.
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
224 =item * B<Stash>
225
226     $c->stash
227
228     $c->stash->{foo} = 'bar';
229
230 =back
231
232 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:
233
234     MyApp->action(
235
236         'hello' => sub {
237             my ( $self, $c ) = @_;
238             $c->stash->{message} = 'Hello World!';
239             $c->forward('!show-message');
240         },
241
242         '!show-message' => sub {
243             my ( $self, $c ) = @_;
244             $c->res->output( $c->stash->{message} );
245         },
246
247     );
248
249 =head3 Actions
250
251 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).
252
253 Catalyst supports several ways to define Actions:
254
255 =over 4
256
257 =item * B<Literal>
258
259     MyApp->action( 'foo/bar' => sub { } );
260
261 Matches only http://localhost:3000/foo/bar.
262
263 =item * B<Regex>
264
265     MyApp->action( '/^foo(\d+)/bar(\d+)$/' => sub { } );
266
267 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/'.
268
269 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.
270
271 =item * B<Namespace-Prefixed>
272
273     package MyApp::Controller::My::Controller; 
274     MyApp->action( '?foo' => sub { } );
275
276 Matches http://localhost:3000/my_controller/foo. The action key must be prefixed with '?'.
277
278 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.
279
280 =item * B<Private>
281
282     MyApp->action( '!foo' => sub { } );
283
284 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:
285
286     $c->forward('!foo');
287
288 See L</Flow Control> for a full explanation of C<forward>.
289
290 =back
291
292 =head4 Builtin Private Actions
293
294 In response to specific application states, Catalyst will automatically call these built in private actions:
295
296 =over 4
297
298 =item * B<!default>
299
300 Called when no other action matches.
301
302 =item * B<!begin>
303
304 Called at the beginning of a request, before any matching actions are called.
305
306 =item * B<!end>
307
308 =back
309
310 Called at the end of a request, after all matching actions are called.
311
312 =head4 B<Namespace-Prefixed Private Actions>
313
314     MyApp->action( '!?foo' => sub { } );
315     MyApp->action( '!?default' => sub { } );
316
317 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.
318
319 =head4 B<URL Argument Handling>
320
321 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:
322
323     MyApp->action( '/^foo$/' => sub { my ($self, $context, $bar, $baz) = @_; } ); 
324
325 But what if you also defined actions for /foo/boo and /foo/boo/hoo ?
326
327     MyApp->action( '/foo/boo' => sub { .. } );
328     MyApp->action( '/foo/boo/hoo' => sub { .. } );
329
330 Catalyst matches actions in most specific to least specific order:
331
332     /foo/boo/hoo
333     /foo/boo
334     /foo # might be /foo/bar/baz
335
336 So Catalyst would never mistakenly dispatch the first two URLs to the '/^foo$/' action.
337
338 =head3 Flow Control
339
340 Control the application flow with the C<forward> method, which accepts the key of an action to execute.
341
342     MyApp->action(
343
344         'hello' => sub {
345             my ( $self, $c ) = @_;
346             $c->stash->{message} = 'Hello World!';
347             $c->forward('!check-message');
348         },
349
350         '!check-message' => sub {
351             my ( $self, $c ) = @_;
352             return unless $c->stash->{message};
353             $c->forward('!show-message');
354         },
355
356         '!show-message' => sub {
357             my ( $self, $c ) = @_;
358             $c->res->output( $c->stash->{message} );
359         },
360
361     );
362
363 You can also forward to classes and methods.
364
365     MyApp->action(
366
367         'hello' => sub {
368             my ( $self, $c ) = @_;
369             $c->forward(qw/MyApp::M::Hello say_hello/);
370         },
371
372         'bye' => sub {
373             my ( $self, $c ) = @_;
374             $c->forward('MyApp::M::Hello');
375         },
376
377     );
378
379     package MyApp::M::Hello;
380
381     sub say_hello {
382         my ( $self, $c ) = @_;
383         $c->res->output('Hello World!');
384     }
385
386     sub process {
387         my ( $self, $c ) = @_;
388         $c->res->output('Goodbye World!');
389     }
390
391 Note that C<forward> returns after processing.
392 Catalyst will automatically try to call process() if you omit the method.
393
394 =head3 Components
395
396 Again, Catalyst has an uncommonly flexible component system. You can define as many L<Models>, L<Views> and L<Controllers> as you like.
397
398 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).
399
400     package MyApp::Controller::MyController;
401
402     use strict;
403     use base 'Catalyst::Base';
404
405     __PACKAGE__->config( foo => 'bar' );
406
407     1;
408
409 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.
410
411 =over 4
412
413 =item * B<MyApp/Model/> 
414
415 =item * B<MyApp/M/>
416
417 =item * B<MyApp/View/>
418
419 =item * B<MyApp/V/>
420
421 =item * B<MyApp/Controller/>
422
423 =item * B<MyApp/C/>
424
425 =back
426
427 =head4 Views
428
429 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:
430
431     package MyApp::V::TT;
432
433     use strict;
434     use base 'Catalyst::View::TT';
435
436     1;
437
438 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/)>.
439
440     MyApp->action(
441
442         'hello' => sub {
443             my ( $self, $c ) = @_;
444             $c->stash->{template} = 'hello.tt';
445         },
446
447         '!end' => sub {
448             my ( $self, $c ) = @_;
449             $c->forward('MyApp::View::TT');
450         },
451
452     );
453
454 You normally render templates at the end of a request, so it's a perfect use for the !end action.
455
456 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. ;)
457
458 =head4 Models
459
460 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>.
461
462 But first, we need a database.
463
464     -- myapp.sql
465     CREATE TABLE foo (
466         id INTEGER PRIMARY KEY,
467         data TEXT
468     );
469
470     CREATE TABLE bar (
471         id INTEGER PRIMARY KEY,
472         foo INTEGER REFERENCES foo,
473         data TEXT
474     );
475
476     INSERT INTO foo (data) VALUES ('TEST!');
477
478
479     % sqlite /tmp/myapp.db < myapp.sql
480
481 Now we can create a CDBI component for this database.
482
483     package MyApp::M::CDBI;
484
485     use strict;
486     use base 'Catalyst::Model::CDBI';
487
488     __PACKAGE__->config(
489         dsn           => 'dbi:SQLite:/tmp/myapp.db',
490         relationships => 1
491     );
492
493     1;
494
495 Catalyst automatically loads table layouts and relationships. Use the stash to pass data to your templates.
496
497     package MyApp;
498
499     use strict;
500     use Catalyst '-Debug';
501
502     __PACKAGE__->config(
503         name => 'My Application',
504         root => '/home/joeuser/myapp/root'
505     );
506
507     __PACKAGE__->action(
508
509         '!end' => sub {
510             my ( $self, $c ) = @_;
511             $c->stash->{template} ||= 'index.tt';
512             $c->forward('MyApp::V::TT');
513         },
514
515         'view' => sub {
516             my ( $self, $c, $id ) = @_;
517             $c->stash->{item} = MyApp::M::CDBI::Foo->retrieve($id);
518         }
519
520     );
521
522     1;
523
524     The id is [% item.data %]
525
526 =head4 Controllers
527
528 Multiple Controllers are a good way to separate logical domains of your application.
529
530     package MyApp::C::Login;
531
532     MyApp->action(
533         '?sign-in' => sub { },
534         '?new-password' => sub { },
535         '?sign-out' => sub { },
536     );
537
538     package MyApp::C::Catalog;
539
540     MyApp->action(
541         '?view' => sub { },
542         '?list' => sub { },
543     );
544
545     package MyApp::C::Cart;
546
547     MyApp->action(
548         '?add' => sub { },
549         '?update' => sub { },
550         '?order' => sub { },
551     );
552
553 =head3 Testing
554
555 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).
556
557 Start your application on the command line...
558
559     script/server.pl
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 Have fun!
568
569 =head1 SUPPORT
570
571 IRC:
572
573     Join #catalyst on irc.perl.org.
574
575 Mailing-Lists:
576
577     http://lists.rawmode.org/mailman/listinfo/catalyst
578     http://lists.rawmode.org/mailman/listinfo/catalyst-dev
579
580 =head1 AUTHOR
581
582 Sebastian Riedel, C<sri@oook.de> and David Naughton, C<naughton@umn.edu>
583
584 =head1 COPYRIGHT
585
586 This program is free software, you can redistribute it and/or modify it under
587 the same terms as Perl itself.