3 Catalyst::Manual::Tutorial - Getting started with Catalyst
7 This document aims to get you up and running with Catalyst.
11 The first step is to install Catalyst, and the simplest way to do this
12 is to install the Catalyst bundle from CPAN:
14 $ perl -MCPAN -e 'install Task::Catalyst'
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.
23 =head2 The very basics - Setting up the skeleton application.
25 Catalyst includes a helper script, C<catalyst.pl>, that will set up a
26 skeleton application for you:
31 created "MyApp/script"
33 created "MyApp/script/myapp_create.pl"
35 This creates the directory structure, populated with skeleton
38 =head2 Testing out the skeleton application
40 You can test out your new application by running the server script that
44 $ script/myapp_server.pl
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/MyApp"
54 [...] [catalyst] [debug] Loaded Private actions:
55 .--------------------------------------+---------------------------------------.
57 +--------------------------------------+---------------------------------------+
59 '--------------------------------------+---------------------------------------'
61 [...] [catalyst] [info] MyApp powered by Catalyst 5.5
62 You can connect to your server at http://localhost:3000
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.)
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):
72 $ telnet localhost 3000
74 Connected to localhost.
75 Escape character is '^]'.
79 Date: Mon, 07 Nov 2005 14:57:39 GMT
81 Content-Type: text/html; charset=utf-8
86 Connection closed by foreign host.
89 You can see the full welcome message by visting
90 http://localhost:3000/ with your browser.
92 More trace messages will appear in the original terminal window:
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 .------------------------------------------------------------------+-----------.
102 +------------------------------------------------------------------+-----------+
103 | /default | 0.000000s |
104 '------------------------------------------------------------------+-----------'
106 The server will continue running until you interrupt it.
108 The application can also be tested from the command line using the generated
109 helper script, C<script/myapp_test.pl>.
111 =head2 Getting started
113 So you picked Catalyst. Good choice. I assume you've installed it as
114 well. For this tutorial you will also need the following modules:
116 L<Catalyst::Plugin::Session>
118 L<Catalyst::Plugin::Session::Store::File>
120 L<Catalyst::Plugin::Session::State::Cookie>
122 L<Catalyst::Plugin::Authentication>
124 L<Catalyst::Plugin::Authentication::Store::Minimal>
126 L<Catalyst::Plugin::Authentication::::Minimal>
128 L<Catalyst::Plugin::Authentication::Credential::Password>
130 L<Catalyst::Plugin::Authorization::Roles>
136 To get started all you need to do is type:
138 B<catalyst.pl tutorial>
140 This should create a directory called F<tutorial> and fill it with the
141 default (standard) Catalyst installation. Change to this directory
142 because we will be running all further commands from inside the
143 F<tutorial> directory.
145 If you now run the built-in mini-server with
146 B<script/tutorial_server.pl>, it will show some standard debug messages
147 in the console screen (more about those in a minute), and then inform
148 you that you can now connect to the test server on port 3000. Point your
149 browser at localhost:3000 to see the built-in catalyst welcome screen.
151 The other important thing catalyst.pl did was create your root
152 controller. This file is a standard perl module like all the other
153 controllers that you might add to your application. It lives in the
154 F<lib/> directory, and will have the same name as you supplied to the
155 command above, in our case it is F<tutorial.pm>. Alongside this file is
156 a directory of the same name, which is the top level namespace for the
157 entire application. Thus every other module we create will be
158 "tutorial::something";
160 The root controller is used to load plugins, to configure the
161 application and its plugins, and for generic private actions. We will
162 explain more about those later.
166 The simplest way to debug your Catalyst application is to run it using
167 the built-in mini-server as described in L<Getting started>.
169 If you want to output any debugging information to the console, then
170 call C<< $context->log->debug() >>, passing it a string to output. For
171 data structures, use Data::Dumper and call C<<
172 $context->log->debug(Dumper($structure)) >>
174 =head2 Model/View/Controller
176 The recommended method for code organization in a Catalyst application
177 is known as the "Model View Controller" design pattern (also referred to
178 "MVC"). The point of the MVC pattern is to divorce the dependencies of
179 parts of the application from each other, and give them standard
180 interfaces. Following this theory of organization should give your code
181 all the benefits of modularity. The main benefits are interchangability
182 of parts and reusable code.
184 Thus you could replace your file data storage with a database or your
185 oracle database with a mysql database and not have to change any of your
186 controlling or view logic. Or you could later decide to output
187 information from your application as RSS instead of HTML just by adding
192 Models deal with the storage of data. For a complex website, you may
193 need multiple varied data sources, each will have it's own model class
194 that provides an abstracted interface to it. In this tutorial we are
195 going to be using a simple database.
199 Views are used to display information to the user. In a web framework,
200 it is generally used to output HTML to the browser. As mentioned
201 previously, views can also be used to output RSS or any other kind of
202 data format. One easy way to do this with Catalyst is to use a
203 templating system such as Template Toolkit. If outputting HTML is all
204 you are going to do, then you will probably only need one view.
208 A controller deals with reacting to user choices, and thus controls what
209 the application does. Since this is a web framework, Catalyst
210 controllers are frequently used to react directly to URLs requested by
211 the user. This tutorial will describe the simplest way of using
212 controllers, where each path or part of a path is assigned its own
213 action (or subroutine). More complex controlling mechanisms will be
214 mentioned briefly, and can be read about in detail in the manual.
219 Now lets write our first bit of application code. First, we would like
220 our application to greet our users. We'll assume for now that our users
221 will be sent to the I<users/greet> URL. To create a controller that
222 serves the I<users> namespace, we run the following command in our
223 F<tutorial> directory:
225 B<script/tutorial_create.pl controller Users>
227 This will create a Users.pm in F<lib/tutorial/Controller>. Open this
228 file in an editor and take a look. You will notice there is some
229 commented out code which we will ignore for now. To make something
230 happen when our URL is visited, we will write a "greet" action which
236 my $name = $context->req->param('name');
237 $c->log->debug("Got name: $name\n");
239 if ($c->req->method eq 'POST') {
241 $c->stash->{message} = 'Please fill in a name!';
244 $c->stash->{message} = "Hello $name!";
247 $c->stash->{template} = 'greet.tt';
250 Whew! So, what does all this do? Lets take it one step at a time.
251 The subroutine declaration gives the action a name. To the right of the
252 name there is an attribute type that looks like this: " : Local". That
253 defines which URIs will translate to this action. "Local", matches
254 exactly one URI: /users/greet. The URI matched by "Local" is composed
255 from the namespace minus the tutorial::controller portion, that is
256 common to all controllers, and the action name itself. Because it is a
257 URI, we use forward slashes instead of double colons. So, in summary,
258 when a user requests http://localhost:3000/users/greet" the "greet"
259 action defined above in the Users controller will be executed.
261 The second line retrieves the parameters Catalyst gives us when it calls
262 our method. The first is the instance of our Users class, and the second
263 is commonly called the context, and named $c. The context is the magical
264 object containing any information you need from catalyst, or want to send to
265 it. You will see it used frequently in Catalyst applications, and a list
266 of all its methods is available in the L<Catalyst> POD.
268 On the third line we use the ->param method of the $context request
269 object to retrieve one of the query parameters, just like in L<CGI>.
271 On the fourth, we make a debug output of this object on the server console,
272 or the error log if running under CGI or mod_perl.
274 Next, if we have a post request, we check if the name field contains anything
275 (or is "true"), if it isnt, we assign an error message to a "message" field in
276 the stash. The stash is yet another method of the context object, it allows us
277 to pass data on to other methods we call later, most usefully the View modules.
279 If the username did contain a value, then we just set our message to
280 greet the user by name.
282 Finally, we set the special "template" variable in the stash to the name
283 of the template we want our view to use to display this page.
287 Ok, so reacting and checking the users data is all fine, but how do we
288 actually display the page/form in the first place, and our results? As
289 previously mentioned, we'll use Template Toolkit for our viewing. To
290 create out TT based view, just run the following command:
292 B<script/tutorial_create.pl view TToolkit TT>
294 Notice that this time we not only gave it the type of module we wanted
295 to create (a view), and a name, but also a third argument, "TT". This is
296 a Catalyst helper module, which will make a standard template toolkit
297 module for you. And that's all you need to do there.
299 To use the view, the easiest way is to set up a standard "end" action.
300 This a private action which will not be matched to a path like our
301 "greet" action, but instead will be called after all other processing is
302 done. Only one end action will be called, if there is one in a
303 controller, it will be prefered over one in the application module, and
306 Since we're writing a simple application, just add an end action like
307 this to F<tutorial.pm>:
311 my ($self, $context) = @_;
312 $context->forward('tutorial::View::TToolkit') unless $c->res->body();
315 The first line declares the end sub, and marks it as a Private action.
316 (The second and last attribute type we'll be using). The second line
317 collects our standard parameters as shown in the controller's greet action.
319 The third line directs Catalyst to pass processing on to our TToolkit
320 view. The forward method, when just passed a class name, calls process
321 on that classs. The standard TT view's process method renders the
322 template named in the templare variable in the stash, using all the
323 other variables in the stash as values to fill it in.
325 NB: This is such a common way to end you processing that there is a
326 plugin which does it for you: L<Catalyst::Plugin::DefaultEnd>.
328 Template Toolkit also has access to the entire context object via "c",
329 for example, using [% c.config.name %] in our template will output
330 "tutorial", our project name.
332 All that remains is to create a simple template called "greet.tt",
333 containing a form with a text field called "name" like below.
336 <form action="[%c.req.uri%]" method="post">
337 <input type="text" name="name"/>
340 In the example above, we use [%c.req.uri%], since we're posting to ourself.
341 if we post to another action, we commonly use the uri_for method, like this:
343 [% c.uri_for('/users/greet')%]
345 Place this file in the F<root> directory, . By default, templates are
346 searched for here, but we can change that, which brings us to..
350 As previously mentioned, the configuration of modules, plugins and so on
351 is done in the main application file. This is especially true for bits
352 which need to be done before an instance of them is created, for example
355 The TT View looks for its templates in the F<root> directory by default.
356 Since this is also the directory that static files go in, we'd rather
357 have a separate F<templates> directory. To do this, change the config
358 call in F<tutorial.pm> like this:
360 __PACKAGE__->config( name => 'tutorial',
361 'View::TToolkit' => {
362 'INCLUDE_PATH' => __PACKAGE__->path_to('templates')
366 And move the F<greet.tt> file from F<root> to the F<templates> directory
369 Now we can run our application again by killing (ctrl-c) and restarting
370 B<script/tutorial_server.pl>. Try connecting to
371 I<localhost:3000/users/greet> with a browser and see what happens. What
372 happens if you try to visit I<localhost:3000/users> ?
374 =head2 Users and Authenticating
376 One of the many reasons to write dynamic websites instead of just using static
377 HTML, is to allow us to produce different content for different users, as well
378 as just restricting access to pages (which we could do with just Apaches
381 In this tutorial, we will just be using basic authentication, when writing
382 a real application, you'll want to use a database or other secure store to
383 contain your user data.
385 To add authentication, all we need to do is add the
386 L<Catalyst::Plugin::Authentication> module to our main application file. Then
387 we need to pick a storage method (one of the
388 L<Catalyst::Plugin::Authentication::Store> modules), and a method of verifying
389 the users credentials (one of the
390 L<Catalyst::Plugin::Authentication::Credential> modules), so just edit
391 F<tutorial.pm> to look like this:
393 use Catalyst qw/-Debug Static::Simple Authentication
394 Authentication::Store::Minimal
395 Authentication::Credential::Password/;
397 To configure, add some users to the config call, for example:
399 authentication => { 'users' =>
401 { 'password' => 'fred1234',
406 Generally, setting up configuration data for plugins is done based on the
407 type of plugin. Check the documentation of the plugin for exact details. The
408 details of this one are in L<Catalyst::Plugin::Authentication::Store::Minimal>.
410 Since our user data is in the config, we can update it at runtime, and thus
411 add users dynamically. (Of course, to keep them permanently we'll need to
412 export our data to disk and read it back into the config on startup)
414 To allow creation of new users we'll add a create action to our Users
420 my ($username, $passwd1, $passwd2) = map { $context->req->param($_)}
421 ('username', 'password', 'passwordverify');
423 if($username && $passwd1 && $passwd2)
425 if($c->config->{authentication}{users}{$username})
427 $c->stash->{message} = 'Sorry that user already exists';
428 $c->stash->{username} = $username;
430 elsif($passwd1 eq $passwd2)
432 $c->config->({%{$context->config},
433 ($username => { password => $passwd1}});
434 $c->stash->{message} = 'User created!';
438 $c->stash->{username} = $username;
439 $c->stash->{message} = 'Passwords don't match!';
442 $c->stash->{template} = 'usercreate.tt';
445 All this is doing is checking that all the appropriate fields are filled,
446 the password fields contain the same data, and then adding the user to the
447 config hash. All the checks produce a message which can be displayed to
448 the user via the View.
450 So our that users can login, we need a login page:
454 my ($self, $context) = @_;
455 $c->stash->{template} = 'userlogin.tt';
457 $c->stash->{message} = 'Login failed.';
461 Verrrry simple. Since Credential::Password's "login" call extracts the
462 username/password data from the query itself (assuming we use a standard
463 name for our form fields), we don't have to do anything but call it.
465 To keep the user logged in, all we need to do is add the Session modules to
466 our collection, and the Auth modules will automatically use them;
468 use Catalyst qw/-Debug Static::Simple Authentication
469 Authentication::Store::Minimal
470 Authentication::Credential::Password
471 Session Session::Store::File Session::State::Cookie/;
477 Authentication is about verifying users, Authorisation is about allowing
478 them to do things. Catalyst currently has two Authorisation modules,
479 Roles and ACL. The Roles module allows you to define groups which you
480 can assign your users to, and then allow access to areas of your website
481 to the groups. The ACL module lets you do more fine grained
482 access/restriction by allowing of denying access however you like. (It
483 also supports Roles as done by the roles module.)
485 Adding Roles via the Minimal store we are already using is quite simple,
486 we just add a roles key to each user, defining the names of the roles
489 authentication => { 'users' =>
491 { 'password' => 'fred1234',
497 We need an interface for our admins to administer the roles, i.e. assign
498 the users to groups. To restrict access to certain actions, we just need
499 to call C<< $context->check_user_roles() >> in each action. So we can
500 make a restricted I<localhost:3000/users/groups> page like this:
504 my ($self, $context) = @_;
505 if($c->check_user_roles('admin')) {
506 # Now we can do things only an admin will see
507 if(my $params = $c->req->params) {
508 my $users = $c->config->{authentication}{users};
509 foreach my $u (keys %$params) {
510 $users->{$u}{roles} = $params->{$u} if($users->{$u});
512 $context->stash->{message} = 'Updated user roles!';
515 $context->stash->{users} = $context->config->{authentication};
517 $context->stash->{template} = 'usersgroups.tt';
520 $context->stash->{message} = 'Admins Only!';
521 $context->stash->{template} = 'error.tt';
525 What we are doing here is checking whether the logged in user (used by
526 default in the check_user_roles method), is a member of the admin group.
527 If it is, then we display the usergroups template, and update the users
528 hash as required. Otherwise, we just show the user an error page.
530 And that's all there is to it.
532 =head2 Data Storage (Modelling)
534 Whether we want our users to be able to contribute to our website, or just
535 create it from changeable data, we need to store the data somewhere. Generally
536 this is done using a database, models can also be other data sources, for
537 example another website, or RSS feeds.
539 If you have or want a database, there are still choices to be made, there are
540 several modules about for accessing databases via OO. The best known are
541 probably L<Class::DBI> and L<DBIx::Class>. Catalyst supports making models
542 using either of these.
544 For a simple example, we will allow our users to store their favourite
545 greeting in our database. Create a table called "greetings" in a database,
546 that contains a "user" field and a "greeting" field. The simplest way to
547 create a model of your database is to use these helper modules, for example
550 B<script/tutorial_create.pl model UserData DBIC dbi:SQLite:/path/to/mydb.db>
552 This will cause the DBIx::Class Loader to inspect your database, and create a
553 module in the Model::UserData namespace for each table in your database.
555 Now we need a form for our users to enter/edit their personal greetings in,
556 we'll make a I<localhost:3000/users/editgreeting> page:
558 sub editgreeting : Local {
560 if($c->req->params->{greeting}) {
561 if(!$c->user_exists) {
562 $c->stash->{message} = "You're not logged in!";
565 my $grtable = $context->model('UserData::Greetings');
566 my $record = $grtable->find_or_create(user => $context->user->id);
567 $record->greeting($context->req->params->{greeting};
569 $c->stash->{message} = 'Greeting updated';
572 $c->stash->{template} = 'usersgreeting.tt';
575 Using C<< $context->user_exists >> from the Authentication plugin, this checks
576 whether the user is logged in already. If they are, if they are, and they have
577 entered a new greeting, we use DBIx::Class' C<find_or_create> to fetch or
578 create a new record in the greetings table for the user. Once we have the
579 record, we change the value of the greeting field, and call C<update> to store
580 the new value in the database.
582 =head2 Engines (Apache and FastCGI)
584 Now that we have the basics together, we can try running our application on a
585 "real" server instead of just using the test server that catalyst comes
586 with. L<Catalyst::Engine> is the module used to implement various types of
587 servers to run it on. The currect popular ones are Apache and FastCGI. To
588 force the use of a particular engine we can use the -Engine flag to Catalyst:
590 use Catalyst qw/-Engine=Apache/;
594 use Catalyst qw/-Engine=FastCGI/;
598 Apache also needs configuring, we need to tell it to load your
599 application. You can either use Catalyst for your entire website, or
600 subsections. Use the Location directive to choose a path to run your
604 SetHandler perl-script
605 PerlResponseHandler MyApp
608 You will need to install the perl modules of your application into one of
609 perls library directories, as listed by B<perl -V>, so that Apache can find
610 them. Alternatively you can use the C<PerlSwitches> directive to tell Apache
613 PerlSwitches -I/path/to/MyApp/
615 These instructions are for using Apache2 and mod_perl 2.0. If you are using
616 mod_perl 1.3 or 1.99, please refer to either L<Catalyst::Engine::Apache::MP13>
617 or L<Catalyst::Engine::Apache2::MP19> for slightly different ways to do it.
619 If you wish to ensure that Apache pre-loads your application, use the
620 PerlModule directive. This means that there will be less of a delay when your
621 application is accessed.
627 These instructions apply to the use of C<mod_fastcgi> under Apache (either 1 or 2 series).
629 There are 3 ways to attach a program to a URL with C<mod_fastcgi>; we'll examine all of them, and explain how to avoid having the C<myapp_fastcgi.pl> substring in the user-visible URLs.
631 In all of these examples, we assume that the C<DocumentRoot> is C</var>, that our app is called C<MyApp> and is kept in C</usr>, that you want the users to access the app either from the root of the server-uri-space, or from C</theapp>. We also assume that the general FastCGI settings (C<FastCgiIpcDir>, loading the module) are already correct (they don't depend on Catalyst or your application layout).
633 =head4 static application
635 In this setup, you tell C<mod_fastcgi> that a particular I<file> is to be run as a FastCGI handler. Put this somewhere in Apache's configuration:
637 FastCgiServer /usr/apps/MyApp/script/myapp_fastcgi.pl
638 Alias / /usr/apps/MyApp/script/myapp_fastcgi.pl/
640 If you want your app under C</theapp>, change the C<Alias> line to:
642 Alias /theapp /usr/apps/MyApp/script/myapp_fastcgi.pl
644 Note the detail of the trailing C</ >: this is a general rule af the C<Alias> directive, both sides must end with C</ >, or both must not; you can't have one with C</ > and the other without, or strange things happen.
646 =head4 dynamic application
648 In this setup, you tell C<mod_fastcgi> that certain files are to be treated as FastCGI handlers, in the same way you have to tell C<mod_cgi>. Put this in the configuration:
650 FastCgiConfig -autoUpdate
652 <Directory /usr/apps/MyApp/script>
655 SetHandles fastcgi-script
659 Alias / /usr/apps/MyApp/script/myapp_fastcgi.pl/
661 Again, if you want your app under C</theapp>, change the C<Alias> line to:
663 Alias /theapp /usr/apps/MyApp/script/myapp_fastcgi.pl
665 =head4 external server
667 In this setup, the application is started separately from Apache, and communicates via a socket with C<mod_fastcgi>. This can be useful if you need to have a particular environment for your application (maybe different between applications), or you want to run them on different machines, or under different users for security reasons.
669 If you want to use a UNIX socket (on the filesystem), put this in Apache's configuration:
671 FastCgiExternalServer /tmp/somewhere -socket /tmp/myapp-socket
672 Alias / /tmp/somewhere/
674 Note that C</tmp> should I<not> exist: it's just a name to connect the two parts.
676 Again, if you want your app under C</theapp>, change the C<Alias> line to:
678 Alias /theapp /tmp/somewhere
680 Then start your Catalyst application:
683 $ ./script/myapp_fastcgi -l /tmp/myapp-socket
685 If you want to use a TCP socket, simply change the C</tmp> to a C<host:port> pair, both in Apache's configuration and on the command line of your application.
689 Upgrading your application to newer Catalyst versions is quite simple. After
690 installing the new Catalyst package, just run:
692 B<catalyst.pl -scripts>
694 One level above your application directory. This will update the scripts
695 directory only, and leave the rest of your app alone, If you wish to make use
696 of other parts of Catalyst that have been updated, leave off the B<-scripts>
697 argument, this will cause .new files to appear, for each module that has
698 either been updated, or is different to the original because you have changed
699 it. To find out what these changes are, type:
701 B<diff MyApp/lib/MyApp/View/TT.pm MyApp/lib/MyApp/View/TT.pm.new>
703 for each of the changed files. (This is a Unix command, Windows users will
704 need to find some equivalent). Copy any changes you need into your original
705 file, then remove the .new files. (This makes life less complicated when the
706 next upgrade comes around.)
710 Jess Robinson, C<jrobinson@cpan.org>
711 Andrew Ford, C<A.Ford@ford-mason.co.uk>
712 Marcus Ramberg, C<mramberg@cpan.org>
714 Please send comments, corrections and suggestions for improvements to
719 Add template examples.
725 This program is free software, you can redistribute it and/or modify
726 it under the same terms as Perl itself.