Make Module::Build make README automatically.
[catagits/Catalyst-Runtime.git] / lib / Catalyst / Manual / Cookbook.pod
CommitLineData
fc7ec1d9 1=head1 NAME
2
3Catalyst::Manual::Cookbook - Cooking with Catalyst
4
5=head1 DESCRIPTION
6
aba94964 7Yummy code like your mum used to bake!
fc7ec1d9 8
9=head1 RECIPES
10
11=head2 Force debug screen
12
13You can force Catalyst to display the debug screen at the end of the request by
51ef2818 14placing a C<die()> call in the C<end> action.
fc7ec1d9 15
61b1e958 16 sub end : Private {
17 my ( $self, $c ) = @_;
18 die "testing";
19 }
fc7ec1d9 20
aff93052 21If you're tired of removing and adding this all the time, you
51ef2818 22can easily add a condition. For example:
aff93052 23
8f8532e1 24 die "Testing" if $c->params->{dump_info};
aff93052 25
fc7ec1d9 26=head2 Disable statistics
27
28Just add this line to your application class if you don't want those nifty
29statistics in your debug messages.
30
31 sub Catalyst::Log::info { }
32
33=head2 Scaffolding
34
35Scaffolding is very simple with Catalyst.
51ef2818 36Just use Catalyst::Model::CDBI::CRUD as your base class.
fc7ec1d9 37
38 # lib/MyApp/Model/CDBI.pm
39 package MyApp::Model::CDBI;
40
41 use strict;
42 use base 'Catalyst::Model::CDBI::CRUD';
43
44 __PACKAGE__->config(
45 dsn => 'dbi:SQLite:/tmp/myapp.db',
46 relationships => 1
47 );
48
49 1;
50
51 # lib/MyApp.pm
52 package MyApp;
53
54 use Catalyst 'FormValidator';
55
56 __PACKAGE__->config(
57 name => 'My Application',
58 root => '/home/joeuser/myapp/root'
59 );
60
61b1e958 61 sub my_table : Global {
62 my ( $self, $c ) = @_;
63 $c->form( optional => [ MyApp::Model::CDBI::Table->columns ] );
64 $c->forward('MyApp::Model::CDBI::Table');
65 }
fc7ec1d9 66
67 1;
68
69Modify the $c->form() parameters to match your needs, and don't forget to copy
70the templates. ;)
71
5c0ff128 72=head2 Single file upload with Catalyst
aba94964 73
74To implement uploads in Catalyst you need to have a HTML form similiar to
75this:
76
77 <form action="/upload" method="post" enctype="multipart/form-data">
78 <input type="hidden" name="form_submit" value="yes">
79 <input type="file" name="my_file">
80 <input type="submit" value="Send">
81 </form>
82
51ef2818 83It's very important not to forget C<enctype="multipart/form-data"> in form. Uploads will not work without this.
aba94964 84
85Catalyst Controller module 'upload' action:
86
5c0ff128 87 sub upload : Global {
88 my ($self, $c) = @_;
4d89569d 89
90 if ( $c->request->parameters->{form_submit} eq 'yes' ) {
91
92 if ( my $upload = $c->request->upload('my_file') ) {
47ae6960 93
5c0ff128 94 my $filename = $upload->filename;
47ae6960 95 my $target = "/tmp/upload/$filename";
96
3ffaf022 97 unless ( $upload->link_to($target) || $upload->copy_to($target) ) {
47ae6960 98 die( "Failed to copy '$filename' to '$target': $!" );
5c0ff128 99 }
5c0ff128 100 }
101 }
4d89569d 102
5c0ff128 103 $c->stash->{template} = 'file_upload.html';
104 }
105
106=head2 Multiple file upload with Catalyst
107
108Code for uploading multiple files from one form needs little changes compared
109to single file upload.
110
111Form goes like this:
112
113 <form action="/upload" method="post" enctype="multipart/form-data">
114 <input type="hidden" name="form_submit" value="yes">
115 <input type="file" name="file1" size="50"><br>
116 <input type="file" name="file2" size="50"><br>
117 <input type="file" name="file3" size="50"><br>
118 <input type="submit" value="Send">
119 </form>
120
121Controller:
122
123 sub upload : Local {
124 my ($self, $c) = @_;
4d89569d 125
126 if ( $c->request->parameters->{form_submit} eq 'yes' ) {
127
128 for my $field ( $c->req->upload ) {
129
02a53b81 130 my $upload = $c->req->upload($field);
4d89569d 131 my $filename = $upload->filename;
47ae6960 132 my $target = "/tmp/upload/$filename";
133
3ffaf022 134 unless ( $upload->link_to($target) || $upload->copy_to($target) ) {
47ae6960 135 die( "Failed to copy '$filename' to '$target': $!" );
aba94964 136 }
137 }
61b1e958 138 }
4d89569d 139
5c0ff128 140 $c->stash->{template} = 'file_upload.html';
141 }
142
51ef2818 143C<for my $field ($c-E<gt>req->upload)> loops automatically over all file input
5c0ff128 144fields and gets input names. After that is basic file saving code, just like in
145single file upload.
aba94964 146
51ef2818 147Notice: C<die>ing might not be what you want to do, when an error occurs, but
148it works as an example. A better idea would be to store error C<$!> in
149$c->stash->{error} and show a custom error template displaying this message.
aba94964 150
5c0ff128 151For more information about uploads and usable methods look at
152C<Catalyst::Request::Upload> and C<Catalyst::Request>.
aba94964 153
deb90705 154=head2 Authentication with Catalyst::Plugin::Authentication::CDBI
155
156There are (at least) two ways to implement authentication with this plugin:
51ef2818 1571) only checking username and password;
deb90705 1582) checking username, password and the roles the user has
159
160For both variants you'll need the following code in your MyApp package:
161
162 use Catalyst qw/Session::FastMmap Static Authentication::CDBI/;
163
164 MyApp->config( authentication => { user_class => 'MyApp::M::MyApp::Users',
165 user_field => 'email',
166 password_field => 'password' });
167
168'user_class' is a Class::DBI class for your users table.
169'user_field' tells which field is used for username lookup (might be
51ef2818 170email, first name, surname etc.).
deb90705 171'password_field' is, well, password field in your table and by default
172password is stored in plain text. Authentication::CDBI looks for 'user'
173and 'password' fields in table, if they're not defined in the config.
174
51ef2818 175In PostgreSQL, the users table might be something like:
deb90705 176
51ef2818 177 CREATE TABLE users (
178 user_id serial,
179 name varchar(100),
180 surname varchar(100),
181 password varchar(100),
182 email varchar(100),
183 primary key(user_id)
184 );
deb90705 185
186We'll discuss the first variant for now:
51ef2818 1871. user:password login/auth without roles
deb90705 188
51ef2818 189To log in a user you might use an action like this:
deb90705 190
7c1078a4 191 sub login : Local {
deb90705 192 my ($self, $c) = @_;
193 if ($c->req->params->{username}) {
194 $c->session_login($c->req->params->{username},
61b1e958 195 $c->req->params->{password} );
deb90705 196 if ($c->req->{user}) {
197 $c->forward('?restricted_area');
198 }
199 }
61b1e958 200 }
deb90705 201
7c1078a4 202This action should not go in your MyApp class...if it does, it will
203conflict with the built-in method of the same name. Instead, put it
204in a Controller class.
205
deb90705 206$c->req->params->{username} and $c->req->params->{password} are html
61b1e958 207form parameters from a login form. If login succeeds, then
208$c->req->{user} contains the username of the authenticated user.
deb90705 209
51ef2818 210If you want to remember the user's login status in between further
211requests, then just use the C<$c-E<gt>session_login> method. Catalyst will
212create a session id and session cookie and automatically append session
213id to all urls. So all you have to do is just check $c->req->{user}
61b1e958 214where needed.
deb90705 215
51ef2818 216To log out a user, just call $c->session_logout.
deb90705 217
51ef2818 218Now let's take a look at the second variant:
2192. user:password login/auth with roles
deb90705 220
51ef2818 221To use roles you need to add the following parameters to MyApp->config in the 'authentication' section:
deb90705 222
223 role_class => 'MyApp::M::MyApp::Roles',
224 user_role_class => 'MyApp::M::MyApp::UserRoles',
225 user_role_user_field => 'user_id',
226 user_role_role_field => 'role_id',
227
228Corresponding tables in PostgreSQL could look like this:
229
51ef2818 230 CREATE TABLE roles (
231 role_id serial,
232 name varchar(100),
233 primary key(role_id)
234 );
235
236 CREATE TABLE user_roles (
237 user_role_id serial,
238 user_id int,
239 role_id int,
240 primary key(user_role_id),
241 foreign key(user_id) references users(user_id),
242 foreign key(role_id) references roles(role_id)
243 );
deb90705 244
61b1e958 245The 'roles' table is a list of role names and the 'user_role' table is
246used for the user -> role lookup.
deb90705 247
51ef2818 248Now if a logged-in user wants to see a location which is allowed only
249for people with an 'admin' role, in your controller you can check it
61b1e958 250with:
deb90705 251
61b1e958 252 sub add : Local {
deb90705 253 my ($self, $c) = @_;
254 if ($c->roles(qw/admin/)) {
255 $c->req->output("Your account has the role 'admin.'");
256 } else {
51ef2818 257 $c->req->output("You're not allowed to be here.");
deb90705 258 }
61b1e958 259 }
deb90705 260
51ef2818 261One thing you might need is to forward non-authenticated users to a login
262form if they try to access restricted areas. If you want to do this
263controller-wide (if you have one controller for your admin section) then it's
264best to add a user check to a '!begin' action:
deb90705 265
61b1e958 266 sub begin : Private {
deb90705 267 my ($self, $c) = @_;
268 unless ($c->req->{user}) {
269 $c->req->action(undef); ## notice this!!
270 $c->forward('?login');
271 }
61b1e958 272 }
deb90705 273
51ef2818 274Pay attention to $c->req->action(undef). This is needed because of the
275way $c->forward works - C<forward> to C<login> gets called, but after that
276Catalyst will still execute the action defined in the URI (e.g. if you
277tried to go to C</add>, then first 'begin' will forward to 'login', but after
278that 'add' will nonetheless be executed). So $c->req->action(undef) undefines any
279actions that were to be called and forwards the user where we want him/her
deb90705 280to be.
281
51ef2818 282And this is all you need to do.
deb90705 283
145074c2 284
285=head2 How to use Catalyst without mod_perl
286
287Catalyst applications give optimum performance when run under mod_perl.
61b1e958 288However sometimes mod_perl is not an option, and running under CGI is
51ef2818 289just too slow. There's also an alternative to mod_perl that gives
dec2a2a9 290reasonable performance named FastCGI.
145074c2 291
292B<Using FastCGI>
293
61b1e958 294To quote from L<http://www.fastcgi.com/>: "FastCGI is a language
295independent, scalable, extension to CGI that provides high performance
296without the limitations of specific server APIs." Web server support
297is provided for Apache in the form of C<mod_fastcgi> and there is Perl
298support in the C<FCGI> module. To convert a CGI Catalyst application
299to FastCGI one needs to initialize an C<FCGI::Request> object and loop
300while the C<Accept> method returns zero. The following code shows how
301it is done - and it also works as a normal, single-shot CGI script.
145074c2 302
303 #!/usr/bin/perl
304 use strict;
305 use FCGI;
306 use MyApp;
307
308 my $request = FCGI::Request();
309 while ($request->Accept() >= 0) {
1c61c726 310 MyApp->run;
145074c2 311 }
312
61b1e958 313Any initialization code should be included outside the request-accept
314loop.
145074c2 315
51ef2818 316There is one little complication, which is that C<MyApp-E<gt>run> outputs a
61b1e958 317complete HTTP response including the status line (e.g.:
318"C<HTTP/1.1 200>").
319FastCGI just wants a set of headers, so the sample code captures the
320output and drops the first line if it is an HTTP status line (note:
321this may change).
322
323The Apache C<mod_fastcgi> module is provided by a number of Linux
324distros and is straightforward to compile for most Unix-like systems.
325The module provides a FastCGI Process Manager, which manages FastCGI
326scripts. You configure your script as a FastCGI script with the
327following Apache configuration directives:
145074c2 328
329 <Location /fcgi-bin>
330 AddHandler fastcgi-script fcgi
331 </Location>
332
333or:
334
335 <Location /fcgi-bin>
336 SetHandler fastcgi-script
337 Action fastcgi-script /path/to/fcgi-bin/fcgi-script
338 </Location>
339
340C<mod_fastcgi> provides a number of options for controlling the FastCGI
341scripts spawned; it also allows scripts to be run to handle the
51ef2818 342authentication, authorization, and access check phases.
145074c2 343
61b1e958 344For more information see the FastCGI documentation, the C<FCGI> module
345and L<http://www.fastcgi.com/>.
145074c2 346
fc7ec1d9 347=head1 AUTHOR
348
349Sebastian Riedel, C<sri@oook.de>
deb90705 350Danijel Milicevic C<me@danijel.de>
351Viljo Marrandi C<vilts@yahoo.com>
61b1e958 352Marcus Ramberg C<mramberg@cpan.org>
fc7ec1d9 353
354=head1 COPYRIGHT
355
61b1e958 356This program is free software, you can redistribute it and/or modify it
357under the same terms as Perl itself.