apply docs patch from Carl Franks (thanks!) with a couple minor changes
[catagits/Catalyst-Runtime.git] / lib / Catalyst / Manual / Tutorial.pod
1 =head1 NAME
2
3 Catalyst::Manual::Tutorial - Getting started with Catalyst
4
5 =head1 DESCRIPTION
6
7 This document aims to get you up and running with Catalyst.
8
9 =head2 Installation
10
11 The first step is to install Catalyst, and the simplest way to do this 
12 is to install the Catalyst bundle from CPAN:
13
14     $ perl -MCPAN -e 'install Task::Catalyst'
15
16 This will retrieve Catalyst and a number of useful extensions and 
17 install them for you. This process might not be totally painless
18 though, and you might want to look at CatInABox 
19 L<http://use.perl.org/~jk2addict/journal/28071>, especially if you are
20 on a system that lacks a compiler.
21
22
23 =head2 The very basics - Setting up the skeleton application.
24
25 Catalyst includes a helper script, C<catalyst.pl>, that will set up a 
26 skeleton application for you:
27
28     $ catalyst tutorial
29
30     created "tutorial"
31     created "tutorial/script"
32     ... output snipped
33     created "tutorial/script/tutorial_create.pl"
34
35 This creates the directory structure, populated with skeleton 
36 files.
37
38 =head2 Testing out the skeleton application
39
40 You can test out your new application by running the server script that
41 Catalyst provides:
42
43     $ cd tutorial
44     $ script/tutorial_server.pl 
45
46     [...] [catalyst] [debug] Debug messages enabled
47     [...] [catalyst] [debug] Loaded plugins:
48     .------------------------------------------------------------------------------.
49     | Catalyst::Plugin::Static::Simple                                             |
50     '------------------------------------------------------------------------------'
51     [...] [catalyst] [debug] Loaded dispatcher "Catalyst::Dispatcher"
52     [...] [catalyst] [debug] Loaded engine "Catalyst::Engine::HTTP"
53     [...] [catalyst] [debug] Found home "/home/users/me/tutorial"
54     [...] [catalyst] [debug] Loaded Private actions:
55     .--------------------------------------+---------------------------------------.
56     | Private                              | Class                                 |
57     +--------------------------------------+---------------------------------------+
58     | /default                             | tutorial                              |
59     '--------------------------------------+---------------------------------------'
60
61     [...] [catalyst] [info] tutorial powered by Catalyst 5.66
62     You can connect to your server at http://localhost:3000
63
64 (Note that each line logged by Catalyst begins with a timestamp, which has
65 been replaced here with "C<...>" so that the text fits onto the lines.)
66
67 The server is now waiting for you to make requests of it.  Try using 
68 telnet to manually make a simple GET request of the server (when 
69 telnet responds with "Escape character is '^]'.", type "GET / HTTP/1.0"
70 and hit return twice):
71
72     $ telnet localhost 3000
73     Trying 127.0.0.1...
74     Connected to localhost.
75     Escape character is '^]'.
76     GET / HTTP/1.0
77
78     HTTP/1.0 200 OK
79     Date: Mon, 07 Nov 2005 14:57:39 GMT
80     Content-Length: 5525
81     Content-Type: text/html; charset=utf-8
82     Status: 200
83     X-Catalyst: 5.66
84
85     [...]
86     Connection closed by foreign host.
87     $
88
89 You can see the full welcome message by visiting
90 http://localhost:3000/ with your browser.
91
92 More trace messages will appear in the original terminal window:
93
94     [...] [catalyst] [debug] **********************************
95     [...] [catalyst] [debug] * Request 1 (0.063/s) [2148]
96     [...] [catalyst] [debug] **********************************
97     [...] [catalyst] [debug] Arguments are ""
98     [...] [catalyst] [debug] "GET" request for "" from localhost
99     [...] [catalyst] [info] Request took 0.046883s (21.330/s)
100     .------------------------------------------------------------------+-----------.
101     | Action                                                           | Time      |
102     +------------------------------------------------------------------+-----------+
103     | /default                                                         | 0.000000s |
104     '------------------------------------------------------------------+-----------'
105
106 The server will continue running until you interrupt it.
107
108 The application can also be tested from the command line using the generated
109 helper script, C<script/tutorial_test.pl>.
110
111 =head2 Getting started
112
113 So you picked Catalyst. Good choice. I assume you have installed it as
114 well. For this tutorial you will also need the following modules:
115
116 L<Catalyst::Plugin::Session>
117
118 L<Catalyst::Plugin::Session::Store::File>
119
120 L<Catalyst::Plugin::Session::State::Cookie>
121
122 L<Catalyst::Plugin::Authentication>
123
124 L<Catalyst::Plugin::Authentication::Store::Minimal>
125
126 L<Catalyst::Plugin::Authentication::::Minimal>
127
128 L<Catalyst::Plugin::Authentication::Credential::Password>
129
130 L<Catalyst::Plugin::Authorization::Roles>
131
132 L<DBD::SQLite>
133
134 ...
135
136 If you have not already done this following the example above, then to get 
137 started all you need to do is type:
138
139     catalyst.pl tutorial
140
141 =for commentary
142 Poor choice of application name - searching for "tutorial" in the docs
143 also results in discussion of the tutorial process, which is probably
144 not what the reader wants.
145
146 =cut
147
148 This should create a directory called F<tutorial> and fill it with the
149 default (standard) Catalyst installation. Change to this directory
150 because we will be running all further commands from inside the
151 F<tutorial> directory.
152
153 If you now run the built-in mini-server with:
154     
155     script/tutorial_server.pl
156
157 it will show some standard debug messages in the console screen 
158 (more about those in a minute), and then inform you that you can now 
159 connect to the test server on port 3000. Point your browser at 
160 http://localhost:3000/ to see the built-in catalyst welcome screen.
161
162 The other important thing B<catalyst.pl> did was create your root
163 controller. This file is a standard perl module like all the other
164 controllers that you might add to your application. It lives in the
165 F<lib/> directory, and will have the same name as you supplied to the
166 command above. In our case it is F<tutorial.pm>. Alongside this file is
167 a directory of the same name, which is the top level namespace for the
168 entire application. Thus every other module we create will be
169 "tutorial::something";
170
171 The root controller is used to load plugins, to configure the
172 application and its plugins, and for generic private actions.  We will
173 explain more about those later.
174
175 =head2 Debugging
176
177 The simplest way to debug your Catalyst application is to run it using
178 the built-in mini-server as described in L<Getting started>. 
179
180 If you want to output any debugging information to the console, then
181 call C<< $c->log->debug() >>, passing it a string to output. For
182 data structures, use L<Data::Dumper> and call C<<
183 $c->log->debug(Dumper($structure)) >>
184
185 =head2 Model/View/Controller
186
187 The recommended method for code organization in a Catalyst application
188 is known as the "Model View Controller" design pattern (also referred to
189 "MVC". See L<http://en.wikipedia.org/wiki/Model-view-controller>). 
190
191 The point of the MVC pattern is to divorce the dependencies of
192 parts of the application from each other, and give them standard
193 interfaces. Following this theory of organization should give your code
194 all the benefits of modularity. The main benefits are interchangeability
195 of parts and reusable code.
196
197 Thus you could replace your file data storage with a database or your
198 Oracle database with a MySQL database and not have to change any of your
199 controlling or view logic. Or you could later decide to output
200 information from your application as RSS instead of HTML just by adding
201 a new view module.
202
203 =head3 Model
204
205 Models deal with the storage of data. For a complex website, you may
206 need multiple varied data sources, each will have it's own model class
207 that provides an abstracted interface to it. In this tutorial we are
208 going to be using a simple database.
209
210 =head3 View
211
212 Views are used to display information to the user. In a web framework,
213 it is generally used to output HTML to the browser. As mentioned
214 previously, views can also be used to output RSS or any other kind of
215 data format.  One easy way to do this with Catalyst is to use a
216 templating system such as Template Toolkit. If outputting HTML is all
217 you are going to do, then you will probably only need one view.
218
219 =head3 Controller
220
221 A controller deals with reacting to user choices, and thus controls what
222 the application does. Since this is a web framework, Catalyst
223 controllers are frequently used to react directly to URLs requested by
224 the user. This tutorial will describe the simplest way of using
225 controllers, where each path or part of a path is assigned its own
226 action (or subroutine). More complex controlling mechanisms will be
227 mentioned briefly, and can be read about in detail in the manual.
228
229
230 =head2 Controlling
231
232 Now lets write our first bit of application code. First, we would like
233 our application to greet our users. We'll assume for now that our users
234 will be sent to the I<users/greet> URL. To create a controller that
235 serves the I<users> namespace, we run the following command in our
236 F<tutorial> directory:
237
238     script/tutorial_create.pl controller Users
239
240 This will create a Users.pm in F<lib/tutorial/Controller>. Open this
241 file in an editor and take a look. You will notice there is some
242 commented out code which we will ignore for now. To make something
243 happen when our URL is visited, we will write a "greet" action which
244 looks like this:
245
246   sub greet : Local {
247     my ($self, $c) = @_;
248
249     my $name = $c->req->param('name');
250     $c->log->debug("Got name: $name\n");
251
252     if ($c->req->method eq 'POST') {
253        if(!$name) {
254             $c->stash->{message} = 'Please fill in a name!';
255         }
256         else {
257             $c->stash->{message} = "Hello $name!";     
258         }
259     }
260     $c->stash->{template} = 'greet.tt';
261   }
262
263 Whew! So, what does all this do? Lets take it one step at a time.
264 The subroutine declaration gives the action a name.  To the right of the
265 name there is an attribute type that looks like this:   
266
267     : Local 
268     
269 That defines which URIs will translate to this action. "Local", matches
270 exactly one URI: 
271
272     /users/greet
273     
274 The URI matched by "Local" is composed from the namespace minus the 
275 tutorial::controller portion, that is common to all controllers, 
276 and the action name itself.  Because it is a URI, we use forward slashes 
277 instead of double colons.  So, in summary, when a user requests:
278  
279     http://localhost:3000/users/greet
280     
281 the "greet" action defined above in the Users controller will be executed.
282
283 The second line retrieves the parameters Catalyst gives us when it calls
284 our method. The first is the instance of our Users class, and the second
285 is commonly called the context, and named $c.  From now on, whenever we 
286 are talking about the context object, it will be represented as $c in 
287 the code.
288
289 The context is the magical object containing any information you need from 
290 catalyst, or want to send to it, and is passed from action to action. 
291 You will see it used frequently in Catalyst applications, and a list of all 
292 its methods is available in the L<Catalyst> POD.
293
294 On the third line we use the ->param method of the context's request object
295 to retrieve one of the query parameters, just like in L<CGI>.
296
297 On the fourth, we make a debug output of this object on the server console,
298 or the error log if running under CGI or mod_perl.
299
300 Next, if we have a post request, we check if the name field contains anything 
301 (or is "true"), if it isn't, we assign an error message to a "message" field 
302 in the stash. The stash is yet another method of the context object, it allows 
303 us to pass data on to other methods we call later, most usefully the View 
304 modules.
305
306 If the username did contain a value, then we just set our message to
307 greet the user by name.
308
309 Finally, we set the special "template" variable in the stash to the name
310 of the template we want our view to use to display this page.
311
312 =head2 Viewing
313
314 Ok, so reacting and checking the users data is all fine, but how do we
315 actually display the page/form in the first place, and our results? As
316 previously mentioned, we'll use Template Toolkit for our viewing. To
317 create out TT based view, just run the following command:
318
319     script/tutorial_create.pl view TToolkit TT
320
321 Notice that this time we not only gave it the type of module we wanted
322 to create (a view), and a name, but also a third argument, "TT". This is
323 a Catalyst helper module, which will make a standard template toolkit
324 module for you. And that's all you need to do there.
325
326 To use the view, the easiest way is to set up a standard "end" action.
327 This a private action which will not be matched to a path like our
328 "greet" action, but instead will be called after all other processing is
329 done. Only one end action will be called, if there is one in a
330 controller, it will be preferred over one in the application module, and
331 so on.
332
333 Since we're writing a simple application, just add an end action like
334 this to F<tutorial.pm>:
335
336     sub end : Private {
337         my ($self, $c) = @_;
338         $c->forward('tutorial::View::TToolkit') unless $c->res->body();
339     }
340
341 The first line declares the end sub, and marks it as a Private action.
342 (The second and last attribute type we'll be using). The second line
343 collects our standard parameters as shown in the controller's greet action.
344
345 The third line directs Catalyst to pass processing on to our TToolkit
346 view. The forward method, when just passed a class name, calls process
347 on that class. The standard TT view's process method renders the
348 template named in the template variable in the stash, using all the
349 other variables in the stash as values to fill it in.
350
351 NB: This is such a common way to end you processing that there is a
352 plugin which does it for you: L<Catalyst::Plugin::DefaultEnd>.
353
354 Template Toolkit also has access to the entire context object via "c",
355 for example, using [% c.config.name %] in our template will output
356 "tutorial", our project name.
357
358 All that remains is to create a simple template called "greet.tt",
359 containing a form with a text field called "name" like below.
360
361     <html><head><title> [% c.name %]</head><body>
362     <p>[%message%]</p>
363     <form action="[%c.req.uri%]" method="post">
364     <input type="text" name="name"/>
365     <input type="submit" value="Submit" name="submit"/>
366     </form>
367     </body></html>
368
369 In the example above, we use [%c.req.uri%], since we're posting to ourself.
370 if we post to another action, we commonly use the uri_for method, like this:
371
372     [% c.uri_for('/users/greet')%]
373
374 Place this file in the F<root> directory. By default, templates are 
375 searched for here, but we can change that, which brings us to...
376
377 =head2 Configuring
378
379 As previously mentioned, the configuration of modules, plugins and so on
380 is done in the main application file. This is especially true for bits
381 which need to be done before an instance of them is created, for example
382 Template Toolkit.
383
384 The TT View looks for its templates in the F<root> directory by default.
385 Since this is also the directory that static files go in, we'd rather
386 have a separate F<templates> directory. To do this, change the config
387 call in F<tutorial.pm> like this:
388
389  __PACKAGE__->config( name => 'tutorial',
390                       'View::TToolkit' => {
391                           'INCLUDE_PATH' => __PACKAGE__->path_to('templates')
392      }
393   );
394
395 And move the F<greet.tt> file from F<root> to the F<templates> directory
396 (after creating it).
397
398 Now we can run our application again by killing (B<ctrl-c>) and restarting
399 B<script/tutorial_server.pl>. Try connecting to
400 I<localhost:3000/users/greet> with a browser and see what happens. What
401 happens if you try to visit I<localhost:3000/users> ? 
402
403 =head2 Users and Authenticating
404
405 One of the many reasons to write dynamic websites instead of just using static 
406 HTML, is to allow us to produce different content for different users, as well
407  as just restricting access to pages (which we could do with just Apaches 
408 htpasswd system).
409
410 In this tutorial, we will just be using basic authentication, when writing 
411 a real application, you'll want to use a database or other secure store to 
412 contain your user data.
413
414 To add authentication, all we need to do is add the
415 L<Catalyst::Plugin::Authentication> module to our main application file. Then
416 we need to pick a storage method (one of the
417 L<Catalyst::Plugin::Authentication::Store> modules), and a method of verifying
418 the users credentials (one of the
419 L<Catalyst::Plugin::Authentication::Credential> modules), so just edit
420 F<tutorial.pm> to look like this: 
421
422  use Catalyst qw/-Debug Static::Simple Authentication 
423                 Authentication::Store::Minimal 
424                 Authentication::Credential::Password/;
425
426 To configure, add some users to the config call, for example: 
427
428  authentication => { 'users' =>
429                        { 'fred' =>
430                            { 'password' => 'fred1234',
431                            }
432                        }
433                    }
434
435 Generally, setting up configuration data for plugins is done based on the 
436 type of plugin. Check the documentation of the plugin for exact details. The 
437 details of this one are in L<Catalyst::Plugin::Authentication::Store::Minimal>.
438
439 Since our user data is in the config, we can update it at runtime, and thus 
440 add users dynamically. (Of course, to keep them permanently we'll need to 
441 export our data to disk and read it back into the config on startup)
442
443 To allow creation of new users we'll add a create action to our Users 
444 controller.
445
446  sub create : Local {
447     my ($self, $c) = @_;
448     my ($username, $passwd1, $passwd2) = map { $c->req->param($_)} 
449        ('username', 'password', 'passwordverify');
450
451     if($username && $passwd1 && $passwd2) {
452        if($c->config->{authentication}{users}{$username}) {
453           $c->stash->{message} = 'Sorry that user already exists';
454           $c->stash->{username} = $username;
455        }
456        elsif($passwd1 eq $passwd2) {
457             $c->config->{authentication}->{users}->{$username} =
458                 {password => $passwd1};
459           $c->stash->{message} = 'User created!';
460        }
461        else {
462           $c->stash->{username} = $username;
463           $c->stash->{message} = 'Passwords do not match!';
464        }
465     }
466     $c->stash->{template} = 'usercreate.tt';
467  }
468
469 All this is doing is checking that all the appropriate fields are filled, 
470 the password fields contain the same data, and then adding the user to the 
471 config hash.  All the checks produce a message which can be displayed to 
472 the user via the View.
473
474 The usercreate.tt template looks like this:
475
476  <html><head><title>[% c.config.name %]</title></head><body>
477  <h1>Create a new user</h1>
478  <h2>Current users are:</h2>
479  <p>
480     [% FOREACH key = c.config.authentication.users.keys %]
481         [% key %]<br/>
482     [% END %]
483  </p>
484  <p> [% c.stash.message %] </p>
485  <form action="/users/create" method="post">
486  <p>User Name: <input type="text" name="username"/></p>
487  <p>Password: <input type="password" name="password"/></p>
488  <p>Confirm Password: <input type="password" name="passwordverify"/></p>
489  <p><input type="submit" name="submit" value="submit"></p>
490  </form>
491  </body></html>
492
493 So our that users can login, we need a login action which we put in the
494 Users controller:
495
496  sub login : Local {
497      my ($self, $c) = @_;
498      $c->stash->{template} = 'userlogin.tt';
499      if(!$c->login()) {
500              $c->stash->{message} = 'Please login.';
501      }
502      else {
503          $c->stash->{message} = "Welcome " . $c->user->id;
504      }
505  }
506
507
508 And the userlogin.tt template:
509
510  <html><head><title>[% c.config.name %]</title></head><body>
511  <p> [% c.stash.message %] </p>
512  <form name='login' action='/users/login' method='post'>
513  <p>Username: <input type='text' name='user' /></p>
514  <p>Password: <input type='password' name='password' /></p>
515  <p><input type="submit" /></form>
516  </body></html>
517
518
519 Verrrry simple. Since Credential::Password's "login" call extracts the 
520 username/password data from the query itself (assuming we use a standard 
521 name for our form fields), we don't have to do anything but call it.
522
523 To keep the user logged in, all we need to do is add the Session modules to 
524 our collection, and the Auth modules will automatically use them; 
525
526  use Catalyst qw/-Debug Static::Simple Authentication 
527                  Authentication::Store::Minimal 
528                  Authentication::Credential::Password
529                  Session Session::Store::File Session::State::Cookie/;
530
531 Magic!
532
533 =head2 Exercise
534
535 As an exercise for the reader, do the following:
536
537 Change users/greet and greet.tt so that the welcome message greets the
538 user by name.
539
540 Enforce user logging in by adding an auto action in tutorial.pm (see
541 the L<Catalyst> documentation to find out about the auto action).
542
543 =head2 Authorising
544
545 Authentication is about verifying users, Authorisation is about
546 allowing them to do things. Catalyst currently has two Authorisation
547 modules, Roles and ACL. The Roles module allows you to define groups
548 which you can assign your users to, and then allow access to areas of
549 your website to the groups. The ACL module lets you do more fine
550 grained access/restriction by allowing of denying access however you
551 like (It also supports Roles as done by the roles module). This
552 example uses L<Catalyst::Plugin::Authorization::Roles>. To use this add
553 "Authorization::Roles" into the "use Catalyst" statement in
554 tutorial.pm.
555
556 Adding Roles via the Minimal store we are already using is quite simple,
557 we just add a roles key to each user, defining the names of the roles
558 they belong to.
559
560  authentication => { 'users' =>
561                             { 'fred' => 
562                                { 'password' => 'fred1234',
563                                  'roles'       => ['admin']
564                                }
565                             }
566                          }
567
568 We need an interface for our admins to administer the roles, i.e. assign
569 the users to groups. To restrict access to certain actions, we just need
570 to call C<< $c->check_user_roles() >> in each action. So we can
571 make a restricted I<http://localhost:3000/users/groups> page like this:
572
573  sub groups : Local {
574     my ($self, $c) = @_;
575     if($c->check_user_roles('admin')) {
576        # Now we can do things only an admin will see
577        if(my $params = $c->req->params) {
578           my $users = $c->config->{authentication}{users};
579           foreach my $u (keys %$params) {
580              $users->{$u}{roles} = $params->{$u} if($users->{$u});
581           }
582           $c->stash->{message} = 'Updated user roles!';
583        }
584        else {
585            $c->stash->{users} = $c->config->{authentication};
586        }
587        $c->stash->{template} = 'usersgroups.tt';
588     }
589     else {
590         $c->stash->{message} = 'Admins Only!';
591         $c->stash->{template} = 'error.tt';
592     }
593  }
594
595 What we are doing here is checking whether the logged in user (used by
596 default in the check_user_roles method), is a member of the admin group.
597 If it is, then we display the usergroups template, and update the users
598 hash as required. Otherwise, we just show the user an error page.
599
600 For this simple example, the usersgroups.tt and error.tt templates could
601 both look like this:
602
603  <html><head><title>[% c.config.name %]</title></head><body>
604  <p>[% c.stash.message %]</p>
605  <p>[% c.stash.users %]</p>
606  </body></html>
607
608 And that's all there is to it.
609
610 =for authors
611 So it's not clear what the groups action is doing - and with the
612 current template, nothing happens.  Running through the sample code,
613 it's clear what's happening, (which is very little), but the purpose,
614 and how to display data is not clear.
615
616 =cut
617
618 So that you can test this out properly without having to go to the
619 trouble of deleting browser cookies manually, we will add a logout
620 action in the Users controller:
621
622  sub logout : Local {
623     my ($self, $c) = @_;
624     $c->stash->{message} = "You have successfully logged out";
625     $c->logout;
626  }
627
628
629 =head2 Data Storage (Modelling)
630
631 Whether we want our users to be able to contribute to our website, or just
632 create it from changeable data, we need to store the data somewhere. Generally
633 this is done using a database, models can also be other data sources, for
634 example another website, or RSS feeds. 
635
636 If you have or want a database, there are still choices to be made, there are
637 several modules about for accessing databases via OO. The best known are
638 probably L<DBIx::Class> and L<Class::DBI>. Catalyst supports making models
639 using either of these.  
640
641 For a simple example, we will allow our users to store their favourite
642 greeting in our database. Create a table called "greetings" in a database,
643 that contains a "user" field and a "greeting" field. The simplest way to
644 create a model of your database is to use these helper modules, for example
645 with L<DBIx::Class>: 
646
647     script/tutorial_create.pl model UserData DBIC dbi:SQLite:/path/to/mydb.db
648
649 This will cause the DBIx::Class Loader to inspect your database, and create a
650 module in the Model::UserData namespace for each table in your database. 
651
652 Now we need a form for our users to enter/edit their personal greetings in,
653 we'll make a I<http://localhost:3000/users/editgreeting> page: 
654
655  sub editgreeting : Local {
656     my ($self, $c) = @_;
657     if($c->req->params->{greeting}) {
658        if(!$c->user_exists) {
659           $c->stash->{message} = "You're not logged in!";
660        }
661        else {
662           my $grtable = $c->model('UserData::Greetings');
663           my $record = $grtable->find_or_create(user => $c->user->id);
664           $record->greeting($c->req->params->{greeting};
665           $record->update;
666           $c->stash->{message} = 'Greeting updated';
667        }
668     }
669     $c->stash->{template} = 'usersgreeting.tt';
670  }
671
672 Using C<< $c->user_exists >> from the Authentication plugin, this checks
673 whether the user is logged in already. If they are, if they are, and they have
674 entered a new greeting, we use DBIx::Class' C<find_or_create> to fetch or
675 create a new record in the greetings table for the user. Once we have the
676 record, we change the value of the greeting field, and call C<update> to store
677 the new value in the database. 
678
679 =head2 Engines (Apache and FastCGI)
680
681 Now that we have the basics together, we can try running our application on a
682 "real" server instead of just using the test server that catalyst comes
683 with. L<Catalyst::Engine> is the module used to implement various types of
684 servers to run it on. The current popular ones are Apache and FastCGI. To
685 force the use of a particular engine we can use the -Engine flag to Catalyst: 
686
687  use Catalyst qw/-Engine=Apache/;
688
689 or
690
691  use Catalyst qw/-Engine=FastCGI/;
692
693 =head3 Apache
694
695 Apache also needs to be configured: we need to tell it to load your
696 application. You can either use Catalyst for your entire website, or
697 subsections. Use the Location directive to choose a path to run your
698 application under: 
699
700  <Location />
701    SetHandler                perl-script
702    PerlResponseHandler  tutorial
703  </Location>
704
705 You will need to install the perl modules of your application into one of
706 perls library directories, as listed by B<perl -V>, so that Apache can find
707 them. Alternatively you can use the C<PerlSwitches> directive to tell Apache
708 where to look: 
709
710  PerlSwitches -I/path/to/tutorial/
711
712 These instructions are for using Apache2 and mod_perl 2.0. If you are using
713 mod_perl 1.3 or 1.99, please refer to either L<Catalyst::Engine::Apache::MP13>
714 or L<Catalyst::Engine::Apache2::MP19> for slightly different ways to do it. 
715
716 If you wish to ensure that Apache pre-loads your application, use the
717 PerlModule directive. This means that there will be less of a delay when your
718 application is accessed. 
719
720  PerlModule tutorial
721
722 =head3 FastCGI
723
724 These instructions apply to the use of C<mod_fastcgi> under Apache
725 (either 1 or 2 series).
726
727 There are 3 ways to attach a program to a URL with C<mod_fastcgi>;
728 we'll examine all of them, and explain how to avoid having the
729 C<tutorial_fastcgi.pl> substring in the user-visible URLs.
730
731 In all of these examples, we assume that the C<DocumentRoot> is
732 C</var>, that our app is called C<tutorial> and is kept in C</usr>, that
733 you want the users to access the app either from the root of the
734 server-uri-space, or from C</theapp>. We also assume that the general
735 FastCGI settings (C<FastCgiIpcDir>, loading the module) are already
736 correct (they don't depend on Catalyst or your application layout).
737
738 =head4 static application
739
740 In this setup, you tell C<mod_fastcgi> that a particular I<file> is to
741 be run as a FastCGI handler. Put this somewhere in Apache's
742 configuration:
743
744   FastCgiServer /usr/apps/tutorial/script/tutorial_fastcgi.pl
745   Alias / /usr/apps/tutorial/script/tutorial_fastcgi.pl/
746
747 If you want your app under C</theapp>, change the C<Alias> line to:
748
749   Alias /theapp /usr/apps/tutorial/script/tutorial_fastcgi.pl
750
751 Note the detail of the trailing C</ >: this is a general rule of the
752 C<Alias> directive, both sides must end with C</ >, or both must not;
753 you can't have one with C</ > and the other without, or strange things
754 happen.
755
756 =head4 dynamic application
757
758 In this setup, you tell C<mod_fastcgi> that certain files are to be
759 treated as FastCGI handlers, in the same way you have to tell
760 C<mod_cgi>. Put this in the configuration:
761
762   FastCgiConfig -autoUpdate
763
764   <Directory /usr/apps/tutorial/script>
765    Options +ExecCGI
766    <Files *_fastcgi.pl>
767     SetHandles fastcgi-script
768    </Files>
769   </Directory>
770
771   Alias / /usr/apps/tutorial/script/tutorial_fastcgi.pl/
772
773 Again, if you want your app under C</theapp>, change the C<Alias> line to:
774
775   Alias /theapp /usr/apps/tutorial/script/tutorial_fastcgi.pl
776
777 =head4 external server
778
779 In this setup, the application is started separately from Apache, and
780 communicates via a socket with C<mod_fastcgi>. This can be useful if
781 you need to have a particular environment for your application (maybe
782 different between applications), or you want to run them on different
783 machines, or under different users for security reasons.
784
785 If you want to use a UNIX socket (on the filesystem), put this in
786 Apache's configuration:
787
788   FastCgiExternalServer /tmp/somewhere -socket /tmp/tutorial-socket
789   Alias / /tmp/somewhere/
790
791 Note that C</tmp> should I<not> exist: it's just a name to connect the
792 two parts.
793
794 Again, if you want your app under C</theapp>, change the C<Alias> line
795 to:
796
797   Alias /theapp /tmp/somewhere
798
799 Then start your Catalyst application:
800
801   $ cd /usr/apps/tutorial
802   $ ./script/tutorial_fastcgi -l /tmp/tutorial-socket
803
804 If you want to use a TCP socket, simply change the C</tmp> to a
805 C<host:port> pair, both in Apache's configuration and on the command
806 line of your application.
807
808 =head2 Upgrading
809
810 Upgrading your application to newer Catalyst versions is quite simple. After
811 installing the new Catalyst package, just run: 
812
813     catalyst.pl -scripts
814
815 One level above your application directory. This will update the
816 scripts directory only, and leave the rest of your app alone, If you
817 wish to make use of other parts of Catalyst that have been updated,
818 leave off the B<-scripts> argument, this will cause .new files to
819 appear, for each module that has either been updated, or is different
820 to the original because you have changed it. To find out what these
821 changes are, type:
822
823     diff tutorial/lib/tutorial/View/TT.pm tutorial/lib/tutorial/View/TT.pm.new
824
825 for each of the changed files. (This is a Unix command, Windows users
826 will need to find some equivalent). Copy any changes you need into
827 your original file, then remove the .new files. (This makes life less
828 complicated when the next upgrade comes around.)
829
830 =head1 AUTHORS
831
832 Jess Robinson, C<jrobinson@cpan.org>
833 Andrew Ford, C<A.Ford@ford-mason.co.uk>
834 Marcus Ramberg, C<mramberg@cpan.org>
835 Kieren Diment, C<kd@totaldatasolution.com>
836 Gavin Henry, C<ghenry@cpan.org>
837
838 Please send comments, corrections and suggestions for improvements to
839 jrobinson@cpan.org, ghenry@cpan.org
840
841 =head1 TODO
842
843 Finish DBIC examples with templates and tested code.  Make
844 /users/groups do something "useful"
845
846 Many other things..
847
848 =head1 COPYRIGHT
849
850 This program is free software, you can redistribute it and/or modify 
851 it under the same terms as Perl itself.