fixed pod reference
[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
8 Catalyst works and shows how to get a simple application up and running quickly.
9
10 =head2 What is Catalyst?
11
12 Catalyst is an elegant web application framework, extremely flexible yet
13 extremely simple. It's similar to Ruby on Rails, Spring (Java) and L<Maypole>,
14 upon which it was originally based.
15
16 =head3 MVC
17
18 Catalyst follows the Model-View-Controller (MVC) design pattern, allowing you to
19 easily separate concerns, like content, presentation, and flow control, into
20 separate modules. This separation allows you to modify code that handles one
21 concern without affecting code that handles the others. Catalyst promotes the
22 re-use of existing Perl modules that already handle common web application
23 concerns well.
24
25 Here's how the M, V, and C map to those concerns, with examples of well-known
26 Perl modules you may want to use for each.
27
28 =over 4
29
30 =item * B<Model>
31
32 Access and modify content (data). L<Class::DBI>, L<Plucene>, L<Net::LDAP>...
33
34 =item * B<View>
35
36 Present content to the user. L<Template Toolkit|Template>, L<Mason|HTML::Mason>,
37 L<HTML::Template>...
38
39 =item * B<Controller>
40
41 Control the whole request phase, check parameters, dispatch actions, flow
42 control. Catalyst!
43
44 =back
45
46 If you're unfamiliar with MVC and design patterns, you may want to check
47 out the original book on the subject, I<Design Patterns>, by Gamma,
48 Helm, Johnson, and Vlissides, also known as the Gang of Four (GoF). You
49 can also just Google it.  Many, many web application frameworks are
50 based on MVC, including all those listed above.
51
52 =head3 Flexibility
53
54 Catalyst is much more flexible than many other frameworks. We'll talk more about
55 this later, but rest assured you can use your favorite Perl modules with
56 Catalyst.
57
58 =over 4
59
60 =item * B<Multiple Models, Views, and Controllers>
61
62 To build a Catalyst application, you handle each type of concern inside special
63 modules called L</Components>. Often this code will be very simple, just calling
64 out to Perl modules like those listed above under L</MVC>. Catalyst handles
65 these components in a very flexible way. Use as many Models, Views, and
66 Controllers as you like, using as many different Perl modules as you like, all
67 in the same application. Want to manipulate multiple databases, and retrieve
68 some data via LDAP? No problem. Want to present data from the same Model using
69 L<Template Toolkit|Template> and L<PDF::Template>? Easy.
70
71 =item * B<Reuseable Components>
72
73 Not only does Catalyst promote the re-use of already existing Perl modules, it
74 also allows you to re-use your Catalyst components in multiple Catalyst
75 applications. 
76
77 =item * B<Unrestrained URL-to-Action Dispatching>
78
79 Catalyst allows you to dispatch any URLs to any application L<Actions>, even
80 through regular expressions! Unlike most other frameworks, it doesn't require
81 mod_rewrite or class and method names in URLs.
82
83 With Catalyst you register your actions and address them directly. For example:
84
85     sub hello : Global {
86         my ( $self, $context ) = @_;
87         $context->response->body('Hello World!');
88     }
89
90 Now http://localhost:3000/hello prints "Hello World!".
91
92 =item * B<Support for CGI, mod_perl, Apache::Request>
93
94 Use L<Catalyst::Engine::Apache> or L<Catalyst::Engine::CGI>.
95
96 =back
97
98 =head3 Simplicity
99
100 The best part is that Catalyst implements all this flexibility in a very simple
101 way.
102
103 =over 4
104
105 =item * B<Building Block Interface>
106
107 Components interoperate very smoothly. For example, Catalyst automatically makes
108 a L<Context> object available to every component. Via the context, you can
109 access the request object, share data between components, and control the flow
110 of your application. Building a Catalyst application feels a lot like snapping
111 together toy building blocks, and everything just works.
112
113 =item * B<Component Auto-Discovery>
114
115 No need to C<use> all of your components. Catalyst automatically finds and loads
116 them.
117
118 =item * B<Pre-Built Components for Popular Modules>
119
120 See L<Catalyst::Model::CDBI> for L<Class::DBI>, or L<Catalyst::View::TT> for
121 L<Template Toolkit|Template>. You can even get an instant web database front end
122 with L<Catalyst::Model::CDBI::CRUD>.
123
124 =item * B<Built-in Test Framework>
125
126 Catalyst comes with a built-in, lightweight http server and test framework,
127 making it easy to test applications from the command line.
128
129 =item * B<Helper Scripts>
130
131 Catalyst provides helper scripts to quickly generate running starter code for
132 components and unit tests.
133
134 =back
135
136 =head2 Quickstart
137
138 Here's how to install Catalyst and get a simple application up and running,
139 using the helper scripts described above.
140
141 =head3 Install
142
143     $ perl -MCPAN -e 'install Bundle::Catalyst'
144
145 =head3 Setup
146
147     $ catalyst.pl MyApp
148     # output omitted
149     $ cd MyApp
150     $ script/myapp_create.pl controller Library::Login
151
152 =head3 Run
153
154     $ script/myapp_server.pl
155
156 Now visit these locations with your favorite browser or user agent to see
157 Catalyst in action:
158
159 =over 4
160
161 =item http://localhost:3000/
162
163 =item http://localhost:3000/library/login/
164
165 =back
166
167 Dead easy!
168
169 =head2 How It Works
170
171 Let's see how Catalyst works, by taking a closer look at the components and
172 other parts of a Catalyst application.
173
174 =head3 Application Class
175
176 In addition to the Model, View, and Controller components, there's a single
177 class that represents your application itself. This is where you configure your
178 application, load plugins, define application-wide actions, and extend Catalyst.
179
180     package MyApp;
181
182     use strict;
183     use Catalyst qw/-Debug/;
184
185     MyApp->config(
186         name => 'My Application',
187
188         # You can put anything else you want in here:
189         my_configuration_variable => 'something',
190     );
191
192     sub default : Private {
193         my ( $self, $context ) = @_;
194         $context->response->body('Catalyst rockz!');
195     }
196
197     1;
198
199 For most applications, Catalyst requires you to define only one config
200 parameter:
201
202 =over 4
203
204 =item * B<name>
205
206 Name of your application.
207
208 =back
209
210 Optionally, you can specify a B<root> parameter for templates and static data.
211 If omitted, Catalyst will try to auto-detect the directory's location. You
212 can define as many parameters as you want for plugins or whatever you
213 need. You can access them anywhere in your application
214 via C<$context-E<gt>config-E<gt>{$param_name}>.
215
216 =head3 Context
217
218 Catalyst automatically blesses a Context object into your application class and
219 makes it available everywhere in your application. Use the Context to directly
220 interact with Catalyst and glue your L<Components> together. For example, if you
221 need to use the Context from within a Template Toolkit template, it's already
222 there:
223
224     <h1>Welcome to [% c.config.name %]!</h1>
225
226 As illustrated earlier in our URL-to-Action dispatching example, the Context is
227 always the second method parameter, behind the Component object reference or
228 class name itself. Previously we called it C<$context> for clarity, but most
229 Catalyst developers just call it C<$c>:
230
231     sub hello : Global {
232         my ( $self, $c ) = @_;
233         $c->res->body('Hello World!');
234     }
235
236 The Context contains several important objects:
237
238 =over 4
239
240 =item * L<Catalyst::Request>
241
242     $c->request
243     $c->req # alias
244
245 The request object contains all kinds of request-specific information, like
246 query parameters, cookies, uploads, headers, and more.
247
248     $c->req->params->{foo};
249     $c->req->cookies->{sessionid};
250     $c->req->headers->content_type;
251     $c->req->base;
252
253 =item * L<Catalyst::Response>
254
255     $c->response
256     $c->res # alias
257
258 The response is like the request, but contains just response-specific
259 information.
260
261     $c->res->body('Hello World');
262     $c->res->status(404);
263     $c->res->redirect('http://oook.de');
264
265 =item * L<Catalyst::Config>
266
267     $c->config
268
269     $c->config->root;
270     $c->config->name;
271
272 =item * L<Catalyst::Log>
273
274     $c->log
275
276     $c->log->debug('Something happened');
277     $c->log->info('Something you should know');
278
279 =item * B<Stash>
280
281     $c->stash
282
283     $c->stash->{foo} = 'bar';
284
285 =back
286
287 The last of these, the stash, is a universal hash for sharing data among
288 application components. For an example, we return to our 'hello' action:
289
290     sub hello : Global {
291         my ( $self, $c ) = @_;
292         $c->stash->{message} = 'Hello World!';
293         $c->forward('show_message');
294     }
295
296     sub show_message : Private {
297         my ( $self, $c ) = @_;
298         $c->res->body( $c->stash->{message} );
299     }
300
301 Note that the stash should be used only for passing data in an individual
302 request cycle; it gets cleared at a new request. If you need to maintain more
303 persistent data, use a session.
304
305 =head3 Actions
306
307 A Catalyst controller is defined by its actions. An action is a sub with a
308 special attribute. You've already seen some examples of actions in this
309 document. The URL (for example http://localhost.3000/foo/bar) consists of two
310 parts, the base (http://localhost:3000/ in this example) and the path (foo/bar).
311 Please note that the trailing slash after the hostname[:port] always belongs to
312 base and not to the action.
313
314 Catalyst supports several types of actions:
315
316 =over 4
317
318 =item * B<Literal>
319
320     package MyApp::C::My::Controller;
321     sub bar : Path('foo/bar') { }
322
323 Literal C<Path> actions will act relative to their current namespace. The above
324 example matches only http://localhost:3000/my/controller/foo/bar. If you start
325 your path with a forward slash, it will match from the root. Example:
326
327     package MyApp::C::My::Controller;
328     sub bar : Path('/foo/bar') { }
329
330 Matches only http://localhost:3000/foo/bar.
331
332     package MyApp::C::My::Controller;
333     sub bar : Path { }
334
335 By leaving the C<Path> definition empty, it will match on the namespace root.
336 The above code matches http://localhost:3000/my/controller.
337
338 =item * B<Regex>
339
340     sub bar : Regex('^item(\d+)/order(\d+)$') { }
341
342 Matches any URL that matches the pattern in the action key, e.g.
343 http://localhost:3000/item23/order42. The '' around the regexp is optional, but
344 perltidy likes it. :)
345
346 Regex matches act globally, i.e. without reference to the namespace from which
347 it is called, so that a C<bar> method in the
348 C<MyApp::Controller::Catalog::Order::Process> namespace won't match any form of
349 C<bar>, C<Catalog>, C<Order>, or C<Process> unless you explicitly put this in
350 the regex. To achieve the above, you should consider using a C<LocalRegex> action.
351
352 =item * B<LocalRegex>
353
354     sub bar : LocalRegex('^widget(\d+)$') { }
355
356 LocalRegex actions act locally. If you were to use C<bar> in
357 C<MyApp::Controller::Catalog>, the above example would match urls like
358 http://localhost:3000/catalog/widget23.
359
360 If you omit the "C<^>" from your regex, then it will match any depth from the
361 controller and not immediately off of the controller name. The following example
362 differes from the above code in that it will match
363 http://localhost:3000/catalog/foo/widget23 as well.
364
365     package MyApp::Controller::Catalog;
366     sub bar : LocalRegex('widget(\d+)$') { }
367
368 For both LocalRegex and Regex actions, if you use capturing parentheses to
369 extract values within the matching URL ("widget23" would capture "23" in the
370 above example), those values are available in the $c->req->snippets
371 array. If you want to pass arguments at the end of your URL, you must use regex
372 action keys. See L</URL Path Handling> below.
373
374 =item * B<Top-level>
375
376     package MyApp; 
377     sub foo : Global { }
378
379 Matches http://localhost:3000/foo. The function name is mapped directly
380 to the application base.
381
382 =item * B<Namespace-Prefixed>
383
384     package MyApp::C::My::Controller; 
385     sub foo : Local { }
386
387 Matches http://localhost:3000/my/controller/foo. 
388
389 This action type indicates that the matching URL must be prefixed with a
390 modified form of the component's class (package) name. This modified class name
391 excludes the parts that have a pre-defined meaning in Catalyst ("MyApp::C" in
392 the above example), replaces "::" with "/", and converts the name to lower case.
393 See L</Components> for a full explanation of the pre-defined meaning of Catalyst
394 component class names.
395
396 =item * B<Private>
397
398     sub foo : Private { }
399
400 Matches no URL, and cannot be executed by requesting a URL that corresponds to
401 the action key. Private actions can be executed only inside a Catalyst
402 application, by calling the C<forward> method:
403
404     $c->forward('foo');
405
406 See L</Flow Control> for a full explanation of C<forward>. Note that, as
407 discussed there, when forwarding from another component, you must use
408 the absolute path to the method, so that a private C<bar> method in your
409 C<MyApp::Controller::Catalog::Order::Process> controller must, if called
410 from elsewhere, be reached with
411 C<$c-E<gt>forward('/catalog/order/process/bar')>.
412
413 =back
414
415 B<Note:> After seeing these examples, you probably wonder what the point
416 is of defining names for regex and path actions. Actually, every public
417 action is also a private one, so you have one unified way of addressing
418 components in your C<forward>s.
419
420 =head4 Built-in Private Actions
421
422 In response to specific application states, Catalyst will automatically
423 call these built-in private actions in your application class:
424
425 =over 4
426
427 =item * B<default : Private>
428
429 Called when no other action matches. Could be used, for example, for
430 displaying a generic frontpage for the main app, or an error page for
431 individual controllers.
432
433 If C<default> isn't acting how you would expect, look at using a
434 L<Literal> C<Path> action (with an empty path string). The difference
435 being that C<Path> takes arguments relative from the namespace and
436 C<default> takes arguments relative from the root.
437
438 =item * B<index : Private>
439
440 C<index> is much like C<default> except that it takes no arguments
441 and it is weighted slightly higher in the matching process.
442
443 =item * B<begin : Private>
444
445 Called at the beginning of a request, before any matching actions are
446 called.
447
448 =item * B<end : Private>
449
450 Called at the end of a request, after all matching actions are called.
451
452 =back
453
454 =head4 Built-in actions in controllers/autochaining
455
456     Package MyApp::C::Foo;
457     sub begin : Private { }
458     sub default : Private { }
459     sub auto : Private { }
460
461 You can define built-in private actions within your controllers as
462 well. The actions will override the ones in less-specific controllers,
463 or your application class. In other words, for each of the three
464 built-in private actions, only one will be run in any request
465 cycle. Thus, if C<MyApp::C::Catalog::begin> exists, it will be run in
466 place of C<MyApp::begin> if you're in the C<catalog> namespace, and
467 C<MyApp::C::Catalog::Order::begin> would override this in turn.
468
469 In addition to the normal built-in actions, you have a special action
470 for making chains, C<auto>. Such C<auto> actions will be run after any
471 C<begin>, but before your action is processed. Unlike the other
472 built-ins, C<auto> actions I<do not> override each other; they will be
473 called in turn, starting with the application class and going through to
474 the I<most> specific class. I<This is the reverse of the order in which
475 the normal built-ins override each other>.
476
477 Here are some examples of the order in which the various built-ins
478 would be called:
479
480 =over 4
481
482 =item for a request for C</foo/foo>
483
484   MyApp::begin
485   MyApp::auto
486   MyApp::C::Foo::default # in the absence of MyApp::C::Foo::Foo
487   MyApp::end
488
489 =item for a request for C</foo/bar/foo>
490
491   MyApp::C::Foo::Bar::begin
492   MyApp::auto
493   MyApp::C::Foo::auto
494   MyApp::C::Foo::Bar::auto
495   MyApp::C::Foo::Bar::default # for MyApp::C::Foo::Bar::foo
496   MyApp::C::Foo::Bar::end
497
498 =back
499
500 The C<auto> action is also distinguished by the fact that you can break
501 out of the processing chain by returning 0. If an C<auto> action returns
502 0, any remaining actions will be skipped, except for C<end>. So, for the
503 request above, if the first auto returns false, the chain would look
504 like this:
505
506 =over 4
507
508 =item for a request for C</foo/bar/foo> where first C<auto> returns
509 false
510
511   MyApp::C::Foo::Bar::begin
512   MyApp::auto
513   MyApp::C::Foo::Bar::end
514
515 =back
516
517 An example of why one might use this is an authentication action: you
518 could set up a C<auto> action to handle authentication in your
519 application class (which will always be called first), and if
520 authentication fails, returning 0 would skip any remaining methods
521 for that URL.
522
523 B<Note:> Looking at it another way, C<auto> actions have to return a
524 true value to continue processing! You can also C<die> in the autochain
525 action; in that case, the request will go straight to the finalize
526 stage, without processing further actions.
527
528 =head4 URL Path Handling
529
530 You can pass variable arguments as part of the URL path. In this case,
531 you must use regex action keys with '^' and '$' anchors, and the
532 arguments must be separated with forward slashes (/) in the URL. For
533 example, suppose you want to handle C</foo/$bar/$baz>, where C<$bar> and
534 C<$baz> may vary:
535
536     sub foo : Regex('^foo$') { my ($self, $context, $bar, $baz) = @_; }
537
538 But what if you also defined actions for C</foo/boo> and C</foo/boo/hoo>?
539
540     sub boo : Path('foo/boo') { .. }
541     sub hoo : Path('foo/boo/hoo') { .. }
542
543 Catalyst matches actions in most specific to least specific order:
544
545     /foo/boo/hoo
546     /foo/boo
547     /foo # might be /foo/bar/baz but won't be /foo/boo/hoo
548
549 So Catalyst would never mistakenly dispatch the first two URLs to the
550 '^foo$' action.
551
552 =head4 Parameter Processing
553
554 Parameters passed in the URL query string are handled with methods in
555 the L<Catalyst::Request> class. The C<param> method is functionally
556 equivalent to the C<param> method of C<CGI.pm> and can be used in
557 modules that require this.
558
559     # http://localhost:3000/catalog/view/?category=hardware&page=3
560     my $category = $c->req->param('category');
561     my $current_page = $c->req->param('page') || 1;
562
563     # multiple values for single parameter name
564     my @values = $c->req->param('scrolling_list');          
565
566     # DFV requires a CGI.pm-like input hash
567     my $results = Data::FormValidator->check($c->req->params, \%dfv_profile);
568
569 =head3 Flow Control
570
571 You control the application flow with the C<forward> method, which
572 accepts the key of an action to execute. This can be an action in the
573 same or another Catalyst controller, or a Class name, optionally
574 followed by a method name. After a C<forward>, the control flow will
575 return to the method from which the C<forward> was issued.
576
577 A C<forward> is similar to a method call. The main differences are that
578 it wraps the call in an C<eval> to allow exception handling; it
579 automatically passes along the context object (C<$c> or C<$context>);
580 and it allows profiling of each call (displayed in the log with
581 debugging enabled).
582
583     sub hello : Global {
584         my ( $self, $c ) = @_;
585         $c->stash->{message} = 'Hello World!';
586         $c->forward('check_message'); # $c is automatically included
587     }
588
589     sub check_message : Private {
590         my ( $self, $c ) = @_;
591         return unless $c->stash->{message};
592         $c->forward('show_message');
593     }
594
595     sub show_message : Private {
596         my ( $self, $c ) = @_;
597         $c->res->body( $c->stash->{message} );
598     }
599
600 A C<forward> does not create a new request, so your request
601 object (C<$c-E<gt>req>) will remain unchanged. This is a
602 key difference between using C<forward> and issuing a
603 redirect.
604
605 You can pass new arguments to a C<forward> by adding them
606 in an anonymous array. In this case C<$c-E<gt>req-E<gt>args>
607 will be changed for the duration of the C<forward> only; upon
608 return, the original value of C<$c-E<gt>req-E<gt>args> will
609 be reset.
610
611     sub hello : Global {
612         my ( $self, $c ) = @_;
613         $c->stash->{message} = 'Hello World!';
614         $c->forward('check_message',[qw/test1/]);
615         # now $c->req->args is back to what it was before
616     }
617
618     sub check_message : Private {
619         my ( $self, $c ) = @_;
620         my $first_argument = $c->req->args[0]; # now = 'test1'
621         # do something...
622     }
623     
624 As you can see from these examples, you can just use the method name as
625 long as you are referring to methods in the same controller. If you want
626 to forward to a method in another controller, or the main application,
627 you will have to refer to the method by absolute path.
628
629   $c->forward('/my/controller/action');
630   $c->forward('/default'); # calls default in main application
631
632 Here are some examples of how to forward to classes and methods.
633
634     sub hello : Global {
635         my ( $self, $c ) = @_;
636         $c->forward(qw/MyApp::M::Hello say_hello/);
637     }
638
639     sub bye : Global {
640         my ( $self, $c ) = @_;
641         $c->forward('MyApp::M::Hello'); # no method: will try 'process'
642     }
643
644     package MyApp::M::Hello;
645
646     sub say_hello {
647         my ( $self, $c ) = @_;
648         $c->res->body('Hello World!');
649     }
650
651     sub process {
652         my ( $self, $c ) = @_;
653         $c->res->body('Goodbye World!');
654     }
655
656 Note that C<forward> returns to the calling action and continues
657 processing after the action finishes. If you want all further processing
658 in the calling action to stop, use C<detach> instead, which will execute
659 the C<detach>ed action and not return to the calling sub. In both cases,
660 Catalyst will automatically try to call process() if you omit the
661 method.
662
663 =head3 Components
664
665 Catalyst has an uncommonly flexible component system. You can define as many
666 L<Models>, L<Views>, and L<Controllers> as you like.
667
668 All components must inherit from L<Catalyst::Base>, which provides a simple
669 class structure and some common class methods like C<config> and C<new>
670 (constructor).
671
672     package MyApp::C::Catalog;
673
674     use strict;
675     use base 'Catalyst::Base';
676
677     __PACKAGE__->config( foo => 'bar' );
678
679     1;
680
681 You don't have to C<use> or otherwise register Models, Views, and
682 Controllers.  Catalyst automatically discovers and instantiates them
683 when you call C<setup> in the main application. All you need to do is
684 put them in directories named for each Component type. Notice that you
685 can use some very terse aliases for each one.
686
687 =over 4
688
689 =item * B<MyApp/Model/> 
690
691 =item * B<MyApp/M/>
692
693 =item * B<MyApp/View/>
694
695 =item * B<MyApp/V/>
696
697 =item * B<MyApp/Controller/>
698
699 =item * B<MyApp/C/>
700
701 =back
702
703 =head4 Views
704
705 To show how to define views, we'll use an already-existing base class for the
706 L<Template Toolkit|Template>, L<Catalyst::View::TT>. All we need to do is
707 inherit from this class:
708
709     package MyApp::V::TT;
710
711     use strict;
712     use base 'Catalyst::View::TT';
713
714     1;
715
716 (You can also generate this automatically by using the helper script:
717
718     script/myapp_create.pl view TT TT
719
720 where the first C<TT> tells the script that the name of the view should
721 be C<TT>, and the second that it should be a Template Toolkit view.)
722
723 This gives us a process() method and we can now just do
724 $c->forward('MyApp::V::TT') to render our templates. The base class makes
725 process() implicit, so we don't have to say C<$c-E<gt>forward(qw/MyApp::V::TT
726 process/)>.
727
728     sub hello : Global {
729         my ( $self, $c ) = @_;
730         $c->stash->{template} = 'hello.tt';
731     }
732
733     sub end : Private {
734         my ( $self, $c ) = @_;
735         $c->forward('MyApp::V::TT');
736     }
737
738 You normally render templates at the end of a request, so it's a perfect
739 use for the global C<end> action.
740
741 Also, be sure to put the template under the directory specified in
742 C<$c-E<gt>config-E<gt>{root}>, or you'll be forced to look at our
743 eyecandy debug screen. ;)
744
745 =head4 Models
746
747 To show how to define models, again we'll use an already-existing base class,
748 this time for L<Class::DBI>: L<Catalyst::Model::CDBI>.
749
750 But first, we need a database.
751
752     -- myapp.sql
753     CREATE TABLE foo (
754         id INTEGER PRIMARY KEY,
755         data TEXT
756     );
757
758     CREATE TABLE bar (
759         id INTEGER PRIMARY KEY,
760         foo INTEGER REFERENCES foo,
761         data TEXT
762     );
763
764     INSERT INTO foo (data) VALUES ('TEST!');
765
766
767     % sqlite /tmp/myapp.db < myapp.sql
768
769 Now we can create a CDBI component for this database.
770
771     package MyApp::M::CDBI;
772
773     use strict;
774     use base 'Catalyst::Model::CDBI';
775
776     __PACKAGE__->config(
777         dsn           => 'dbi:SQLite:/tmp/myapp.db',
778         relationships => 1
779     );
780
781     1;
782
783 Catalyst automatically loads table layouts and relationships. Use the stash to
784 pass data to your templates.
785
786     package MyApp;
787
788     use strict;
789     use Catalyst '-Debug';
790
791     __PACKAGE__->config(
792         name => 'My Application',
793         root => '/home/joeuser/myapp/root'
794     );
795     
796     __PACKAGE__->setup;
797
798     sub end : Private {
799         my ( $self, $c ) = @_;
800         $c->stash->{template} ||= 'index.tt';
801         $c->forward('MyApp::V::TT');
802     }
803
804     sub view : Global {
805         my ( $self, $c, $id ) = @_;
806         $c->stash->{item} = MyApp::M::CDBI::Foo->retrieve($id);
807     }
808
809     1;
810
811     # Then, in a TT template:
812     The id is [% item.data %]
813
814 Models do not have to be part of your Catalyst application; you
815 can always call an outside module that serves as your Model:
816
817     # in a Controller
818     sub list : Local {
819       my ( $self, $c ) = @_;
820       $c->stash->{template} = 'list.tt';
821       use Some::Outside::CDBI::Module;
822       my @records = Some::Outside::CDBI::Module->retrieve_all;
823       $c->stash->{records} = \@records;
824     }
825
826 But by using a Model that is part of your Catalyst application, you gain
827 several things: you don't have to C<use> each component, Catalyst will
828 find and load it automatically at compile-time; you can C<forward> to
829 the module, which can only be done to Catalyst components; and only
830 Catalyst components can be fetched with
831 C<$c-E<gt>comp('MyApp::M::SomeModel')>.
832
833 Happily, since many people have existing Model classes that they
834 would like to use with Catalyst (or, conversely, they want to
835 write Catalyst models that can be used outside of Catalyst, e.g.
836 in a cron job), it's trivial to write a simple component in
837 Catalyst that slurps in an outside Model:
838
839     package MyApp::M::Catalog;
840     use base qw/Catalyst::Base Some::Other::CDBI::Module::Catalog/;
841     1;
842
843 and that's it! Now C<Some::Other::CDBI::Module::Catalog> is part of your
844 Cat app as C<MyApp::M::Catalog>.
845
846 =head4 Controllers
847
848 Multiple controllers are a good way to separate logical domains of your
849 application.
850
851     package MyApp::C::Login;
852
853     sub sign-in : Local { }
854     sub new-password : Local { }
855     sub sign-out : Local { }
856
857     package MyApp::C::Catalog;
858
859     sub view : Local { }
860     sub list : Local { }
861
862     package MyApp::C::Cart;
863
864     sub add : Local { }
865     sub update : Local { }
866     sub order : Local { }
867
868 =head3 Testing
869
870 Catalyst has a built-in http server for testing! (Later, you can easily use a
871 more powerful server, e.g. Apache/mod_perl, in a production environment.)
872
873 Start your application on the command line...
874
875     script/myapp_server.pl
876
877 ...then visit http://localhost:3000/ in a browser to view the output.
878
879 You can also do it all from the command line:
880
881     script/myapp_test.pl http://localhost/
882
883 Have fun!
884
885 =head1 SUPPORT
886
887 IRC:
888
889     Join #catalyst on irc.perl.org.
890
891 Mailing-lists:
892
893     http://lists.rawmode.org/mailman/listinfo/catalyst
894     http://lists.rawmode.org/mailman/listinfo/catalyst-dev
895
896 =head1 AUTHOR
897
898 Sebastian Riedel, C<sri@oook.de> 
899 David Naughton, C<naughton@umn.edu>
900 Marcus Ramberg, C<mramberg@cpan.org>
901 Jesse Sheidlower, C<jester@panix.com>
902 Danijel Milicevic, C<me@danijel.de>
903
904 =head1 COPYRIGHT
905
906 This program is free software, you can redistribute it and/or modify it under
907 the same terms as Perl itself.