Spell checking and formatting, with some grammar corrections.
[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  <p> [% c.stash.message %] </p>
479  <form action="/users/create" method="post">
480  <p>User Name: <input type="text" name="username"/></p>
481  <p>Password: <input type="password" name="password"/></p>
482  <p>Confirm Password: <input type="password" name="passwordverify"/></p>
483  <p><input type="submit" name="submit" value="submit"></p>
484  </form>
485  </body></html>
486
487 So our that users can login, we need a login action which we put in the
488 Users controller:
489
490  sub login : Local {
491      my ($self, $c) = @_;
492      $c->stash->{template} = 'userlogin.tt';
493      if(!$c->login()) {
494              $c->stash->{message} = 'Please login.';
495      }
496      else {
497          $c->stash->{message} = "Welcome " . $c->user->id;
498      }
499  }
500
501
502 And the userlogin.tt template:
503
504  <html><head><title>[% c.config.name %]</title></head><body>
505  <p> [% c.stash.message %] </p>
506  <form name='login' action='/users/login' method='post'>
507  <p>Username: <input type='text' name='user' /></p>
508  <p>Password: <input type='password' name='password' /></p>
509  <p><input type="submit" /></form>
510  </body></html>
511
512
513 Verrrry simple. Since Credential::Password's "login" call extracts the 
514 username/password data from the query itself (assuming we use a standard 
515 name for our form fields), we don't have to do anything but call it.
516
517 To keep the user logged in, all we need to do is add the Session modules to 
518 our collection, and the Auth modules will automatically use them; 
519
520  use Catalyst qw/-Debug Static::Simple Authentication 
521                  Authentication::Store::Minimal 
522                  Authentication::Credential::Password
523                  Session Session::Store::File Session::State::Cookie/;
524
525 Magic!
526
527 =head2 Exercise
528
529 As an exercise for the reader, do the following:
530
531 Change users/greet and greet.tt so that the welcome message greets the
532 user by name.
533
534 Enforce user logging in by adding an auto action in tutorial.pm (see
535 the L<Catalyst> documentation to find out about the auto action).
536
537 =head2 Authorising
538
539 Authentication is about verifying users, Authorisation is about
540 allowing them to do things. Catalyst currently has two Authorisation
541 modules, Roles and ACL. The Roles module allows you to define groups
542 which you can assign your users to, and then allow access to areas of
543 your website to the groups. The ACL module lets you do more fine
544 grained access/restriction by allowing of denying access however you
545 like (It also supports Roles as done by the roles module). This
546 example uses L<Catalyst::Plugin::Authorization::Roles>. To use this add
547 "Authorization::Roles" into the "use Catalyst" statement in
548 tutorial.pm.
549
550 Adding Roles via the Minimal store we are already using is quite simple,
551 we just add a roles key to each user, defining the names of the roles
552 they belong to.
553
554  authentication => { 'users' =>
555                             { 'fred' => 
556                                { 'password' => 'fred1234',
557                                  'roles'       => ['admin']
558                                }
559                             }
560                          }
561
562 We need an interface for our admins to administer the roles, i.e. assign
563 the users to groups. To restrict access to certain actions, we just need
564 to call C<< $c->check_user_roles() >> in each action. So we can
565 make a restricted I<http://localhost:3000/users/groups> page like this:
566
567  sub groups : Local {
568     my ($self, $c) = @_;
569     if($c->check_user_roles('admin')) {
570        # Now we can do things only an admin will see
571        if(my $params = $c->req->params) {
572           my $users = $c->config->{authentication}{users};
573           foreach my $u (keys %$params) {
574              $users->{$u}{roles} = $params->{$u} if($users->{$u});
575           }
576           $c->stash->{message} = 'Updated user roles!';
577        }
578        else {
579            $c->stash->{users} = $c->config->{authentication};
580        }
581        $c->stash->{template} = 'usersgroups.tt';
582     }
583     else {
584         $c->stash->{message} = 'Admins Only!';
585         $c->stash->{template} = 'error.tt';
586     }
587  }
588
589 What we are doing here is checking whether the logged in user (used by
590 default in the check_user_roles method), is a member of the admin group.
591 If it is, then we display the usergroups template, and update the users
592 hash as required. Otherwise, we just show the user an error page.
593
594 For this simple example, the usersgroups.tt and error.tt templates could
595 both look like this:
596
597  <html><head><title>[% c.config.name %]</title></head><body>
598  <p>[% c.stash.message %]</p>
599  <p>[% c.stash.users %]</p>
600  </body></html>
601
602 And that's all there is to it.
603
604 =for authors
605 So it's not clear what the groups action is doing - and with the
606 current template, nothing happens.  Running through the sample code,
607 it's clear what's happening, (which is very little), but the purpose,
608 and how to display data is not clear.
609
610 =cut
611
612 So that you can test this out properly without having to go to the
613 trouble of deleting browser cookies manually, we will add a logout
614 action in the Users controller:
615
616  sub logout : Local {
617     my ($self, $c) = @_;
618     $c->stash->{message} = "You have successfully logged out";
619     $c->logout;
620  }
621
622
623 =head2 Data Storage (Modelling)
624
625 Whether we want our users to be able to contribute to our website, or just
626 create it from changeable data, we need to store the data somewhere. Generally
627 this is done using a database, models can also be other data sources, for
628 example another website, or RSS feeds. 
629
630 If you have or want a database, there are still choices to be made, there are
631 several modules about for accessing databases via OO. The best known are
632 probably L<Class::DBI> and L<DBIx::Class>. Catalyst supports making models
633 using either of these.  
634
635 For a simple example, we will allow our users to store their favourite
636 greeting in our database. Create a table called "greetings" in a database,
637 that contains a "user" field and a "greeting" field. The simplest way to
638 create a model of your database is to use these helper modules, for example
639 with L<DBIx::Class>: 
640
641     script/tutorial_create.pl model UserData DBIC dbi:SQLite:/path/to/mydb.db
642
643 This will cause the DBIx::Class Loader to inspect your database, and create a
644 module in the Model::UserData namespace for each table in your database. 
645
646 Now we need a form for our users to enter/edit their personal greetings in,
647 we'll make a I<http://localhost:3000/users/editgreeting> page: 
648
649  sub editgreeting : Local {
650     my ($self, $c) = @_;
651     if($c->req->params->{greeting}) {
652        if(!$c->user_exists) {
653           $c->stash->{message} = "You're not logged in!";
654        }
655        else {
656           my $grtable = $c->model('UserData::Greetings');
657           my $record = $grtable->find_or_create(user => $c->user->id);
658           $record->greeting($c->req->params->{greeting};
659           $record->update;
660           $c->stash->{message} = 'Greeting updated';
661        }
662     }
663     $c->stash->{template} = 'usersgreeting.tt';
664  }
665
666 Using C<< $c->user_exists >> from the Authentication plugin, this checks
667 whether the user is logged in already. If they are, if they are, and they have
668 entered a new greeting, we use DBIx::Class' C<find_or_create> to fetch or
669 create a new record in the greetings table for the user. Once we have the
670 record, we change the value of the greeting field, and call C<update> to store
671 the new value in the database. 
672
673 =head2 Engines (Apache and FastCGI)
674
675 Now that we have the basics together, we can try running our application on a
676 "real" server instead of just using the test server that catalyst comes
677 with. L<Catalyst::Engine> is the module used to implement various types of
678 servers to run it on. The current popular ones are Apache and FastCGI. To
679 force the use of a particular engine we can use the -Engine flag to Catalyst: 
680
681  use Catalyst qw/-Engine=Apache/;
682
683 or
684
685  use Catalyst qw/-Engine=FastCGI/;
686
687 =head3 Apache
688
689 Apache also needs to be configured: we need to tell it to load your
690 application. You can either use Catalyst for your entire website, or
691 subsections. Use the Location directive to choose a path to run your
692 application under: 
693
694  <Location />
695    SetHandler                perl-script
696    PerlResponseHandler  tutorial
697  </Location>
698
699 You will need to install the perl modules of your application into one of
700 perls library directories, as listed by B<perl -V>, so that Apache can find
701 them. Alternatively you can use the C<PerlSwitches> directive to tell Apache
702 where to look: 
703
704  PerlSwitches -I/path/to/tutorial/
705
706 These instructions are for using Apache2 and mod_perl 2.0. If you are using
707 mod_perl 1.3 or 1.99, please refer to either L<Catalyst::Engine::Apache::MP13>
708 or L<Catalyst::Engine::Apache2::MP19> for slightly different ways to do it. 
709
710 If you wish to ensure that Apache pre-loads your application, use the
711 PerlModule directive. This means that there will be less of a delay when your
712 application is accessed. 
713
714  PerlModule tutorial
715
716 =head3 FastCGI
717
718 These instructions apply to the use of C<mod_fastcgi> under Apache
719 (either 1 or 2 series).
720
721 There are 3 ways to attach a program to a URL with C<mod_fastcgi>;
722 we'll examine all of them, and explain how to avoid having the
723 C<tutorial_fastcgi.pl> substring in the user-visible URLs.
724
725 In all of these examples, we assume that the C<DocumentRoot> is
726 C</var>, that our app is called C<tutorial> and is kept in C</usr>, that
727 you want the users to access the app either from the root of the
728 server-uri-space, or from C</theapp>. We also assume that the general
729 FastCGI settings (C<FastCgiIpcDir>, loading the module) are already
730 correct (they don't depend on Catalyst or your application layout).
731
732 =head4 static application
733
734 In this setup, you tell C<mod_fastcgi> that a particular I<file> is to
735 be run as a FastCGI handler. Put this somewhere in Apache's
736 configuration:
737
738   FastCgiServer /usr/apps/tutorial/script/tutorial_fastcgi.pl
739   Alias / /usr/apps/tutorial/script/tutorial_fastcgi.pl/
740
741 If you want your app under C</theapp>, change the C<Alias> line to:
742
743   Alias /theapp /usr/apps/tutorial/script/tutorial_fastcgi.pl
744
745 Note the detail of the trailing C</ >: this is a general rule of the
746 C<Alias> directive, both sides must end with C</ >, or both must not;
747 you can't have one with C</ > and the other without, or strange things
748 happen.
749
750 =head4 dynamic application
751
752 In this setup, you tell C<mod_fastcgi> that certain files are to be
753 treated as FastCGI handlers, in the same way you have to tell
754 C<mod_cgi>. Put this in the configuration:
755
756   FastCgiConfig -autoUpdate
757
758   <Directory /usr/apps/tutorial/script>
759    Options +ExecCGI
760    <Files *_fastcgi.pl>
761     SetHandles fastcgi-script
762    </Files>
763   </Directory>
764
765   Alias / /usr/apps/tutorial/script/tutorial_fastcgi.pl/
766
767 Again, if you want your app under C</theapp>, change the C<Alias> line to:
768
769   Alias /theapp /usr/apps/tutorial/script/tutorial_fastcgi.pl
770
771 =head4 external server
772
773 In this setup, the application is started separately from Apache, and
774 communicates via a socket with C<mod_fastcgi>. This can be useful if
775 you need to have a particular environment for your application (maybe
776 different between applications), or you want to run them on different
777 machines, or under different users for security reasons.
778
779 If you want to use a UNIX socket (on the filesystem), put this in
780 Apache's configuration:
781
782   FastCgiExternalServer /tmp/somewhere -socket /tmp/tutorial-socket
783   Alias / /tmp/somewhere/
784
785 Note that C</tmp> should I<not> exist: it's just a name to connect the
786 two parts.
787
788 Again, if you want your app under C</theapp>, change the C<Alias> line
789 to:
790
791   Alias /theapp /tmp/somewhere
792
793 Then start your Catalyst application:
794
795   $ cd /usr/apps/tutorial
796   $ ./script/tutorial_fastcgi -l /tmp/tutorial-socket
797
798 If you want to use a TCP socket, simply change the C</tmp> to a
799 C<host:port> pair, both in Apache's configuration and on the command
800 line of your application.
801
802 =head2 Upgrading
803
804 Upgrading your application to newer Catalyst versions is quite simple. After
805 installing the new Catalyst package, just run: 
806
807     catalyst.pl -scripts
808
809 One level above your application directory. This will update the
810 scripts directory only, and leave the rest of your app alone, If you
811 wish to make use of other parts of Catalyst that have been updated,
812 leave off the B<-scripts> argument, this will cause .new files to
813 appear, for each module that has either been updated, or is different
814 to the original because you have changed it. To find out what these
815 changes are, type:
816
817     diff tutorial/lib/tutorial/View/TT.pm tutorial/lib/tutorial/View/TT.pm.new
818
819 for each of the changed files. (This is a Unix command, Windows users
820 will need to find some equivalent). Copy any changes you need into
821 your original file, then remove the .new files. (This makes life less
822 complicated when the next upgrade comes around.)
823
824 =head1 AUTHORS
825
826 Jess Robinson, C<jrobinson@cpan.org>
827 Andrew Ford, C<A.Ford@ford-mason.co.uk>
828 Marcus Ramberg, C<mramberg@cpan.org>
829 Kieren Diment, C<kd@totaldatasolution.com>
830 Gavin Henry, C<ghenry@cpan.org>
831
832 Please send comments, corrections and suggestions for improvements to
833 jrobinson@cpan.org, ghenry@cpan.org
834
835 =head1 TODO
836
837 Finish DBIC examples with templates and tested code.  Make
838 /users/groups do something "useful"
839
840 Many other things..
841
842 =head1 COPYRIGHT
843
844 This program is free software, you can redistribute it and/or modify 
845 it under the same terms as Perl itself.