You are on page 1of 237

Catalyst Manual

April 20, 2007

Contents
Catalyst::Manual::About
What is Catalyst? The short summary
What isnt Catalyst? . . . . . .
Web programming: The Olden Days .
The MVC pattern . . . . . . . . . . .
A simple example . . . . . . . . .
AUTHOR . . . . . . . . . . . . . . . .
SEE ALSO . . . . . . . . . . . . . . .
COPYRIGHT . . . . . . . . . . . . .
Catalyst::Manual::Actions
USING ACTIONS . . . . . . . . . .
WRITING YOUR OWN ACTIONS
ACTIONS . . . . . . . . . . . . . . .
Catalyst::Action::RenderView .
AUTHOR . . . . . . . . . . . . . . .
COPYRIGHT . . . . . . . . . . . .

.
.
.
.
.
.

.
.
.
.
.
.
.
.

.
.
.
.
.
.

.
.
.
.
.
.
.
.

.
.
.
.
.
.

.
.
.
.
.
.
.
.

.
.
.
.
.
.

.
.
.
.
.
.
.
.

.
.
.
.
.
.

Catalyst::Manual::Cookbook
RECIPES . . . . . . . . . . . . . . . . . . . .
Basics . . . . . . . . . . . . . . . . . . . . . .
Delivering a Custom Error Page . . . .
Disable statistics . . . . . . . . . . . . .
Enable debug status in the environment
Sessions . . . . . . . . . . . . . . . . . .
State . . . . . . . . . . . . . . . . . . . .
Store . . . . . . . . . . . . . . . . . . . .
Authentication magic . . . . . . . . . .
Using a session . . . . . . . . . . . . . .
EXAMPLE . . . . . . . . . . . . . . . .
More information . . . . . . . . . . . . .
Configure your application . . . . . . . .
Using YAML . . . . . . . . . . . . . . .
3

.
.
.
.
.
.
.
.

.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.

.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.

.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.

.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.

.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.

.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.

.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.

.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.

.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.

.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.

.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.

.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.

.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.

.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.

.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.

.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.

.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.

.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.

.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.

17
17
19
19
20
21
22
22
22

.
.
.
.
.
.

23
23
23
24
24
24
24

.
.
.
.
.
.
.
.
.
.
.
.
.
.

25
25
25
25
26
26
26
26
27
27
27
27
28
28
28

CONTENTS
Skipping your VCSs directories . . . . . . . . . . . . .
Users and Access Control . . . . . . . . . . . . . . . .
Authentication (logging in) . . . . . . . . . . . .
Pass-through login (and other actions) . . . . . .
Role-based Authorization . . . . . . . . . . . . .
Authentication/Authorization . . . . . . . . . . .
Modules . . . . . . . . . . . . . . . . . . . . . . .
Credential verifiers . . . . . . . . . . . . . . . . .
Storage backends . . . . . . . . . . . . . . . . . .
User objects . . . . . . . . . . . . . . . . . . . . .
ACL authorization . . . . . . . . . . . . . . . . .
Roles authorization . . . . . . . . . . . . . . . . .
Logging in . . . . . . . . . . . . . . . . . . . . . .
Checking roles . . . . . . . . . . . . . . . . . . .
EXAMPLE . . . . . . . . . . . . . . . . . . . . .
Using authentication in a testing environment . .
More information . . . . . . . . . . . . . . . . . .
Authorization . . . . . . . . . . . . . . . . . . . .
Introduction . . . . . . . . . . . . . . . . . . . . .
Role Based Access Control . . . . . . . . . . . . .
Access Control Lists . . . . . . . . . . . . . . . .
Models . . . . . . . . . . . . . . . . . . . . . . . . . . .
Using existing DBIC (etc.) classes with Catalyst
DBIx::Class as a Catalyst Model . . . . . . . . .
XMLRPC . . . . . . . . . . . . . . . . . . . . . .
Tip . . . . . . . . . . . . . . . . . . . . . . . . . .
Views . . . . . . . . . . . . . . . . . . . . . . . . . . .
Catalyst::View::TT . . . . . . . . . . . . . . . . .
Creating your View . . . . . . . . . . . . . . . . .
TT . . . . . . . . . . . . . . . . . . . . . . . . . .
TTSite . . . . . . . . . . . . . . . . . . . . . . . .
$c->stash . . . . . . . . . . . . . . . . . . . . . .
$c->uri for() . . . . . . . . . . . . . . . . . . . .
Adding RSS feeds . . . . . . . . . . . . . . . . . .
Using TT templates . . . . . . . . . . . . . . . .
Using XML::Feed . . . . . . . . . . . . . . . . . .
Final words . . . . . . . . . . . . . . . . . . . . .
Forcing the browser to download content . . . . .
Controllers . . . . . . . . . . . . . . . . . . . . . . . .
Extending RenderView (formerly DefaultEnd) . .
Action Types . . . . . . . . . . . . . . . . . . . .
Introduction . . . . . . . . . . . . . . . . . . . . .
Type attributes . . . . . . . . . . . . . . . . . . .
A word of warning . . . . . . . . . . . . . . . . .

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

29
30
30
30
30
31
32
32
32
32
32
33
33
33
33
34
34
34
34
35
36
37
37
37
37
39
39
40
40
40
40
41
42
43
43
44
45
45
46
46
47
47
47
50

CONTENTS
More Information . . . . . . . . . . . . . . . .
Component-based Subrequests . . . . . . . .
File uploads . . . . . . . . . . . . . . . . . . .
Single file upload with Catalyst . . . . . . . .
Multiple file upload with Catalyst . . . . . .
Forwarding with arguments . . . . . . . . . .
Deployment . . . . . . . . . . . . . . . . . . . . . .
mod perl Deployment . . . . . . . . . . . . .
Pros . . . . . . . . . . . . . . . . . . . . . . .
Speed . . . . . . . . . . . . . . . . . . . . . .
Shared memory for multiple apps . . . . . . .
Cons . . . . . . . . . . . . . . . . . . . . . . .
Memory usage . . . . . . . . . . . . . . . . .
Reloading . . . . . . . . . . . . . . . . . . . .
Cannot run multiple versions of the same app
Setup . . . . . . . . . . . . . . . . . . . . . .
1. Install Catalyst::Engine::Apache . . . . . .
2. Install Apache with mod perl . . . . . . .
3. Configure your application . . . . . . . . .
Test It . . . . . . . . . . . . . . . . . . . . . .
Other Options . . . . . . . . . . . . . . . . .
Non-root location . . . . . . . . . . . . . . . .
Static file handling . . . . . . . . . . . . . . .
Catalyst on shared hosting . . . . . . . . . .
FastCGI Deployment . . . . . . . . . . . . . .
Pros . . . . . . . . . . . . . . . . . . . . . . .
Speed . . . . . . . . . . . . . . . . . . . . . .
App Server . . . . . . . . . . . . . . . . . . .
Load-balancing . . . . . . . . . . . . . . . . .
Multiple versions of the same app . . . . . . .
Can run with threaded Apache . . . . . . . .
Cons . . . . . . . . . . . . . . . . . . . . . . .
More complex environment . . . . . . . . . .
Setup . . . . . . . . . . . . . . . . . . . . . .
1. Install Apache with mod fastcgi . . . . . .
2. Configure your application . . . . . . . . .
Standalone server mode . . . . . . . . . . . .
More Info . . . . . . . . . . . . . . . . . . . .
Development server deployment . . . . . . . .
Pros . . . . . . . . . . . . . . . . . . . . . . .
Simple . . . . . . . . . . . . . . . . . . . . . .
Cons . . . . . . . . . . . . . . . . . . . . . . .
Speed . . . . . . . . . . . . . . . . . . . . . .
Setup . . . . . . . . . . . . . . . . . . . . . .

5
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

50
50
51
51
51
52
53
53
53
53
53
53
53
53
53
54
54
54
54
55
55
55
55
55
56
56
56
56
57
57
57
57
57
57
57
57
58
58
58
58
59
59
59
59

CONTENTS
Start up the development server . . . . . . . . . .
Configuring Apache . . . . . . . . . . . . . . . . .
Quick deployment: Building PAR Packages . . . .
Follow these few points to try it out! . . . . . . . .
Serving static content . . . . . . . . . . . . . . . .
Introduction to Static::Simple . . . . . . . . . . . .
Usage . . . . . . . . . . . . . . . . . . . . . . . . .
Configuring . . . . . . . . . . . . . . . . . . . . . .
More information . . . . . . . . . . . . . . . . . . .
Serving manually with the Static plugin
(myapp server.pl) . . . . . . . . . . . . . .
Common problems with the Static plugin . . . . .
Serving Static Files with Apache . . . . . . . . . .
Caching . . . . . . . . . . . . . . . . . . . . . . . .
Cache Plugins . . . . . . . . . . . . . . . . . . . . .
Page Caching . . . . . . . . . . . . . . . . . . . . .
Template Caching . . . . . . . . . . . . . . . . . .
More Info . . . . . . . . . . . . . . . . . . . . . . .
Testing . . . . . . . . . . . . . . . . . . . . . . . . . . .
Testing . . . . . . . . . . . . . . . . . . . . . . . .
Tests . . . . . . . . . . . . . . . . . . . . . . . . . .
Creating tests . . . . . . . . . . . . . . . . . . . . .
Running tests locally . . . . . . . . . . . . . . . . .
Running tests remotely . . . . . . . . . . . . . . .
Test::WWW::Mechanize and Catalyst . . . . . . .
Further Reading . . . . . . . . . . . . . . . . . . .
More Information . . . . . . . . . . . . . . . . . . .
AUTHORS . . . . . . . . . . . . . . . . . . . . . . . . .
COPYRIGHT . . . . . . . . . . . . . . . . . . . . . . .

. . . .
. . . .
. . . .
. . . .
. . . .
. . . .
. . . .
. . . .
. . . .
with
. . . .
. . . .
. . . .
. . . .
. . . .
. . . .
. . . .
. . . .
. . . .
. . . .
. . . .
. . . .
. . . .
. . . .
. . . .
. . . .
. . . .
. . . .
. . . .

. . . . . . . . . .
. . . . . . . . . .
. . . . . . . . . .
. . . . . . . . . .
. . . . . . . . . .
. . . . . . . . . .
. . . . . . . . . .
. . . . . . . . . .
. . . . . . . . . .
HTTP::Daemon
. . . . . . . . . .
. . . . . . . . . .
. . . . . . . . . .
. . . . . . . . . .
. . . . . . . . . .
. . . . . . . . . .
. . . . . . . . . .
. . . . . . . . . .
. . . . . . . . . .
. . . . . . . . . .
. . . . . . . . . .
. . . . . . . . . .
. . . . . . . . . .
. . . . . . . . . .
. . . . . . . . . .
. . . . . . . . . .
. . . . . . . . . .
. . . . . . . . . .
. . . . . . . . . .

63
64
64
65
65
66
67
67
67
67
67
68
69
69
69
70
71
71
72

.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.

73
73
73
73
73
74
74
74
75

Catalyst::Manual::Internals
Initialization . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Request Lifecycle . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
AUTHOR . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

77
77
77
78

Catalyst::Manual::DevelopmentProcess
Aims of the Catalyst Core Team . . . . . . . . .
Charter for the Catalyst Core Team . . . . . . .
Intention . . . . . . . . . . . . . . . . . . . .
Membership . . . . . . . . . . . . . . . . . .
Technical Decisions. . . . . . . . . . . . . .
Organizational and Philosophical Decisions.
CPAN Releases . . . . . . . . . . . . . . . .
Public statements from the Core Team . . .

.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.

59
59
59
60
61
61
61
61
62

CONTENTS
COPYRIGHT

7
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

Catalyst::Manual::Intro
What is Catalyst? . . . . . . . . . . . . . . . . .
MVC . . . . . . . . . . . . . . . . . . . . . .
Flexibility . . . . . . . . . . . . . . . . . . .
Simplicity . . . . . . . . . . . . . . . . . . .
Quickstart . . . . . . . . . . . . . . . . . . . . . .
Install . . . . . . . . . . . . . . . . . . . . .
Setup . . . . . . . . . . . . . . . . . . . . .
Run . . . . . . . . . . . . . . . . . . . . . .
How It Works . . . . . . . . . . . . . . . . . . . .
Components . . . . . . . . . . . . . . . . . .
Views . . . . . . . . . . . . . . . . . . . . .
Models . . . . . . . . . . . . . . . . . . . . .
Controllers . . . . . . . . . . . . . . . . . .
ACCEPT CONTEXT . . . . . . . . . . . .
Application Class . . . . . . . . . . . . . . .
Context . . . . . . . . . . . . . . . . . . . .
Actions . . . . . . . . . . . . . . . . . . . .
Action types . . . . . . . . . . . . . . . . .
Built-in Private Actions . . . . . . . . . . .
Built-in actions in controllers/autochaining
URL Path Handling . . . . . . . . . . . . .
Parameter Processing . . . . . . . . . . . .
Flow Control . . . . . . . . . . . . . . . . .
Testing . . . . . . . . . . . . . . . . . . . .
SEE ALSO . . . . . . . . . . . . . . . . . . . . .
SUPPORT . . . . . . . . . . . . . . . . . . . . .
AUTHOR . . . . . . . . . . . . . . . . . . . . . .
COPYRIGHT . . . . . . . . . . . . . . . . . . .

78

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

79
79
79
80
81
81
81
82
82
82
82
83
84
87
88
88
89
91
92
95
95
97
97
97
99
100
100
100
100

Catalyst::Manual::Plugins
PLUGINS . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Catalyst::Plugin::Account::AutoDiscovery . . . . . . . . .
Catalyst::Plugin::Acme::Scramble . . . . . . . . . . . . . .
Catalyst::Plugin::Alarm . . . . . . . . . . . . . . . . . . . .
Catalyst::Plugin::AtomPP . . . . . . . . . . . . . . . . . . .
Catalyst::Plugin::AtomServer . . . . . . . . . . . . . . . . .
Catalyst::Plugin::Authentication . . . . . . . . . . . . . .
Catalyst::Plugin::Authentication::Credential::Atom . .
Catalyst::Plugin::Authentication::Credential::CHAP . .
Catalyst::Plugin::Authentication::Credential::Flickr .
Catalyst::Plugin::Authentication::Credential::Hatena .

.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.

101
101
101
101
101
101
101
102
102
102
102
102

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

CONTENTS
Catalyst::Plugin::Authentication::Credential::HTTP . . . . . . . . .
Catalyst::Plugin::Authentication::Credential::JugemKey . . . . . .
Catalyst::Plugin::Authentication::Credential::PAM . . . . . . . . . .
Catalyst::Plugin::Authentication::Credential::Password . . . . . .
Catalyst::Plugin::Authentication::Credential::TypeKey . . . . . . .
Catalyst::Plugin::Authentication::OpenID . . . . . . . . . . . . . . . .
Catalyst::Plugin::Authentication::Store . . . . . . . . . . . . . . . .
Catalyst::Plugin::Authentication::Store::DBIC . . . . . . . . . . . .
Catalyst::Plugin::Authentication::Store::Htpasswd . . . . . . . . . .
Catalyst::Plugin::Authentication::Store::HTTP . . . . . . . . . . . .
Catalyst::Plugin::Authentication::Store::LDAP . . . . . . . . . . . .
Catalyst::Plugin::Authentication::Store::Minimal . . . . . . . . . .
Catalyst::Plugin::Authentication::User::Hash . . . . . . . . . . . . .
Catalyst::Plugin::Authorization::ACL . . . . . . . . . . . . . . . . . .
Catalyst::Plugin::Authorization::Roles . . . . . . . . . . . . . . . . .
Catalyst::Plugin::AutoSession . . . . . . . . . . . . . . . . . . . . . . .
Catalyst::Plugin::Browser . . . . . . . . . . . . . . . . . . . . . . . . . .
Catalyst::Plugin::Cache::FastMmap, FileCache, BerkeleyDB, and Memcached
Catalyst::Plugin::Captcha . . . . . . . . . . . . . . . . . . . . . . . . . .
Catalyst::Plugin::CGI::Untaint . . . . . . . . . . . . . . . . . . . . . .
Catalyst::Plugin::Charsets::Japanese . . . . . . . . . . . . . . . . . .
Catalyst::Plugin::Compress::Bzip2 . . . . . . . . . . . . . . . . . . . .
Catalyst::Plugin::Compress::Deflate . . . . . . . . . . . . . . . . . . .
Catalyst::Plugin::Compress::Gzip . . . . . . . . . . . . . . . . . . . . .
Catalyst::Plugin::Compress::Zlib . . . . . . . . . . . . . . . . . . . . .
Catalyst::Plugin::ConfigLoader . . . . . . . . . . . . . . . . . . . . . .
Catalyst::Plugin::ConfigurablePathTo . . . . . . . . . . . . . . . . . .
Catalyst::Plugin::Continuation . . . . . . . . . . . . . . . . . . . . . .
Catalyst::Plugin::DateTime . . . . . . . . . . . . . . . . . . . . . . . . .
Catalyst::Plugin::DefaultEnd . . . . . . . . . . . . . . . . . . . . . . . .
Catalyst::Plugin::Devel::InPageLogs . . . . . . . . . . . . . . . . . . .
Catalyst::Plugin::Devel::InPageLogs::Log . . . . . . . . . . . . . . . .
Catalyst::Plugin::Dojo . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Catalyst::Plugin::Dumper . . . . . . . . . . . . . . . . . . . . . . . . . .
Catalyst::Plugin::Email . . . . . . . . . . . . . . . . . . . . . . . . . . .
Catalyst::Plugin::Email::Japanese . . . . . . . . . . . . . . . . . . . .
Catalyst::Plugin::Email::Page . . . . . . . . . . . . . . . . . . . . . . .
Catalyst::Plugin::EmailValid . . . . . . . . . . . . . . . . . . . . . . . .
Catalyst::Plugin::FillInForm . . . . . . . . . . . . . . . . . . . . . . . .
Catalyst::Plugin::Flavour . . . . . . . . . . . . . . . . . . . . . . . . . .
Catalyst::Plugin::FormValidator . . . . . . . . . . . . . . . . . . . . . .
Catalyst::Plugin::FormValidator::Simple . . . . . . . . . . . . . . . .
Catalyst::Plugin::Geography . . . . . . . . . . . . . . . . . . . . . . . .
Catalyst::Plugin::Geography::Implementation . . . . . . . . . . . . . .

102
102
102
102
102
102
102
103
103
103
103
103
103
103
103
103
103
104
104
104
104
104
104
104
104
104
104
104
104
104
104
104
104
104
104
105
105
105
105
105
105
105
105
105

CONTENTS
Catalyst::Plugin::HashedCookies . . . . . . . .
Catalyst::Plugin::HTML::Scrubber . . . . . . .
Catalyst::Plugin::HTML::Widget . . . . . . . .
Catalyst::Plugin::I18N . . . . . . . . . . . . . .
Catalyst::Plugin::JSONRPC . . . . . . . . . . . .
Catalyst::Plugin::Markdown . . . . . . . . . . .
Catalyst::Plugin::Message . . . . . . . . . . . .
Catalyst::Plugin::MobileAgent . . . . . . . . .
Catalyst::Plugin::Observe . . . . . . . . . . . .
Catalyst::Plugin::OrderedParams . . . . . . . .
Catalyst::Plugin::PageCache . . . . . . . . . .
Catalyst::Plugin::Params::Nested . . . . . . .
Catalyst::Plugin::Params::Nested::Expander
Catalyst::Plugin::Pluggable . . . . . . . . . .
Catalyst::Plugin::Prototype . . . . . . . . . .
Catalyst::Plugin::Redirect . . . . . . . . . . .
Catalyst::Plugin::RequestToken . . . . . . . .
Catalyst::Plugin::RequireSSL . . . . . . . . . .
Catalyst::Plugin::Scheduler . . . . . . . . . .
Catalyst::Plugin::Session . . . . . . . . . . . .
Catalyst::Plugin::Session::PerUser . . . . . .
Catalyst::Plugin::Session::State . . . . . . .
Catalyst::Plugin::Session::State::Cookie . .
Catalyst::Plugin::Session::State::URI . . . .
Catalyst::Plugin::Session::Store . . . . . . .
Catalyst::Plugin::Session::Store::CDBI . . .
Catalyst::Plugin::Session::Store::DBI . . . .
Catalyst::Plugin::Session::Store::DBIC . . .
Catalyst::Plugin::Session::Store::Dummy . .
Catalyst::Plugin::Session::Store::FastMmap
Catalyst::Plugin::Session::Store::File . . .
Catalyst::Plugin::Session::Store::Memcached
Catalyst::Plugin::Session::Test::Store . . .
Catalyst::Plugin::Singleton . . . . . . . . . .
Catalyst::Plugin::Snippets . . . . . . . . . . .
Catalyst::Plugin::SRU . . . . . . . . . . . . . .
Catalyst::Plugin::StackTrace . . . . . . . . . .
Catalyst::Plugin::Static . . . . . . . . . . . .
Catalyst::Plugin::Static::Simple . . . . . . .
Catalyst::Plugin::SubRequest . . . . . . . . . .
Catalyst::Plugin::SuperForm . . . . . . . . . .
Catalyst::Plugin::Textile . . . . . . . . . . . .
Catalyst::Plugin::Unicode . . . . . . . . . . . .
Catalyst::Plugin::Unicode::Encoding . . . . .

9
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

105
105
105
105
106
106
106
106
106
106
106
106
106
106
106
106
106
106
107
107
107
107
107
107
107
107
107
107
107
107
107
107
107
107
107
107
107
107
108
108
108
108
108
108

10

CONTENTS
Catalyst::Plugin::Upload::Basename . . . . . . . . .
Catalyst::Plugin::Upload::MD5 . . . . . . . . . . . .
Catalyst::Plugin::Upload::MIME . . . . . . . . . . .
Catalyst::Plugin::UploadProgress . . . . . . . . . .
Catalyst::Plugin::XMLRPC . . . . . . . . . . . . . . .
CONTROLLERS . . . . . . . . . . . . . . . . . . . . . . . . .
Catalyst::Controller::BindLex . . . . . . . . . . . .
MODELS . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Catalyst::Model::CDBI . . . . . . . . . . . . . . . . .
Catalyst::Model::CDBI::Plain . . . . . . . . . . . . .
Catalyst::Model::DBIC::Schema . . . . . . . . . . . .
Catalyst::Model::EVDB . . . . . . . . . . . . . . . . .
Catalyst::Model::File . . . . . . . . . . . . . . . . .
Catalyst::Model::Gedcom . . . . . . . . . . . . . . . .
Catalyst::Model::LDAP . . . . . . . . . . . . . . . . .
Catalyst::Model::NetBlogger . . . . . . . . . . . . .
Catalyst::Model::Plucene . . . . . . . . . . . . . . .
Catalyst::Model::Proxy . . . . . . . . . . . . . . . . .
Catalyst::Model::SVN . . . . . . . . . . . . . . . . . .
Catalyst::Model::Xapian . . . . . . . . . . . . . . . .
VIEWS . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Catalyst::View::Atom::XML . . . . . . . . . . . . . . .
Catalyst::View::Chart::Strip . . . . . . . . . . . . .
Catalyst::View::CSS::Squish . . . . . . . . . . . . .
Catalyst::View::Embperl . . . . . . . . . . . . . . . .
Catalyst::View::GD::Barcode . . . . . . . . . . . . .
Catalyst::View::GraphViz . . . . . . . . . . . . . . .
Catalyst::View::HTML::Template . . . . . . . . . . .
Catalyst::View::Jemplate . . . . . . . . . . . . . . .
Catalyst::View::JSON . . . . . . . . . . . . . . . . . .
Catalyst::View::Mason . . . . . . . . . . . . . . . . .
Catalyst::View::MicroMason . . . . . . . . . . . . . .
Catalyst::View::PHP . . . . . . . . . . . . . . . . . . .
Catalyst::View::PSP . . . . . . . . . . . . . . . . . . .
Catalyst::View::Petal . . . . . . . . . . . . . . . . .
Catalyst::View::TT . . . . . . . . . . . . . . . . . . .
Catalyst::View::XSLT . . . . . . . . . . . . . . . . . .
Catalyst::View::vCard . . . . . . . . . . . . . . . . .
OBSOLETE MODULES . . . . . . . . . . . . . . . . . . . . .
Catalyst::Model::DBIC . . . . . . . . . . . . . . . . .
Catalyst::Plugin::Authentication::Basic::Remote
Catalyst::Plugin::Authentication::CDBI . . . . . .
Catalyst::Plugin::Authentication::CDBI::Basic .
Catalyst::Plugin::Authentication::LDAP . . . . . .

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

108
108
108
108
108
108
108
109
109
109
109
109
109
109
109
109
109
109
109
109
110
110
110
110
110
110
110
110
110
110
110
110
110
110
110
110
111
111
111
111
111
111
111
111

CONTENTS

11

Catalyst::Plugin::Authentication::Simple . . . . . . .
Catalyst::Plugin::Authorization::CDBI::GroupToken .
Catalyst::Plugin::CDBI::Transaction . . . . . . . . . .
Catalyst::Plugin::Config::* . . . . . . . . . . . . . . . . . . .
Catalyst::Plugin::DefaultEnd . . . . . . . . . . . . . . .
Catalyst::Plugin::SanitizeUrl . . . . . . . . . . . . . .
Catalyst::Plugin::SanitizeUrl::PrepAction . . . . . .
Catalyst::Plugin::Session::* . . . . . . . . . . . . . . . . . .
AUTHORS . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
COPYRIGHT . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Catalyst::Manual::Tutorial
Detailed Table of Contents . .
Part 1: Introduction . . .
Part 2: Catalyst Basics .
Part 3: Basic CRUD . . .
Part 4: Authentication . .
Part 5: Authorization . .
Part 6: Debugging . . . .
Part 7: Testing . . . . . .
Part 8: Advanced CRUD
Part 9: Appendices . . . .
THANKS . . . . . . . . . . . .
AUTHOR . . . . . . . . . . . .

.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.

Catalyst::Manual::Tutorial::Intro
OVERVIEW . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
VERSIONS AND CONVENTIONS USED IN THIS TUTORIAL
CATALYST INSTALLATION . . . . . . . . . . . . . . . . . . . .
DATABASES . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
WHERE TO GET WORKING CODE . . . . . . . . . . . . . . .
AUTHOR . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Catalyst::Manual::Tutorial::CatalystBasics
OVERVIEW . . . . . . . . . . . . . . . . . . .
CREATE A CATALYST PROJECT . . . . . .
CREATE A SQLITE DATABASE . . . . . . .
EDIT THE LIST OF CATALYST PLUGINS .
DATABASE ACCESS WITH DBIx::Class . .
Create a DBIC Schema File . . . . . . . .
Create the DBIC Result Source Files . .
Use Catalyst::Model::DBIC::Schema To
CREATE A CATALYST CONTROLLER . . .
CATALYST VIEWS . . . . . . . . . . . . . . .

. . . . . .
. . . . . .
. . . . . .
. . . . . .
. . . . . .
. . . . . .
. . . . . .
Load The
. . . . . .
. . . . . .

.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.

. . . . . . . .
. . . . . . . .
. . . . . . . .
. . . . . . . .
. . . . . . . .
. . . . . . . .
. . . . . . . .
Model Class .
. . . . . . . .
. . . . . . . .

.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.

111
111
111
111
111
112
112
112
112
112

.
.
.
.
.
.
.
.
.
.
.
.

113
113
113
114
114
115
115
116
116
116
117
117
118

.
.
.
.
.
.

119
120
121
122
123
123
123

.
.
.
.
.
.
.
.
.
.

125
126
126
128
130
132
132
133
137
138
139

12

CONTENTS
Create a Catalyst View Using TTSite . . . . . . . .
Using RenderView for the Default View . . . . . . .
The History Leading Up To RenderView . . . . . . .
Globally Customize Every View . . . . . . . . . . . .
Create a TT Template Page . . . . . . . . . . . . . .
RUN THE APPLICATION . . . . . . . . . . . . . . . . .
USING THE DEFAULT TEMPLATE NAME . . . . . . .
RETURN TO A MANUALLY-SPECIFIED TEMPLATE
AUTHOR . . . . . . . . . . . . . . . . . . . . . . . . . . .

.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.

139
141
141
142
143
144
147
148
149

Catalyst::Manual::Tutorial::BasicCRUD
OVERVIEW . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
FORMLESS SUBMISSION . . . . . . . . . . . . . . . . . . . . . .
Include a Create Action in the Books Controller . . . . . . .
Include a Template for the url_create Action: . . . . . . . .
Try the url_create Feature . . . . . . . . . . . . . . . . . . .
MANUALLY BUILDING A CREATE FORM . . . . . . . . . . .
Add Method to Display The Form . . . . . . . . . . . . . . .
Add a Template for the Form . . . . . . . . . . . . . . . . . .
Add a Method to Process Form Values and Update Database
Test Out The Form . . . . . . . . . . . . . . . . . . . . . . . .
A SIMPLE DELETE FEATURE . . . . . . . . . . . . . . . . . . .
Include a Delete Link in the List . . . . . . . . . . . . . . . .
Add a Delete Action to the Controller . . . . . . . . . . . . .
Try the Delete Feature . . . . . . . . . . . . . . . . . . . . . .
Fixing a Dangerous URL . . . . . . . . . . . . . . . . . . . .
Try the Delete and Redirect Logic . . . . . . . . . . . . . . .
Using uri_for to Pass Query Parameters . . . . . . . . . . .
Try the Delete and Redirect With Query Param Logic . . . .
AUTHOR . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

151
151
152
152
153
154
155
155
156
156
157
157
157
159
160
160
161
161
162
162

Catalyst::Manual::Tutorial::Authentication
OVERVIEW . . . . . . . . . . . . . . . . . . . . . . .
BASIC AUTHENTICATION . . . . . . . . . . . . . .
Add Users and Roles to the Database . . . . . .
Add User and Role Information to DBIC Schema
Create New Result Source Objects . . . . . . .
Sanity-Check Reload of Development Server . . .
Include Authentication and Session Plugins . . .
Configure Authentication . . . . . . . . . . . . .
Add Login and Logout Controllers . . . . . . . .
Add a Login Form TT Template Page . . . . . .
Add Valid User Check . . . . . . . . . . . . . . .
Displaying Content Only to Authenticated Users

.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.

163
163
164
164
165
166
169
170
171
172
173
174
176

.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.

CONTENTS

13

Try Out Authentication . . . . . . . . . . . . . . . . . .


USING PASSWORD HASHES . . . . . . . . . . . . . . . . .
Get a SHA-1 Hash for the Password . . . . . . . . . . .
Switch to SHA-1 Password Hashes in the Database . . .
Enable
SHA-1
Hash
Passwords
lyst::Plugin::Authentication::Store::DBIC
Try Out the Hashed Passwords . . . . . . . . . . . . . .
USING THE SESSION FOR FLASH . . . . . . . . . . . . .
Try Out Flash . . . . . . . . . . . . . . . . . . . . . . .
AUTHOR . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

.
.
.
.
.
.
.
.
.

.
.
.
.

.
.
.
.
in
. .
. .
. .
. .
. .

.
.
.
.

.
.
.
.

.
.
.
.

.
.
.
.

.
.
.
.
.

.
.
.
.
.

.
.
.
.
.

.
.
.
.
.

. . . .
. . . .
. . . .
. . . .
Cata. . . .
. . . .
. . . .
. . . .
. . . .

176
177
177
178
178
179
179
181
181

Catalyst::Manual::Tutorial::Authorization
OVERVIEW . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
BASIC AUTHORIZATION . . . . . . . . . . . . . . . . . . . . .
Update Plugins to Include Support for Authorization . . . .
Add Config Information for Authorization . . . . . . . . . .
Add Role-Specific Logic to the Book List Template . . . .
Limit Books::add to admin Users . . . . . . . . . . . . . .
Try Out Authentication And Authorization . . . . . . . . .
ENABLE ACL-BASED AUTHORIZATION . . . . . . . . . . . .
Add the Catalyst::Plugin::Authorization::ACL Plugin
Add ACL Rules to the Application Class . . . . . . . . . .
Add a Method to Handle Access Violations . . . . . . . . .
AUTHOR . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.

183
183
184
184
184
185
186
188
188
188
188
190
190

Catalyst::Manual::Tutorial::Debugging
OVERVIEW . . . . . . . . . . . . . . . . . .
LOG STATEMENTS . . . . . . . . . . . . .
RUNNING CATALYST UNDER THE PERL
DEBUGGING MODULES FROM CPAN . .
AUTHOR . . . . . . . . . . . . . . . . . . . .

.
.
.
.
.

.
.
.
.
.

.
.
.
.
.

.
.
.
.
.

.
.
.
.
.

.
.
.
.
.

.
.
.
.
.

.
.
.
.
.

.
.
.
.
.

193
193
194
194
197
198

.
.
.
.
.
.

199
199
200
200
201
205
205

. . . . . . . .
. . . . . . . .
DEBUGGER
. . . . . . . .
. . . . . . . .

.
.
.
.
.

.
.
.
.
.

.
.
.
.
.

Catalyst::Manual::Tutorial::Testing
OVERVIEW . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
RUNNING THE CANNED CATALYST TESTS . . . . . . . . .
RUNNING A SINGLE TEST . . . . . . . . . . . . . . . . . . . . .
ADDING YOUR OWN TEST SCRIPT . . . . . . . . . . . . . . .
SUPPORTING BOTH PRODUCTION AND TEST DATABASES
AUTHOR . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

.
.
.
.
.
.

.
.
.
.
.
.

.
.
.
.
.
.

.
.
.
.
.
.

.
.
.
.
.
.

.
.
.
.
.
.

.
.
.
.
.
.

Catalyst::Manual::Tutorial::AdvancedCRUD
207
OVERVIEW . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 207
HTML::WIDGET FORM CREATION . . . . . . . . . . . . . . . . . . . . . . . . . . 208
Add the HTML::Widget Plugin . . . . . . . . . . . . . . . . . . . . . . . . . 208

14

CONTENTS
Add a Form Creation Helper Method . . . . . . . . . . . . . .
Add Actions to Display and Save the Form . . . . . . . . . .
Update the CSS . . . . . . . . . . . . . . . . . . . . . . . . .
Create a Template Page To Display The Form . . . . . . . .
Add Links for Create and Update via HTML::Widget . . . . .
Test The <HTML::Widget> Create Form . . . . . . . . . . .
HTML::WIDGET VALIDATION AND FILTERING . . . . . . . . . .
Add Constraints and Filters to the Widget Creation Method
Rebuild the Form Submission Method to Include Validation .
Try Out the Form . . . . . . . . . . . . . . . . . . . . . . . .
Enable DBIx::Class::HTMLWidget Support . . . . . . . . . . . . .
Add DBIx::Class::HTMLWidget to DBIC Model . . . . . . .
Use populate_from_widget in hw_create_do . . . . . . . . .
Try Out the Form . . . . . . . . . . . . . . . . . . . . . . . .
Rendering HTMLWidget Forms in a Table . . . . . . . . . . . . . . .
Add a New Element Container . . . . . . . . . . . . . . . .
Enable the New Element Container When Building the Form
Update the TT Template . . . . . . . . . . . . . . . . . . . .
Try Out the Form . . . . . . . . . . . . . . . . . . . . . . . .
AUTHOR . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

208
209
210
211
211
212
212
212
214
215
215
216
216
217
218
218
219
220
221
221

Catalyst::Manual::Tutorial::Appendices
OVERVIEW . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
APPENDIX 1: CUT AND PASTE FOR POD-BASED EXAMPLES
Un-indenting with Vi/Vim . . . . . . . . . . . . . . . . . . . .
Un-indenting with Emacs . . . . . . . . . . . . . . . . . . . .
APPENDIX 2: USING MYSQL AND POSTGRESQL . . . . . . . .
MySQL . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
PostgreSQL . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
APPENDIX 3: IMPROVED HASHING SCRIPT . . . . . . . . . . .
AUTHOR . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.

223
223
223
224
224
224
225
229
230
231

Catalyst::Manual::WritingPlugins
WHY PLUGINS? . . . . . . . . . . . . .
WHATS NEXT? . . . . . . . . . . . . . .
INTEGRATING YOUR PLUGIN . . . .
The request life-cycle . . . . . . . . .
What Plugins look like . . . . . . . .
Calling methods from your Plugin .
Overloading - Plugging into Catalyst
Storage and Configuration . . . . . .
EXAMPLE . . . . . . . . . . . . . . . . .
SEE ALSO . . . . . . . . . . . . . . . . .
THANKS TO . . . . . . . . . . . . . . . .

.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.

233
233
233
233
233
234
234
235
235
235
237
237

.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.

CONTENTS
COPYRIGHT . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
AUTHOR . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

15
237
237

16

CONTENTS

Catalyst::Manual::About - The
philosophy of Catalyst
This document is a basic introduction to the why of Catalyst. It does not teach
you how to write Catalyst applications; for an introduction to that please see Catalyst::Manual::Intro. Rather, it explains the basics of what Catalyst is typically used
for, and why you might want to use Catalyst to build your applications.

What is Catalyst? The short summary


Catalyst is a web application framework. This means that you use it to help build applications that run on the web, or that run using protocols used for the web. Catalyst is designed
to make it easy to manage the various tasks you need to do to run an application on the
web, either by doing them itself, or by letting you plug in existing Perl modules that do
what you need. There are a number of things you typically do with a web application. For
example:
* Interact with a web server
If youre on the web, youre relying on a web server, a program that sends files over
the web. There are a number of these, and your application has to do the right thing
to make sure that your program works with the web server youre using. If you change
your web server, you dont want to have to rewrite your entire application to work
with the new one.
* Do something based on a URI
Its typical for web applications to use URIs as a main way for
users to interact with the rest of the application;
various elements
of the URI will indicate what the application needs to do.
Thus,
http://www.mysite.com/add_record.cgi?name=John&title=President
will
add a person named John whose title is President to your database, and
http://www.mysite.com/catalog/display/23 will go to a display of item 23
in your catalog, and http://www.mysite.com/order_status/7582 will display
the status of order 7582, and http://www.mysite.com/add_comment/?page=8 will
display a form to add a comment to page 8. Your application needs to have a regular
way of processing these URIs so it knows what to do when such a request comes in.
17

18

Catalyst::Manual::About

* Interact with a data store


You probably use a database to keep track of your information. Your application
needs to interact with your database, so you can create, edit, and retrieve your data.
* Handle forms
When a user submits a form, you receive it, process it to make sure its been filled
in properly, and then do something based on the result--submit an order, update a
record, send e-mail, or return to the form if theres an error.
* Display results
If you have an application running on the web, people need to see things. You usually
want your application displayed on a web browser, in which case you will probably
be using a template system to help generate HTML code. But you might need other
kinds of display, such as PDF files, or other forms of output, such as RSS feeds or
e-mail.
* Manage users
You might need the concept of a user, someone whos allowed to use your system, and
is allowed to do certain things only. Perhaps normal users can only view or modify
their own information; administrative users can view or modify anything; normal
users can only order items for their own account; normal users can view things but
not modify them; order-processing users can send records to a different part of the
system; and so forth. You need a way of ensuring that people are who they say they
are, and that people only do the things theyre allowed to do.
* Develop the application itself
When youre writing or modifying the application, you want to have access to detailed
logs of what it is doing. You want to be able to write tests to ensure that it does what
its supposed to, and that new changes dont break the existing code.
Catalyst makes it easy to do all of these tasks, and many more. It is extremely flexible
in terms of what it allows you to do, and very fast. It has a very large number of plugins
that interact with existing Perl modules so that you can easily use them from within your
application.
* Interact with a web server?
Catalyst lets you use a number of different ones, and even comes with a built-in server
for testing or local deployment.
* Do something based on a URI?
Catalyst has extremely flexible systems for figuring out what to do based on a URI.
* Interact with a data store?
Catalyst has many plugins for different databases and database frameworks, and for
other non-database storage systems.

Web programming: The Olden Days

19

* Handle forms?
Catalyst has plugins available for several form creation and validation systems that
make it easy for the programmer to manage.
* Display results?
Catalyst has plugins available for a number of template modules and other output
packages.
* Manage users?
Catalyst has plugins that handle sessions, authentication, and authorization, in any
way you need.
* Developing the application?
Catalyst has detailed logging built-in, which you can configure as necessary, and
supports the easy creation of new tests--some of which are automatically created
when you begin writing a new application.

What isnt Catalyst?


Catalyst is not an out-of-the-box solution that allows you to set up a complete working
e-commerce application in ten minutes. (There are, however, several systems built on top
of Catalyst that can get you very close to a working app.)
Catalyst is designed for flexibility and power; to an extent, this comes at the expense of
simplicity. Programmers have many options for almost everything they need to do, which
means that any given need can be done in many ways, and finding the one thats right for
you, and learning the right way to do it, can take time. TIMTOWDI works both ways.
Catalyst is not designed for end users, but for working programmers.

Web programming: The Olden Days


Perl has long been favored for web applications. There are a wide variety of ways to use
Perl on the web, and things have changed over time. Its possible to handle everything with
very raw Perl code:
print "Content-type: text/html\n\n<center><h1>Hello
World!</h1></center>";
for example, or
my @query_elements = split(/&/, $ENV{QUERY_STRING});
foreach my $element (@query_elements) {
my ($name, $value) = split(/=/, $element);
# do something with your parameters, or kill yourself
# in frustration for having to program like this
}

20

Catalyst::Manual::About

Much better than this is to use Lincoln Steins great CGI module, which smoothly
handles a wide variety of common tasks--parameter parsing, generating form elements from
Perl data structures, printing http headers, escaping text, and very many more, all with
your choice of functional or object-oriented style. While CGI was revolutionary and is still
widely used, it has various drawbacks that make it unsuitable for larger applications: it is
slow; your code with it generally combines application logic and display code; and it makes
it very difficult to handle larger applications with complicated control flow.
A variety of frameworks followed, of which the most widely used is probably
CGI::Application, which encourages the development of modular code, with easy-tounderstand control-flow handling, the use of plugins and templating systems, and the
like. Other systems include AxKit, which is designed for use with XML running under mod perl; Maypole--upon which Catalyst was originally based--designed for the easy
development of powerful web databases; Jifty, which does a great deal of automation
in helping to set up web sites with many complex features; and Ruby on Rails (see
http://www.rubyonrails.org1 ), written of course in Ruby and among the most popular web
development systems. Is it not the purpose of this document to criticize or even briefly
evaluate these other frameworks; they may be useful for you and if so we encourage you to
give them a try.

The MVC pattern


MVC, or Model-View-Controller, is a model currently favored for web applications. This
design pattern is originally from the Smalltalk programming language. The basic idea is that
the three main areas of an application--handling application flow (Controller), processing
information (Model), and outputting the results (View)--are kept separate, so that it is
possible to change or replace any one without affecting the others, and so that if youre
interested in one particular aspect, you know where to find it.
Discussions of MVC often degenerate into nitpicky arguments about the history of the
pattern, and exactly what usually or should go into the Controller or the Model. We have
no interest in joining such a debate. In any case, Catalyst does not enforce any particular
setup; you are free to put any sort of code in any part of your application, and this discussion,
along with others elsewhere in the Catalyst documentation, are only suggestions based on
what we think works well. In most Catalyst applications, each branch of MVC will be made
of up of several Perl modules that can handle different needs in your application.
The purpose of the Model is to access and modify data. Typically the Model will
interact with a relational database, but its also common to use other data sources, such as
the Xapian search engine or an LDAP server.
The purpose of the View is to present data to the user. Typical Views use a templating
module to generate HTML code, using Template Toolkit, Mason, HTML::Template, or the
like, but its also possible to generate PDF output, send e-mail, etc., from a View. In
Catalyst applications the View is usually a small module, just gluing some other module
into Catalyst; the display logic is written within the template itself.
1

http://www.rubyonrails.org

The MVC pattern

21

The Controller is Catalyst itself. When a request is made to Catalyst, it will be received
by one of your Controller modules; this module will figure out what the user is trying to
do, gather the necessary data from a Model, and send it to a View for display.

A simple example
The general idea is that you should be able to change things around without affecting the
rest of your application. Lets look at a very simple example (keeping in mind that there are
many ways of doing this, and what were discussing is one possible way, not the only way).
Suppose you have a record to display. It doesnt matter if its a catalog entry, a library
book, a music CD, a personnel record, or anything else, but lets pretend its a catalog
entry. A user is given a URL such as http://www.mysite.com/catalog/display/2782.
Now what?
First, Catalyst figures out that youre using the catalog Controller (how Catalyst figures this out is entirely up to you; URL dispatching is extremely flexible in Catalyst). Then
Catalyst determines that you want to use a display method in your catalog Controller.
(There could be other display methods in other Controllers, too.) Somewhere in this process, its possible that youll have authentication and authorization routines to make sure
that the user is registered and is allowed to display a record. The Controllers display
method will then extract 2782 as the record you want to retrieve, and make a request to a
Model for that record. The Controller will then look at what the Model returns: if theres
no record, the Controller will ask the View to display an error message, otherwise it will
hand the View the record and ask the View to display it. In either case, the View will then
generate an HTML page, which Catalyst will send to the users browser, using whatever
web server youve configured.
How does this help you?
In many ways. Suppose you have a small catalog now, and youre using a lightweight
database such as SQLite, or maybe just a text file. But eventually your site grows, and you
need to upgrade to something more powerful--MySQL or Postgres, or even Oracle or DB2.
If your Model is separate, you only have to change one thing, the Model; your Controller
can expect that if it issues a query to the Model, it will get the right kind of result back.
What about the View? The idea is that your template is concerned almost entirely
with display, so that you can hand it off to a designer who doesnt have to worry about
how to write code. If you get all the data in the Controller and then pass it to the View,
the template isnt responsible for any kind of data processing. And if you want to change
your output, its simple: just write a new View. If your Controller is already getting the
data you need, you can pass it in the same way, and whether you display the results to a
web browser, generate a PDF, or e-mail the results back to the user, the Controller hardly
changes at all--its up to the View.
And throughout the whole process, most of the tools you need are either part of Catalyst
(the parameter-processing routines that extract 2782 from the URL, for example) or are
easily plugged into it (the authentication routines, or the plugins for using Template Toolkit
as your View).
Now, Catalyst doesnt enforce very much at all. Template Toolkit is a very powerful

22

Catalyst::Manual::About

templating system, and you can connect to a database, issue queries, and act on them from
within a TT-based View, if you want. You can handle paging (i.e. retrieving only a portion
of the total records possible) in your Controller or your Model. In the above example, your
Controller looked at the query result, determining whether to ask the View for a no-result
error message, or for a result display; but its perfectly possible to hand your query result
directly to the View, and let your template decide what to do. Its up to you; Catalyst
doesnt enforce anything.
In some cases there might be very good reasons to do things a certain way (issuing
database queries from a template defeats the whole purpose of separation-of-concerns, and
will drive your designer crazy), while in others its just a matter of personal preference
(perhaps your template, rather than your Controller, is the better place to decide what to
display if you get an empty result). Catalyst just gives you the tools.

AUTHOR
Jesse Sheidlower, jester@panix.com

SEE ALSO
Catalyst, Catalyst::Manual::Intro

COPYRIGHT
This program is free software, you can redistribute it and/or modify it under the same terms
as Perl itself.

Catalyst::Manual::Actions Catalyst Reusable Actions


This section of the manual describes the reusable action system in Catalyst, how they
work, descriptions of some existing ones, and how to write your own. Reusable actions
are attributes on Catalyst methods that allow you to decorate your method with functions
running before or after the method call. This can be used to implement commonly used
action patterns, while still leaving you full freedom to customize them.

USING ACTIONS
This is pretty simple. It works just like the normal dispatch attributes you are used to, like
Local or Private:
sub Hello :Local :ActionClass(SayBefore) {
$c->res->output( Hello .$c->stash->{what} );
}
In this example, we expect the SayBefore action to magically populate stash with something relevant before Hello is run. In the next section well show you how to implement it.
If you want it in another namespace than Catalyst::Action you can prefix the action name
with a +, for instance +Foo::SayBefore, or if you just want it under your application
namespace instead, use MyAction, like MyAction(SayBefore).

WRITING YOUR OWN ACTIONS


Implementing the action itself is almost as easy. Just use Catalyst::Action as a base class
and decorate the execute call in the Action class:
package Catalyst::Action::SayBefore;
use base Catalyst::Action;
sub execute {
my $self = shift;
my ( $controller, $c, $test ) = @_;
23

24

Catalyst::Manual::Actions

$c->stash->{what} = world;
$self->NEXT::execute( @_ );
};
1;
If you want to do something after the action, just put it after the execute call. Pretty
simple, huh?

ACTIONS
Catalyst::Action::RenderView
This is meant to decorate end actions.
Its similar in operation to Catalyst::Plugin::DefaultEnd, but allows you to decide on an action level rather than on an
application level where it should be run.

AUTHOR
The Catalyst Core Team - see http://catalyst.perl.org/

COPYRIGHT
This program is free software. You can redistribute it and/or modify it under the same
terms as Perl itself.

Catalyst::Manual::Cookbook Cooking with Catalyst


Yummy code like your mum used to bake!

RECIPES
Basics
These recipes cover some basic stuff that is worth knowing for catalyst developers.

Delivering a Custom Error Page


By default, Catalyst will display its own error page whenever it encounters an error in your
application. When running under -Debug mode, the error page is a useful screen including
the error message and Data::Dump output of the relevant parts of the $c context object.
When not in -Debug, users see a simple Please come back later screen.
To use a custom error page, use a special end method to short-circuit the error processing. The following is an example; you might want to adjust it further depending on the
needs of your application (for example, any calls to fillform will probably need to go into
this end method; see Catalyst::Plugin::FillInForm).
sub end : Private {
my ( $self, $c ) = @_;
if ( scalar @{ $c->error } ) {
$c->stash->{errors}
= $c->error;
$c->stash->{template} = errors.tt;
$c->forward(MyApp::View::TT);
$c->error(0);
}
return 1 if $c->response->status =~ /^3\d\d$/;
return 1 if $c->response->body;

25

26

Catalyst::Manual::Cookbook

unless ( $c->response->content_type ) {
$c->response->content_type(text/html; charset=utf-8);
}
$c->forward(MyApp::View::TT);
}
You can manually set errors in your code to trigger this page by calling
$c->error( You broke me! );

Disable statistics
Just add this line to your application class if you dont want those nifty statistics in your
debug messages.
sub Catalyst::Log::info { }

Enable debug status in the environment


Normally you enable the debugging info by adding the -Debug flag to your use Catalyst
statement. However, you can also enable it using environment variable, so you can (for example) get debug info without modifying your application scripts. Just set CATALYST_DEBUG
or &lt;MYAPP&gt;_DEBUG to a true value.

Sessions
When you have your users identified, you will want to somehow remember that fact, to
save them from having to identify themselves for every single page. One way to do this is
to send the username and password parameters in every single page, but thats ugly, and
wont work for static pages.
Sessions are a method of saving data related to some transaction, and giving the whole
collection a single ID. This ID is then given to the user to return to us on every page they
visit while logged in. The usual way to do this is using a browser cookie.
Catalyst uses two types of plugins to represent sessions:

State
A State module is used to keep track of the state of the session between the users browser,
and your application.
A common example is the Cookie state module, which sends the browser a cookie containing the session ID. It will use default value for the cookie name and domain, so will
just work when used.

Basics

27

Store
A Store module is used to hold all the data relating to your session, for example the users
ID, or the items for their shopping cart. You can store data in memory (FastMmap), in a
file (File) or in a database (DBI).

Authentication magic
If you have included the session modules in your application, the Authentication modules
will automagically use your session to save and retrieve the user data for you.

Using a session
Once the session modules are loaded, the session is available as $c->session, and can be
writen to and read from as a simple hash reference.

EXAMPLE
use Catalyst qw/
Session
Session::Store::FastMmap
Session::State::Cookie
/;

## Write data into the session


sub add_item : Local {
my ( $self, $c ) = @_;
my $item_id = $c->req->param("item");
push @{ $c->session->{items} }, $item_id;
}
## A page later we retrieve the data from the session:
sub get_items : Local {
my ( $self, $c ) = @_;
$c->stash->{items_to_display} = $c->session->{items};
}

28

Catalyst::Manual::Cookbook

More information
http://search.cpan.org/dist/Catalyst-Plugin-Session2
http://search.cpan.org/dist/Catalyst-Plugin-Session-State-Cookie3
http://search.cpan.org/dist/Catalyst-Plugin-Session-State-URI4
http://search.cpan.org/dist/Catalyst-Plugin-Session-Store-FastMmap5
http://search.cpan.org/dist/Catalyst-Plugin-Session-Store-File6
http://search.cpan.org/dist/Catalyst-Plugin-Session-Store-DBI7

Configure your application


You configure your application with the config method in your application class. This can
be hard-coded, or brought in from a separate configuration file.

Using YAML
YAML is a method for creating flexible and readable configuration files. Its a great way to
keep your Catalyst application configuration in one easy-to-understand location.
In your application class (e.g. lib/MyApp.pm):
use YAML;
# application setup
__PACKAGE__->config( YAML::LoadFile(__PACKAGE__->config->{home} . /
myapp.yml) );
__PACKAGE__->setup;
Now create myapp.yml in your application home:
--- #YAML:1.0
# DO NOT USE TABS FOR INDENTATION OR label/value SEPARATION!!!
name:
MyApp
# session; perldoc Catalyst::Plugin::Session::FastMmap
session:
expires:
3600
rewrite:
0
storage:
/tmp/myapp.session
2

http://search.cpan.org/dist/Catalyst-Plugin-Session
http://search.cpan.org/dist/Catalyst-Plugin-Session-State-Cookie
4
http://search.cpan.org/dist/Catalyst-Plugin-Session-State-URI
5
http://search.cpan.org/dist/Catalyst-Plugin-Session-Store-FastMmap
6
http://search.cpan.org/dist/Catalyst-Plugin-Session-Store-File
7
http://search.cpan.org/dist/Catalyst-Plugin-Session-Store-DBI
3

Skipping your VCSs directories

29

# emails; perldoc Catalyst::Plugin::Email


# this passes options as an array :(
email:
- SMTP
- localhost
This is equivalent to:
# configure base package
__PACKAGE__->config( name => MyApp );
# configure authentication
__PACKAGE__->config->{authentication} = {
user_class => MyApp::Model::MyDB::Customer,
...
};
# configure sessions
__PACKAGE__->config->{session} = {
expires => 3600,
...
};
# configure email sending
__PACKAGE__->config->{email} = [qw/SMTP localhost/];
See also YAML.

Skipping your VCSs directories


Catalyst uses Module::Pluggable to load Models, Views and Controllers. Module::Pluggable
will scan through all directories and load modules it finds. Sometimes you might want
to skip some of these directories, for example when your version control system makes a
subdirectory with meta-information in every version-controlled directory. While Catalyst
skips subversion and CVS directories already, there are other source control systems. Here
is the configuration you need to add their directories to the list to skip.
You can make catalyst skip these directories using the Catalyst config:
# Configure the application
__PACKAGE__->config(
name => MyApp,
setup_components => { except => qr/SCCS/ },
);
See the Module::Pluggable manual page for more information on except and other
options.

30

Catalyst::Manual::Cookbook

Users and Access Control


Most multiuser, and some single user web applications require that users identify themselves,
and the application is often required to define those roles. The recipes below describe some
ways of doing this.

Authentication (logging in)


This is extensively covered in other documentation; see in particular Catalyst::Plugin::Authentication and the Authentication chapter of the Tutorial at Catalyst::Manual::Tutorial::Authorization.

Pass-through login (and other actions)


An easy way of having assorted actions that occur during the processing of a request that
are orthogonal to its actual purpose - logins, silent commands etc. Provide actions for these,
but when theyre required for something else fill e.g. a form variable login and have a sub
begin like so:
sub begin : Private {
my ($self, $c) = @_;
foreach my $action (qw/login docommand foo bar whatever/) {
if ($c->req->params->{"__${action}"}) {
$c->forward($action);
}
}
}

Role-based Authorization
For more advanced access control, you may want to consider using role-based authorization.
This means you can assign different roles to each user, e.g. user, admin, etc.
The login and logout methods and view template are exactly the same as in the
previous example.
The Catalyst::Plugin::Authorization::Roles plugin is required when implementing roles:
use Catalyst qw/
Authentication
Authentication::Credential::Password
Authentication::Store::Htpasswd
Authorization::Roles
/;

Users and Access Control


Roles
are
implemented
automatically
when
using
lyst::Authentication::Store::Htpasswd:
# no additional role configuration required
__PACKAGE__->config->{authentication}{htpasswd} = "passwdfile";

31
Cata-

Or can be set up manually when using Catalyst::Authentication::Store::DBIC:


# Authorization using a many-to-many role relationship
__PACKAGE__->config->{authorization}{dbic} = {
role_class
=> My::Model::DBIC::Role,
role_field
=> name,
user_role_user_field => user,
# DBIx::Class only (omit if using Class::DBI)
role_rel
=> user_role,
# Class::DBI only, (omit if using DBIx::Class)
user_role_class
=> My::Model::CDBI::UserRole
user_role_role_field => role,
};
To restrict access to any action, you can use the check_user_roles method:
sub restricted : Local {
my ( $self, $c ) = @_;
$c->detach("unauthorized")
unless $c->check_user_roles( "admin" );
# do something restricted here
}
You can also use the assert_user_roles method. This just gives an error if the current
user does not have one of the required roles:
sub also_restricted : Global {
my ( $self, $c ) = @_;
$c->assert_user_roles( qw/ user admin / );
}

Authentication/Authorization
This is done in several steps:
Verification
Getting the user to identify themselves, by giving you some piece of information known

32

Catalyst::Manual::Cookbook
only to you and the user. Then you can assume that the user is who they say they
are. This is called credential verification.

Authorization
Making sure the user only accesses functions you want them to access. This is done by
checking the verified users data against your internal list of groups, or allowed persons
for the current page.

Modules
The Catalyst Authentication system is made up of many interacting modules, to give you
the most flexibility possible.

Credential verifiers
A Credential module tables the user input, and passes it to a Store, or some other system,
for verification. Typically, a user object is created by either this module or the Store and
made accessible by a $c->user call.
Examples:
Password - Simple username/password checking.
HTTPD
- Checks using basic HTTP auth.
TypeKey - Check using the typekey system.

Storage backends
A Storage backend contains the actual data representing the users. It is queried by the
credential verifiers. Updating the store is not done within this system, you will need to do
it yourself.
Examples:
DBIC
- Storage using a database.
Minimal - Storage using a simple hash (for testing).

User objects
A User object is created by either the storage backend or the credential verifier, and filled
with the retrieved user information.
Examples:
Hash
- A simple hash of keys and values.

ACL authorization
ACL stands for Access Control List. The ACL plugin allows you to regulate access on a
path by path basis, by listing which users, or roles, have access to which paths.

Users and Access Control

33

Roles authorization
Authorization by roles is for assigning users to groups, which can then be assigned to ACLs,
or just checked when needed.

Logging in
When you have chosen your modules, all you need to do is call the $c->login method. If
called with no parameters, it will try to find suitable parameters, such as username and
password, or you can pass it these values.

Checking roles
Role checking is done by using the $c->check_user_roles method, this will check using
the currently logged in user (via $c->user). You pass it the name of a role to check, and it
returns true if the user is a member.

EXAMPLE
use Catalyst qw/Authentication
Authentication::Credential::Password
Authentication::Store::Htpasswd
Authorization::Roles/;
__PACKAGE__->config->{authentication}{htpasswd} = "passwdfile";
sub login : Local {
my ($self, $c) = @_;
if (
my $user = $c->req->param("user")
and my $password = $c->req->param("password") )
{
if ( $c->login( $user, $password ) ) {
$c->res->body( "hello " . $c->user->name );
} else {
# login incorrect
}
}
else {
# invalid form input
}
}
sub restricted : Local {
my ( $self, $c ) = @_;

34

Catalyst::Manual::Cookbook

$c->detach("unauthorized")
unless $c->check_user_roles( "admin" );
# do something restricted here
}

Using authentication in a testing environment


Ideally, to write tests for authentication/authorization code one would first set up a test
database with known data, then use Test::WWW::Mechanize::Catalyst to simulate a user
logging in. Unfortunately the former can be rather awkward, which is why its a good thing
that the authentication framework is so flexible.
Instead of using a test database, one can simply change the authentication store to
something a bit easier to deal with in a testing environment. Additionally, this has the
advantage of not modifying ones database, which can be problematic if one forgets to use
the testing instead of production database.
e.g.,
use Catalyst::Plugin::Authentication::Store::Minimal::Backend;
# Sets up the user test_user with password test_pass
MyApp->default_auth_store(
Catalyst::Plugin::Authentication::Store::Minimal::Backend->new({
test_user => { password => test_pass },
})
);
Now, your test code can call $c-login(test user, test pass)> and successfully login,
without messing with the database at all.

More information
http://search.cpan.org/perldoc?Catalyst::Plugin::Authentication8 has a longer explanation.

Authorization
Introduction
Authorization is the step that comes after authentication. Authentication establishes that
the user agent is really representing the user we think its representing, and then authorization determines what this user is allowed to do.
8

http://search.cpan.org/perldoc?Catalyst::Plugin::Authentication

Users and Access Control

35

Role Based Access Control


Under role based access control each user is allowed to perform any number of roles. For
example, at a zoo no one but specially trained personnel can enter the moose cage (Mynd
you, mse bites kan be pretty nasti!). For example:
package Zoo::Controller::MooseCage;
sub feed_moose : Local {
my ( $self, $c ) = @_;
$c->model( "Moose" )->eat( $c->req->param("food") );
}
With this action, anyone can just come into the moose cage and feed the moose, which
is a very dangerous thing. We need to restrict this action, so that only a qualified moose
feeder can perform that action.
The Authorization::Roles plugin lets us perform role based access control checks. Lets
load it:
use Catalyst qw/
Authentication # yadda yadda
Authorization::Roles
/;
And now our action should look like this:
sub feed_moose : Local {
my ( $self, $c ) = @_;
if ( $c->check_roles( "moose_feeder" ) ) {
$c->model( "Moose" )->eat( $c->req->param("food") );
} else {
$c->stash->{error} = "unauthorized";
}
}
This checks $c->user, and only if the user has all the roles in the list, a true value is
returned.
check_roles has a sister method, assert_roles, which throws an exception if any roles
are missing.
Some roles that might actually make sense in, say, a forum application:
administrator
moderator

each with a distinct task (system administration versus content administration).

36

Catalyst::Manual::Cookbook

Access Control Lists


Checking for roles all the time can be tedious and error prone.
The Authorization::ACL plugin lets us declare where wed like checks to be done automatically for us.
For example, we may want to completely block out anyone who isnt a moose_feeder
from the entire MooseCage controller:
Zoo->deny_access_unless( "/moose_cage", [qw/moose_feeder/] );
The role list behaves in the same way as check_roles. However, the ACL plugin isnt
limited to just interacting with the Roles plugin. We can use a code reference instead. For
example, to allow either moose trainers or moose feeders into the moose cage, we can create
a more complex check:
Zoo->deny_access_unless( "/moose_cage", sub {
my $c = shift;
$c->check_roles( "moose_trainer" ) || $c->check_roles( "moose_feeder"
);
});
The more specific a role, the earlier it will be checked. Lets say moose feeders are now
restricted to only the feed_moose action, while moose trainers get access everywhere:
Zoo->deny_access_unless( "/moose_cage", [qw/moose_trainer/] );
Zoo->allow_access_if( "/moose_cage/feed_moose", [qw/moose_feeder/]);
When the feed_moose action is accessed the second check will be made. If the user is
a moose_feeder, then access will be immediately granted. Otherwise, the next rule in line
will be tested - the one checking for a moose_trainer. If this rule is not satisfied, access
will be immediately denied.
Rules applied to the same path will be checked in the order they were added.
Lastly, handling access denial events is done by creating an access_denied private
action:
sub access_denied : Private {
my ( $self, $c, $action ) = @_;

}
This action works much like auto, in that it is inherited across namespaces (not like
object oriented code). This means that the access_denied action which is nearest to the
action which was blocked will be triggered.
If this action does not exist, an error will be thrown, which you can clean up in your
end private action instead.

Models

37

Also, its important to note that if you restrict access to / then end, default, etc will
also be restricted.
MyApp->acl_allow_root_internals;
will create rules that permit access to end, begin, and auto in the root of your app (but
not in any other controller).

Models
Models are where application data belongs. Catalyst is exteremely flexible with the kind of
models that it can use. The recipes here are just the start.

Using existing DBIC (etc.) classes with Catalyst


Many people have existing Model classes that they would like to use with Catalyst (or,
conversely, they want to write Catalyst models that can be used outside of Catalyst, e.g.
in a cron job). Its trivial to write a simple component in Catalyst that slurps in an outside
Model:
package MyApp::Model::DB;
use base qw/Catalyst::Model::DBIC::Schema/;
__PACKAGE__->config(
schema_class => Some::DBIC::Schema,
connect_info => [dbi:SQLite:foo.db, , , {AutoCommit=>1}];
);
1;
and thats it! Now Some::DBIC::Schema is part of your Cat app as MyApp::Model::DB.

DBIx::Class as a Catalyst Model


See Catalyst::Model::DBIC::Schema.

XMLRPC
Unlike SOAP, XMLRPC is a very simple (and imo elegant) web-services protocol, exchanging small XML messages like these:
Request:
POST /api HTTP/1.1
TE: deflate,gzip;q=0.3
Connection: TE, close
Accept: text/xml
Accept: multipart/*
Host: 127.0.0.1:3000
User-Agent: SOAP::Lite/Perl/0.60

38

Catalyst::Manual::Cookbook

Content-Length: 192
Content-Type: text/xml
<?xml version="1.0" encoding="UTF-8"?>
<methodCall>
<methodName>add</methodName>
<params>
<param><value><int>1</int></value></param>
<param><value><int>2</int></value></param>
</params>
</methodCall>
Response:
Connection: close
Date: Tue, 20 Dec 2005 07:45:55 GMT
Content-Length: 133
Content-Type: text/xml
Status: 200
X-Catalyst: 5.70
<?xml version="1.0" encoding="us-ascii"?>
<methodResponse>
<params>
<param><value><int>3</int></value></param>
</params>
</methodResponse>
Now follow these few steps to implement the application:
1. Install Catalyst (5.61 or later), Catalyst::Plugin::XMLRPC (0.06 or later) and
SOAP::Lite (for XMLRPCsh.pl).
2. Create an application framework:
% catalyst.pl MyApp
...
% cd MyApp
3. Add the XMLRPC plugin to MyApp.pm
use Catalyst qw/-Debug Static::Simple XMLRPC/;
4. Add an API controller
% ./script/myapp_create.pl controller API
5. Add a XMLRPC redispatch method and an add method with Remote attribute to
lib/MyApp/Controller/API.pm
sub default : Private {

Views

39

my ( $self, $c ) = @_;
$c->xmlrpc;
}
sub add : Remote {
my ( $self, $c, $a, $b ) = @_;
return $a + $b;
}
The default action is the entry point for each XMLRPC request. It will redispatch every
request to methods with Remote attribute in the same class.
The add method is not a traditional action; it has no private or public path. Only the
XMLRPC dispatcher knows it exists.
6. Thats it! You have built your first web service. Lets test it with XMLRPCsh.pl
(part of SOAP::Lite):
% ./script/myapp_server.pl
...
% XMLRPCsh.pl http://127.0.0.1:3000/api
Usage: method[(parameters)]
> add( 1, 2 )
--- XMLRPC RESULT --3

Tip
Your return data type is usually auto-detected, but you can easily enforce a specific one.
sub add : Remote {
my ( $self, $c, $a, $b ) = @_;
return RPC::XML::int->new( $a + $b );
}

Views
Views pertain to the display of your application. As with models, catalyst is uncommonly
flexible. The recipes below are just a start.

40

Catalyst::Manual::Cookbook

Catalyst::View::TT
One of the first things you probably want to do when starting a new Catalyst application
is set up your View. Catalyst doesnt care how you display your data; you can choose to
generate HTML, PDF files, or plain text if you wanted.
Most Catalyst applications use a template system to generate their HTML, and though
there are several template systems available, Template Toolkit is probably the most popular.
Once again, the Catalyst developers have done all the hard work, and made things
easy for the rest of us. Catalyst::View::TT provides the interface to Template Toolkit, and
provides Helpers which let us set it up that much more easily.

Creating your View


Catalyst::View::TT provides two different helpers for us to use: TT and TTSite.

TT
Create a basic Template Toolkit View using the provided helper script:
script/myapp_create.pl view TT TT
This will create lib/MyApp/View/MyView.pm, which is going to be pretty empty to
start. However, it sets everything up that you need to get started. You can now define
which template you want and forward to your view. For instance:
sub hello : Local {
my ( $self, $c ) = @_;
$c->stash->{template} = hello.tt;
$c->forward( $c->view(TT) );
}
In practice you wouldnt do the forwarding manually, but would use Catalyst::Action::RenderView.

TTSite
Although the TT helper does create a functional, working view, you may find yourself
having to create the same template files and changing the same options every time you
create a new application. The TTSite helper saves us even more time by creating the basic
templates and setting some common options for us.
Once again, you can use the helper script:
script/myapp_create.pl view TT TTSite
This time, the helper sets several options for us in the generated View.

Views

41

__PACKAGE__->config({
CATALYST_VAR => Catalyst,
INCLUDE_PATH => [
MyApp->path_to( root, src ),
MyApp->path_to( root, lib )
],
PRE_PROCESS => config/main,
WRAPPER
=> site/wrapper,
ERROR
=> error.tt2,
TIMER
=> 0
});
INCLUDE PATH defines the directories that Template Toolkit should search for the
template files.
PRE PROCESS is used to process configuration options which are common to every
template file.
WRAPPER is a file which is processed with each template, usually used to easily
provide a common header and footer for every page.

In addition to setting these options, the TTSite helper also created the template and
config files for us! In the root directory, youll notice two new directories: src and lib.
Several configuration files in root/lib/config are called by PRE PROCESS.
The files in root/lib/site are the site-wide templates, called by WRAPPER, and display
the html framework, control the layout, and provide the templates for the header and footer
of your page. Using the template organization provided makes it much easier to standardize
pages and make changes when they are (inevitably) needed.
The template files that you will create for your application will go into root/src, and
you dont need to worry about putting the the <html> or <head> sections; just put in the
content. The WRAPPER will the rest of the page around your template for you.

$c->stash
Of course, having the template system include the header and footer for you isnt all that
we want our templates to do. We need to be able to put data into our templates, and have
it appear where and how we want it, right? Thats where the stash comes in.
In our controllers, we can add data to the stash, and then access it from the template.
For instance:
sub hello : Local {
my ( $self, $c ) = @_;
$c->stash->{name} = Adam;

42

Catalyst::Manual::Cookbook

$c->stash->{template} = hello.tt;
$c->forward( $c->view(TT) );
}
Then, in hello.tt:
<strong>Hello, [% name %]!</strong>
When you view this page, it will display Hello, Adam!
All of the information in your stash is available, by its name/key, in your templates.
And your data dont have to be plain, old, boring scalars. You can pass array references
and hash references, too.
In your controller:
sub hello : Local {
my ( $self, $c ) = @_;
$c->stash->{names} = [ Adam, Dave, John ];
$c->stash->{template} = hello.tt;
$c->forward( $c->view(TT) );
}
In hello.tt:
[% FOREACH name IN names %]
<strong>Hello, [% name %]!</strong><br />
[% END %]
This allowed us to loop through each item in the arrayref, and display a line for each
name that we have.
This is the most basic usage, but Template Toolkit is quite powerful, and allows you to
truly keep your presentation logic separate from the rest of your application.

$c->uri for()
One of my favorite things about Catalyst is the ability to move an application around
without having to worry that everything is going to break. One of the areas that used
to be a problem was with the http links in your template files. For example, suppose
you have an application installed at http://www.domain.com/Calendar. The links point
to /Calendar, /Calendar/2005, /Calendar/2005/10, etc. If you move the application
to be at http://www.mydomain.com/Tools/Calendar, then all of those links will suddenly
break.
Thats where $c->uri for() comes in. This function will merge its parameters with either
the base location for the app, or its current namespace. Lets take a look at a couple of

Views

43

examples.
In your template, you can use the following:
<a href="[% c.uri_for(/login) %]">Login Here</a>
Although the parameter starts with a forward slash, this is relative to the application root, not the webserver root. This is important to remember. So, if your
application is installed at http://www.domain.com/Calendar, then the link would be
http://www.mydomain.com/Calendar/Login. If you move your application to a different
domain or path, then that link will still be correct.
Likewise,
<a href="[% c.uri_for(2005,10, 24) %]">October, 24 2005</a>
The first parameter does NOT have a forward slash, and so it will be relative to the
current namespace. If the application is installed at http://www.domain.com/Calendar.
and if the template is called from MyApp::Controller::Display, then the link would become
http://www.domain.com/Calendar/Display/2005/10/24.
Once again, this allows you to move your application around without having to worry
about broken links. But theres something else, as well. Since the links are generated
by uri for, you can use the same template file by several different controllers, and each
controller will get the links that its supposed to. Since we believe in Dont Repeat Yourself,
this is particularly helpful if you have common elements in your site that you want to keep
in one file.
Further Reading:
http://search.cpan.org/perldoc?Catalyst9
http://search.cpan.org/perldoc?Catalyst%3A%3AView%3A%3ATT10
http://search.cpan.org/perldoc?Template11

Adding RSS feeds


Adding RSS feeds to your Catalyst applications is simple. Well see two different aproaches
here, but the basic premise is that you forward to the normal view action first to get the
objects, then handle the output differently.

Using TT templates
This is the aproach used in Agave (http://dev.rawmode.org/12 ).
sub rss : Local {
my ($self,$c) = @_;
$c->forward(view);
$c->stash->{template}=rss.tt;
9

http://search.cpan.org/perldoc?Catalyst
http://search.cpan.org/perldoc?Catalyst%3A%3AView%3A%3ATT
11
http://search.cpan.org/perldoc?Template
12
http://dev.rawmode.org/
10

44

Catalyst::Manual::Cookbook

}
Then you need a template. Heres the one from Agave:
<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0" xmlns:dc="http://purl.org/dc/elements/1.1/">
<channel>
<title>[ [% blog.name || c.config.name || "Agave" %] ] RSS Feed</title>
<link>[% base %]</link>
<description>Recent posts</description>
<language>en-us</language>
<ttl>40</ttl>
[% WHILE (post = posts.next) %]
<item>
<title>[% post.title %]</title>
<description>[% post.formatted_teaser|html%]</description>
<pubDate>[% post.pub_date %]</pubDate>
<guid>[% post.full_uri %]</guid>
<link>[% post.full_uri %]</link>
<dc:creator>[% post.author.screenname %]</dc:creator>
</item>
[% END %]
</channel>
</rss>

Using XML::Feed
A more robust solution is to use XML::Feed, as was done in the Catalyst Advent Calendar.
Assuming we have a view action that populates entries with some DBIx::Class iterator,
the code would look something like this:
sub rss : Local {
my ($self,$c) = @_;
$c->forward(view); # get the entries
my $feed = XML::Feed->new(RSS);
$feed->title( $c->config->{name} . RSS Feed );
$feed->link( $c->req->base ); # link to the site.
$feed->description(Catalyst advent calendar); Some description
# Process the entries
while( my $entry = $c->stash->{entries}->next ) {
my $feed_entry = XML::Feed::Entry->new(RSS);
$feed_entry->title($entry->title);
$feed_entry->link( $c->uri_for($entry->link) );

Views

45

$feed_entry->issued( DateTime->from_epoch(epoch => $entry>created) );


$feed->add_entry($feed_entry);
}
$c->res->body( $feed->as_xml );
}
A little more code in the controller, but with this approach youre pretty sure to get
something that validates.
Note that for both of the above aproaches, youll need to set the content type like this:
$c->res->content_type(application/rss+xml);

Final words
You could generalize the second variant easily by replacing RSS with a variable, so you
can generate Atom feeds with the same code.
Now, go ahead and make RSS feeds for all your stuff. The world *needs* updates on
your goldfish!

Forcing the browser to download content


Sometimes you need your application to send content for download. For example, you can
generate a comma-separated values (CSV) file for your users to download and import into
their spreadsheet program.
Lets say you have an Orders controller which generates a CSV file in the export action
(i.e., http://localhost:3000/orders/export):
sub export : Local Args(0) {
my ( $self, $c ) = @_;
# In a real application, youd generate this from the database
my $csv = "1,5.99\n2,29.99\n3,3.99\n";
$c->res->content_type(text/comma-separated-values);
$c->res->body($csv);
}
Normally the browser uses the last part of the URI to generate a filename for data it
cannot display. In this case your browser would likely ask you to save a file named export.
Luckily you can have the browser download the content with a specific filename by
setting the Content-Disposition header:
my $filename = Important Orders.csv;
$c->res->header(Content-Disposition, qq[attachment; filename=

46

Catalyst::Manual::Cookbook

"$filename"]);
Note the use of quotes around the filename; this ensures that any spaces in the filename
are handled by the browser.
Put this right before calling $c->res->body and your browser will download a file named
Important Orders.csv instead of export.
You can also use this to have the browser download content which it normally displays,
such as JPEG images or even HTML. Just be sure to set the appropriate content type and
disposition.

Controllers
Controllers are the main point of communication between the web server and your application. Here we explore some aspects of how they work.

Extending RenderView (formerly DefaultEnd)


The recommended approach for an end action is to use Catalyst::Action::RenderView
(taking the place of Catalyst::Plugin::DefaultEnd), which does what you usually need.
However there are times when you need to add a bit to it, but dont want to write your
own end action.
You can extend it like this:
To add something to an end action that is called before rendering (this is likely to be
what you want), simply place it in the end method:
sub end : ActionClass(RenderView) {
my ( $self, $c ) = @_;
# do stuff here; the RenderView action is called afterwards
}
To add things to an end action that are called after rendering, you can set it up like
this:
sub render : ActionClass(RenderView) { }
sub end : Private {
my ( $self, $c ) = @_;
$c->forward(render);
# do stuff here
}

Controllers

47

Action Types
Introduction
A Catalyst application is driven by one or more Controller modules. There are a number
of ways that Catalyst can decide which of the methods in your controller modules it should
call. Controller methods are also called actions, because they determine how your catalyst
application should (re-)act to any given URL. When the application is started up, catalyst
looks at all your actions, and decides which URLs they map to.

Type attributes
Each action is a normal method in your controller, except that it has an attribute attached.
These can be one of several types.
Assume our Controller module starts with the following package declaration:
package MyApp::Controller::Buckets;
and we are running our application on localhost, port 3000 (the test server default).
Path
A Path attribute also takes an argument, this can be either a relative or an absolute
path. A relative path will be relative to the controller namespace, an absolute path
will represent an exact matching URL.
sub my_handles : Path(handles) { .. }
becomes
http://localhost:3000/buckets/handles
and
sub my_handles : Path(/handles) { .. }
becomes
http://localhost:3000/handles
Local
When using a Local attribute, no parameters are needed, instead, the name of the
action is matched in the URL. The namespaces created by the name of the controller
package is always part of the URL.
sub my_handles : Local { .. }
becomes

48

Catalyst::Manual::Cookbook
http://localhost:3000/buckets/my_handles

Global
A Global attribute is similar to a Local attribute, except that the namespace of the
controller is ignored, and matching starts at root.
sub my_handles : Global { .. }
becomes
http://localhost:3000/my_handles

Regex
By now you should have figured that a Regex attribute is just what it sounds like.
This one takes a regular expression, and matches starting from root. These differ from
the rest as they can match multiple URLs.
sub my_handles : Regex(^handles) { .. }
matches
http://localhost:3000/handles
and
http://localhost:3000/handles_and_other_parts
etc.
LocalRegex
A LocalRegex is similar to a Regex, except it only matches below the current controller
namespace.
sub my_handles : LocalRegex(^handles) { .. }
matches
http://localhost:3000/buckets/handles
and
http://localhost:3000/buckets/handles_and_other_parts
etc.

Controllers

49

Private
Last but not least, there is the Private attribute, which allows you to create your own
internal actions, which can be forwarded to, but wont be matched as URLs.
sub my_handles : Private { .. }
becomes nothing at all..
Catalyst also predefines some special Private actions, which you can override, these
are:
default
The default action will be called, if no other matching action is found. If you
dont have one of these in your namespace, or any sub part of your namespace,
youll get an error page instead. If you want to find out where it was the user
was trying to go, you can look in the request object using $c->req->path.
sub default : Private { .. }
works for all unknown URLs, in this controller namespace, or every one if put
directly into MyApp.pm.
index
The index action is called when someone tries to visit the exact namespace of
your controller. If index, default and matching Path actions are defined, then
index will be used instead of default and Path.
sub index : Private { .. }
becomes
http://localhost:3000/buckets
begin
The begin action is called at the beginning of every request involving this namespace directly, before other matching actions are called. It can be used to set up
variables/data for this particular part of your app. A single begin action is called,
its always the one most relevant to the current namespace.
sub begin : Private { .. }
is called once when
http://localhost:3000/bucket/(anything)?
is visited.
end
Like begin, this action is always called for the namespace it is in, after every
other action has finished. It is commonly used to forward processing to the View

50

Catalyst::Manual::Cookbook
component. A single end action is called, its always the one most relevant to the
current namespace.

sub end : Private { .. }


is called once after any actions when
http://localhost:3000/bucket/(anything)?
is visited.
auto
Lastly, the auto action is magic in that every auto action in the chain of paths
up to and including the ending namespace, will be called. (In contrast, only one
of the begin/end/default actions will be called, the relevant one).
package MyApp.pm;
sub auto : Private { .. }
and
sub auto : Private { .. }
will both be called when visiting
http://localhost:3000/bucket/(anything)?

A word of warning
Due to possible namespace conflicts with Plugins, it is advised to only put the pre-defined
Private actions in your main MyApp.pm file, all others should go in a Controller module.

More Information
http://search.cpan.org/author/SRI/Catalyst-5.61/lib/Catalyst/Manual/Intro.pod13
http://dev.catalyst.perl.org/wiki/FlowChart14

Component-based Subrequests
See Catalyst::Plugin::SubRequest.
13
14

http://search.cpan.org/author/SRI/Catalyst-5.61/lib/Catalyst/Manual/Intro.pod
http://dev.catalyst.perl.org/wiki/FlowChart

Controllers

51

File uploads
Single file upload with Catalyst
To implement uploads in Catalyst, you need to have a HTML form similar to this:
<form action="/upload" method="post" enctype="multipart/form-data">
<input type="hidden" name="form_submit" value="yes">
<input type="file" name="my_file">
<input type="submit" value="Send">
</form>
Its very important not to forget enctype="multipart/form-data" in the form.
Catalyst Controller module upload action:
sub upload : Global {
my ($self, $c) = @_;
if ( $c->request->parameters->{form_submit} eq yes ) {
if ( my $upload = $c->request->upload(my_file) ) {
my $filename = $upload->filename;
my $target
= "/tmp/upload/$filename";
unless ( $upload->link_to($target) || $upload->copy_to($target) ) {
die( "Failed to copy $filename to $target: $!" );
}
}
}
$c->stash->{template} = file_upload.html;
}

Multiple file upload with Catalyst


Code for uploading multiple files from one form needs a few changes:
The form should have this basic structure:
<form action="/upload" method="post" enctype="multipart/form-data">
<input type="hidden" name="form_submit" value="yes">
<input type="file" name="file1" size="50"><br>
<input type="file" name="file2" size="50"><br>
<input type="file" name="file3" size="50"><br>
<input type="submit" value="Send">
</form>

52

Catalyst::Manual::Cookbook

And in the controller:


sub upload : Local {
my ($self, $c) = @_;
if ( $c->request->parameters->{form_submit} eq yes ) {
for my $field ( $c->req->upload ) {
my $upload
= $c->req->upload($field);
my $filename = $upload->filename;
my $target
= "/tmp/upload/$filename";
unless ( $upload->link_to($target) || $upload->copy_to($target) ) {
die( "Failed to copy $filename to $target: $!" );
}
}
}
$c->stash->{template} = file_upload.html;
}
for my $field ($c-&gt;req-upload)> loops automatically over all file input fields
and gets input names. After that is basic file saving code, just like in single file upload.
Notice: dieing might not be what you want to do, when an error occurs, but it works
as an example. A better idea would be to store error $! in $c->stash->{error} and show
a custom error template displaying this message.
For more information about uploads and usable methods look at Catalyst::Request::Upload and Catalyst::Request.

Forwarding with arguments


Sometimes you want to pass along arguments when forwarding to another action. As of
version 5.30, arguments can be passed in the call to forward; in earlier versions, you can
manually set the arguments in the Catalyst Request object:
# version 5.30 and later:
$c->forward(/wherever, [qw/arg1 arg2 arg3/]);
# pre-5.30
$c->req->args([qw/arg1 arg2 arg3/]);
$c->forward(/wherever);
(See the Catalyst::Manual::Intro Flow Control section for more information on passing arguments via forward.)

Deployment

53

Deployment
The recipes below describe aspects of the deployment process, including web server engines
and tips to improve application efficiency.

mod perl Deployment


mod perl is the best solution for many applications, but well list some pros and cons so
you can decide for yourself. The other production deployment option is FastCGI, for which
see below.

Pros
Speed
mod perl is very fast and your app will benefit from being loaded in memory within each
Apache process.

Shared memory for multiple apps


If you need to run several Catalyst apps on the same server, mod perl will share the memory
for common modules.

Cons
Memory usage
Since your application is fully loaded in memory, every Apache process will be rather large.
This means a large Apache process will be tied up while serving static files, large files, or
dealing with slow clients. For this reason, it is best to run a two-tiered web architecture
with a lightweight frontend server passing dynamic requests to a large backend mod perl
server.

Reloading
Any changes made to the core code of your app require a full Apache restart. Catalyst does
not support Apache::Reload or StatINC. This is another good reason to run a frontend web
server where you can set up an ErrorDocument 502 page to report that your app is down
for maintenance.

Cannot run multiple versions of the same app


It is not possible to run two different versions of the same application in the same Apache
instance because the namespaces will collide.

54

Catalyst::Manual::Cookbook

Setup
Now that we have that out of the way, lets talk about setting up mod perl to run a Catalyst
app.

1. Install Catalyst::Engine::Apache
You should install the latest versions of both Catalyst and Catalyst::Engine::Apache. The
Apache engines were separated from the Catalyst core in version 5.50 to allow for updates
to the engine without requiring a new Catalyst release.

2. Install Apache with mod perl


Both Apache 1.3 and Apache 2 are supported, although Apache 2 is highly recommended.
With Apache 2, make sure you are using the prefork MPM and not the worker MPM.
The reason for this is that many Perl modules are not thread-safe and may have problems
running within the threaded worker environment. Catalyst is thread-safe however, so if you
know what youre doing, you may be able to run using worker.
In Debian, the following commands should get you going.
apt-get install apache2-mpm-prefork
apt-get install libapache2-mod-perl2

3. Configure your application


Every Catalyst application will automagically become a mod perl handler when run within
mod perl. This makes the configuration extremely easy. Here is a basic Apache 2 configuration.
PerlSwitches -I/var/www/MyApp/lib
PerlModule MyApp
<Location />
SetHandler
modperl
PerlResponseHandler MyApp
</Location>
The most important line here is PerlModule MyApp. This causes mod perl to preload
your entire application into shared memory, including all of your controller, model, and
view classes and configuration. If you have -Debug mode enabled, you will see the startup
output scroll by when you first start Apache.
For an example Apache 1.3 configuration, please see the documentation for Catalyst::Engine::Apache::MP13.

Deployment

55

Test It
Thats it, your app is now a full-fledged mod perl application! Try it out by going to
http://your.server.com/.

Other Options
Non-root location
You may not always want to run your app at the root of your server or virtual host. In this
case, its a simple change to run at any non-root location of your choice.
<Location /myapp>
SetHandler
modperl
PerlResponseHandler MyApp
</Location>
When running this way, it is best to make use of the uri_for method in Catalyst for
constructing correct links.

Static file handling


Static files can be served directly by Apache for a performance boost.
DocumentRoot /var/www/MyApp/root
<Location /static>
SetHandler default-handler
</Location>
This will let all files within root/static be handled directly by Apache. In a two-tiered
setup, the frontend server should handle static files. The configuration to do this on the
frontend will vary.

Catalyst on shared hosting


So, you want to put your Catalyst app out there for the whole world to see, but you dont
want to break the bank. There is an answer - if you can get shared hosting with FastCGI
and a shell, you can install your Catalyst app in a local directory on your shared host. First,
run
perl -MCPAN -e shell
and go through the standard CPAN configuration process. Then exit out without installing anything. Next, open your .bashrc and add
export PATH=$HOME/local/bin:$HOME/local/script:$PATH
perlversion=perl -v | grep built for | awk {print $4} | sed -e s/v//
;
export PERL5LIB=$HOME/local/share/perl/$perlversion:$HOME/

56

Catalyst::Manual::Cookbook

local/lib/perl/$perlversion:$HOME/local/lib:$PERL5LIB
and log out, then back in again (or run ". .bashrc" if you prefer). Finally, edit
.cpan/CPAN/MyConfig.pm and add
make_install_arg => qq[SITEPREFIX=$ENV{HOME}/local],
makepl_arg => qq[INSTALLDIRS=site install_base=$ENV{HOME}/local],
Now you can install the modules you need using CPAN as normal; they will be installed
into your local directory, and perl will pick them up. Finally, change directory into the root
of your virtual host and symlink your applications script directory in:
cd path/to/mydomain.com
ln -s ~/lib/MyApp/script script
And add the following lines to your .htaccess file (assuming the server is setup to handle
.pl as fcgi - you may need to rename the script to myapp fastcgi.fcgi and/or use a SetHandler
directive):
RewriteEngine On
RewriteCond %{REQUEST_URI} !^/?script/myapp_fastcgi.pl
RewriteRule ^(.*)$ script/myapp_fastcgi.pl/$1 [PT,L]
Now http://mydomain.com/ should now Just Work. Congratulations, now you can tell
your friends about your new website (or in our case, tell the client its time to pay the
invoice :) )

FastCGI Deployment
FastCGI is a high-performance extension to CGI. It is suitable for production environments.

Pros
Speed
FastCGI performs equally as well as mod perl. Dont let the CGI fool you; your app runs
as multiple persistent processes ready to receive connections from the web server.

App Server
When using external FastCGI servers, your application runs as a standalone application
server. It may be restarted independently from the web server. This allows for a more
robust environment and faster reload times when pushing new app changes. The frontend
server can even be configured to display a friendly down for maintenance page while the
application is restarting.

Deployment

57

Load-balancing
You can launch your application on multiple backend servers and allow the frontend web
server to load-balance between all of them. And of course, if one goes down, your app
continues to run fine.

Multiple versions of the same app


Each FastCGI application is a separate process, so you can run different versions of the
same app on a single server.

Can run with threaded Apache


Since your app is not running inside of Apache, the faster mpm worker module can be used
without worrying about the thread safety of your application.

Cons
More complex environment
With FastCGI, there are more things to monitor and more processes running than when
using mod perl.

Setup
1. Install Apache with mod fastcgi
mod fastcgi for Apache is a third party module, and can be found at
http://www.fastcgi.com/15 . It is also packaged in many distributions, for example,
libapache2-mod-fastcgi in Debian.

2. Configure your application


# Serve static content directly
DocumentRoot /var/www/MyApp/root
Alias /static /var/www/MyApp/root/static
FastCgiServer /var/www/MyApp/script/myapp_fastcgi.pl -processes 3
Alias /myapp/ /var/www/MyApp/script/myapp_fastcgi.pl/
# Or, run at the root
Alias / /var/www/MyApp/script/myapp_fastcgi.pl/
The above commands will launch 3 app processes and make the app available at /myapp/
15

http://www.fastcgi.com/

58

Catalyst::Manual::Cookbook

Standalone server mode


While not as easy as the previous method, running your app as an external server gives you
much more flexibility.
First, launch your app as a standalone server listening on a socket.
script/myapp_fastcgi.pl -l /tmp/myapp.socket -n 5 -p /tmp/myapp.pid -d
You can also listen on a TCP port if your web server is not on the same machine.
script/myapp_fastcgi.pl -l :8080 -n 5 -p /tmp/myapp.pid -d
You will probably want to write an init script to handle starting/stopping of the app
using the pid file.
Now, we simply configure Apache to connect to the running server.
# 502 is a Bad Gateway error, and will occur if the backend server is down
# This allows us to display a friendly static page that says "down for
# maintenance"
Alias /_errors /var/www/MyApp/root/error-pages
ErrorDocument 502 /_errors/502.html
FastCgiExternalServer /tmp/myapp -socket /tmp/myapp.socket
Alias /myapp/ /tmp/myapp/
# Or, run at the root
Alias / /tmp/myapp/

More Info
Catalyst::Engine::FastCGI.

Development server deployment


The development server is a mini web server written in perl. If you expect a low number of
hits or you dont need mod perl/FastCGI speed, you could use the development server as the
application server with a lightweight proxy web server at the front. However, be aware that
there are known issues, especially with Internet Explorer. Many of these issues can be dealt
with by running the server with the -k (keepalive) option but be aware for more complex
applications this may not be suitable. Consider using Catalyst::Engine::HTTP::POE. This
recipe is easily adapted for POE as well.

Pros
As this is an application server setup, the pros are the same as FastCGI (with the exception
of speed). It is also:

Deployment

59

Simple
The development server is what you create your code on, so if it works here, it should work
in production!

Cons
Speed
Not as fast as mod perl or FastCGI. Needs to fork for each request that comes in - make
sure static files are served by the web server to save forking.

Setup
Start up the development server
script/myapp_server.pl -p 8080 -k

-f -pidfile=/tmp/myapp.pid -daemon

You will probably want to write an init script to handle stop/starting the app using the
pid file.

Configuring Apache
Make sure mod proxy is enabled and add:
# Serve static content directly
DocumentRoot /var/www/MyApp/root
Alias /static /var/www/MyApp/root/static
ProxyRequests Off
<Proxy *>
Order deny,allow
Allow from all
</Proxy>
ProxyPass / http://localhost:8080/
ProxyPassReverse / http://localhost:8080/
You can wrap the above within a VirtualHost container if you want different apps served
on the same host.

Quick deployment: Building PAR Packages


You have an application running on your development box, but then you have to quickly
move it to another one for demonstration/deployment/testing...
PAR packages can save you from a lot of trouble here. They are usual Zip files that
contain a blib tree; you can even include all prereqs and a perl interpreter by setting a few
flags!

60

Catalyst::Manual::Cookbook

Follow these few points to try it out!


1. Install Catalyst and PAR 0.89 (or later)
% perl -MCPAN -e install Catalyst
...
% perl -MCPAN -e install PAR
...
2. Create a application
% catalyst.pl MyApp
...
% cd MyApp
Recent versions of Catalyst (5.62 and up) include Module::Install::Catalyst, which
simplifies the process greatly. From the shell in your application directory:
% perl Makefile.PL
% make catalyst_par
Congratulations! Your package myapp.par is ready, the following steps are just optional.
3. Test your PAR package with parl (no typo)
% parl myapp.par
Usage:
[parl] myapp[.par] [script] [arguments]
Examples:
parl myapp.par myapp_server.pl -r
myapp myapp_cgi.pl
Available scripts:
myapp_cgi.pl
myapp_create.pl
myapp_fastcgi.pl
myapp_server.pl
myapp_test.pl
% parl myapp.par myapp_server.pl
You can connect to your server at http://localhost:3000
Yes, this nifty little starter application gets automatically included. You can also use
catalyst par script(myapp server.pl) to set a default script to execute.
6. Want to create a binary that includes the Perl interpreter?
% pp -o myapp myapp.par
% ./myapp myapp_server.pl

Deployment

61

You can connect to your server at http://localhost:3000

Serving static content


Serving static content in Catalyst used to be somewhat tricky; the use of Catalyst::Plugin::Static::Simple makes everything much easier. This plugin will automatically serve your static content during development, but allows you to easily switch to
Apache (or other server) in a production environment.

Introduction to Static::Simple
Static::Simple is a plugin that will help to serve static content for your application. By
default, it will serve most types of files, excluding some standard Template Toolkit extensions, out of your root file directory. All files are served by path, so if images/me.jpg is
requested, then root/images/me.jpg is found and served.

Usage
Using the plugin is as simple as setting your use line in MyApp.pm to include:
use Catalyst qw/Static::Simple/;
and already files will be served.

Configuring
Static content is best served from a single directory within your root directory. Having many
different directories such as root/css and root/images requires more code to manage,
because you must separately identify each static directory--if you decide to add a root/js
directory, youll need to change your code to account for it. In contrast, keeping all static
directories as subdirectories of a main root/static directory makes things much easier to
manage. Heres an example of a typical root directory structure:
root/
root/content.tt
root/controller/stuff.tt
root/header.tt
root/static/
root/static/css/main.css
root/static/images/logo.jpg
root/static/js/code.js

All static content lives under root/static, with everything else being Template Toolkit
files.

62

Catalyst::Manual::Cookbook

Include Path
You may of course want to change the default locations, and make Static::Simple look
somewhere else, this is as easy as:
MyApp->config->{static}->{include_path} = [
MyApp->config->{root},
/path/to/my/files
];
When you override include path, it will not automatically append the normal root
path, so you need to add it yourself if you still want it. These will be searched in
order given, and the first matching file served.
Static directories
If you want to force some directories to be only static, you can set them using paths
relative to the root dir, or regular expressions:
MyApp->config->{static}->{dirs} = [
static,
qr/^(images|css)/,
];

File extensions
By default, the following extensions are not served (that is, they will be processed by
Catalyst): tmpl, tt, tt2, html, xhtml. This list can be replaced easily:
MyApp->config->{static}->{ignore_extensions} = [
qw/tmpl tt tt2 html xhtml/
];

Ignoring directories
Entire directories can be ignored. If used with include path, directories relative to the
include path dirs will also be ignored:
MyApp->config->{static}->{ignore_dirs} = [ qw/tmpl css/ ];

More information
http://search.cpan.org/dist/Catalyst-Plugin-Static-Simple/16
16

http://search.cpan.org/dist/Catalyst-Plugin-Static-Simple/

Deployment

Serving manually
(myapp server.pl)

63

with

the

Static

plugin

with

HTTP::Daemon

In some situations you might want to control things more directly, using Catalyst::Plugin::Static.
In your main application class (MyApp.pm), load the plugin:
use Catalyst qw/-Debug FormValidator Static OtherPlugin/;
You will also need to make sure your end method does not forward static content to the
view, perhaps like this:
sub end : Private {
my ( $self, $c ) = @_;
$c->forward( MyApp::View::TT )
unless ( $c->res->body || !$c->stash->{template} );
}
This code will only forward to the view if a template has been previously defined by a
controller and if there is not already data in $c-&gt;res-&gt;body.
Next, create a controller to handle requests for the /static path. Use the Helper to save
time. This command will create a stub controller as lib/MyApp/Controller/Static.pm.
$ script/myapp_create.pl controller Static
Edit the file and add the following methods:
# serve all files under /static as static files
sub default : Path(/static) {
my ( $self, $c ) = @_;
# Optional, allow the browser to cache the content
$c->res->headers->header( Cache-Control => max-age=86400 );
$c->serve_static; # from Catalyst::Plugin::Static
}
# also handle requests for /favicon.ico
sub favicon : Path(/favicon.ico) {
my ( $self, $c ) = @_;
$c->serve_static;
}
You can also define a different icon for the browser to use instead of favicon.ico by using
this in your HTML header:
<link rel="icon" href="/static/myapp.ico" type="image/x-icon" />

64

Catalyst::Manual::Cookbook

Common problems with the Static plugin


The Static plugin makes use of the shared-mime-info package to automatically determine
MIME types. This package is notoriously difficult to install, especially on win32 and OS X.
For OS X the easiest path might be to install Fink, then use apt-get install sharedmime-info. Restart the server, and everything should be fine.
Make sure you are using the latest version (>= 0.16) for best results. If you are having
errors serving CSS files, or if they get served as text/plain instead of text/css, you may have
an outdated shared-mime-info version. You may also wish to simply use the following code
in your Static controller:
if ($c->req->path =~ /css$/i) {
$c->serve_static( "text/css" );
} else {
$c->serve_static;
}

Serving Static Files with Apache


When using Apache, you can bypass Catalyst and any Static plugins/controllers controller
by intercepting requests for the root/static path at the server level. All that is required is
to define a DocumentRoot and add a separate Location block for your static content. Here
is a complete config for this application under mod perl 1.x:
<Perl>
use lib qw(/var/www/MyApp/lib);
</Perl>
PerlModule MyApp
<VirtualHost *>
ServerName myapp.example.com
DocumentRoot /var/www/MyApp/root
<Location />
SetHandler perl-script
PerlHandler MyApp
</Location>
<LocationMatch "/(static|favicon.ico)">
SetHandler default-handler
</LocationMatch>
</VirtualHost>
And heres a simpler example thatll get you started:

Deployment

65

Alias /static/ "/my/static/files/"


<Location "/static">
SetHandler none
</Location>

Caching
Catalyst makes it easy to employ several different types of caching to speed up your applications.

Cache Plugins
There are three wrapper plugins around common CPAN cache modules: Cache::FastMmap,
Cache::FileCache, and Cache::Memcached. These can be used to cache the result of slow
operations.
This very page youre viewing makes use of the FileCache plugin to cache the rendered
XHTML version of the source POD document. This is an ideal application for a cache
because the source document changes infrequently but may be viewed many times.
use Catalyst qw/Cache::FileCache/;
...
use File::stat;
sub render_pod : Local {
my ( self, $c ) = @_;
# the cache is keyed on the filename and the modification time
# to check for updates to the file.
my $file = $c->path_to( root, 2005, 11.pod );
my $mtime = ( stat $file )->mtime;
my $cached_pod = $c->cache->get("$file $mtime");
if ( !$cached_pod ) {
$cached_pod = do_slow_pod_rendering();
# cache the result for 12 hours
$c->cache->set( "$file $mtime", $cached_pod, 12h );
}
$c->stash->{pod} = $cached_pod;
}
We could actually cache the result forever, but using a value such as 12 hours allows old
entries to be automatically expired when they are no longer needed.

66

Catalyst::Manual::Cookbook

Page Caching
Another method of caching is to cache the entire HTML page. While this is traditionally
handled by a front-end proxy server like Squid, the Catalyst PageCache plugin makes it
trivial to cache the entire output from frequently-used or slow actions.
Many sites have a busy content-filled front page that might look something like this. It
probably takes a while to process, and will do the exact same thing for every single user
who views the page.
sub front_page : Path(/) {
my ( $self, $c ) = @_;
$c->forward( get_news_articles );
$c->forward( build_lots_of_boxes );
$c->forward( more_slow_stuff );
$c->stash->{template} = index.tt;
}
We can add the PageCache plugin to speed things up.
use Catalyst qw/Cache::FileCache PageCache/;
sub front_page : Path (/) {
my ( $self, $c ) = @_;
$c->cache_page( 300 );
# same processing as above
}
Now the entire output of the front page, from <html> to </html>, will be cached for
5 minutes. After 5 minutes, the next request will rebuild the page and it will be re-cached.
Note that the page cache is keyed on the page URI plus all parameters, so requests for /
and /?foo=bar will result in different cache items. Also, only GET requests will be cached
by the plugin.
You can even get that front-end Squid proxy to help out by enabling HTTP headers for
the cached page.
MyApp->config->{page_cache}->{set_http_headers} = 1;
This would now set the following headers so proxies and browsers may cache the content
themselves.
Cache-Control: max-age=($expire_time - time)
Expires: $expire_time
Last-Modified: $cache_created_time

Testing

67

Template Caching
Template Toolkit provides support for caching compiled versions of your templates. To
enable this in Catalyst, use the following configuration. TT will cache compiled templates
keyed on the file mtime, so changes will still be automatically detected.
package MyApp::View::TT;
use strict;
use warnings;
use base Catalyst::View::TT;
__PACKAGE__->config(
COMPILE_DIR => /tmp/template_cache,
);
1;

More Info
See the documentation for each cache plugin for more details and other available configuration options.
Catalyst::Plugin::Cache::FastMmap
Catalyst::Plugin::Cache::FileCache
Catalyst::Plugin::Cache::Memcached
Catalyst::Plugin::PageCache
http://search.cpan.org/dist/Template-Toolkit/lib/Template/Manual/Config.pod#Caching and Compiling

Testing
Testing is an integral part of the web application development process. Tests make multi
developer teams easier to coordinate, and they help ensure that there are no nasty surprises
after upgrades or alterations.

Testing
Catalyst provides a convenient way of testing your application during development and
before deployment in a real environment.
Catalyst::Test makes it possible to run the same tests both locally (without an external daemon) and against a remote server via HTTP.

Tests
Lets examine a skeleton applications t/ directory:
17

http://search.cpan.org/dist/Template-Toolkit/lib/Template/Manual/Config.pod#Caching_and_Compiling_Options

68

Catalyst::Manual::Cookbook

mundus:~/MyApp chansen$ ls -l t/
total 24
-rw-r--r-- 1 chansen chansen
95 18 Dec 20:50 01app.t
-rw-r--r-- 1 chansen chansen 190 18 Dec 20:50 02pod.t
-rw-r--r-- 1 chansen chansen 213 18 Dec 20:50 03podcoverage.t

01app.t
Verifies that the application loads, compiles, and returns a successful response.
02pod.t
Verifies that all POD is free from errors. Only executed if the TEST_POD environment
variable is true.
03podcoverage.t
Verifies that all methods/functions have POD coverage.
TEST_POD environment variable is true.

Only executed if the

Creating tests
mundus:~/MyApp chansen$ cat t/01app.t | perl -ne printf( "%2d
)
1 use Test::More tests => 2;
2 use_ok( Catalyst::Test, MyApp );
3
4 ok( request(/)->is_success );

%s", $., $_

The first line declares how many tests we are going to run, in this case two. The second
line tests and loads our application in test mode. The fourth line verifies that our application
returns a successful response.
Catalyst::Test exports two functions, request and get. Each can take three different
arguments:
A string which is a relative or absolute URI.
request(/my/path);
request(http://www.host.com/my/path);

An instance of URI.
request( URI->new(http://www.host.com/my/path) );

Testing

69

An instance of HTTP::Request.
request( HTTP::Request->new( GET => http://www.host.com/my/path) );
request returns an instance of HTTP::Response and get returns the content (body) of
the response.

Running tests locally


mundus:~/MyApp chansen$ CATALYST_DEBUG=0 TEST_POD=1 prove --lib lib/ t/
t/01app............ok
t/02pod............ok
t/03podcoverage....ok
All tests successful.
Files=3, Tests=4, 2 wallclock secs ( 1.60 cusr + 0.36 csys = 1.96 CPU)
CATALYST_DEBUG=0 ensures that debugging is off; if its enabled you will see debug logs
between tests.
TEST_POD=1 enables POD checking and coverage.
prove A command-line tool that makes it easy to run tests. You can find out more
about it from the links below.

Running tests remotely


mundus:~/MyApp chansen$ CATALYST_SERVER=http://localhost:3000/ prove --lib
lib/ t/01app.t
t/01app....ok
All tests successful.
Files=1, Tests=2, 0 wallclock secs ( 0.40 cusr + 0.01 csys = 0.41 CPU)
CATALYST_SERVER=http://localhost:3000/ is the absolute deployment URI of your
application. In CGI or FastCGI it should be the host and path to the script.

Test::WWW::Mechanize and Catalyst


Be sure to check out Test::WWW::Mechanize::Catalyst. It makes it easy to test HTML,
forms and links. A short example of usage:
use Test::More tests => 6;
use_ok( Test::WWW::Mechanize::Catalyst, MyApp );
my $mech = Test::WWW::Mechanize::Catalyst->new;
$mech->get_ok("http://localhost/", Got index page);
$mech->title_like( qr/^MyApp on Catalyst/, Got right index title );
ok( $mech->find_link( text_regex => qr/^Wiki/i ), Found link to Wiki );

70

Catalyst::Manual::Cookbook

ok( $mech->find_link( text_regex => qr/^Mailing-List/i ), Found link to


Mailing-List );
ok( $mech->find_link( text_regex => qr/^IRC channel/i ), Found link to IRC
channel );

Further Reading
Catalyst::Test
http://search.cpan.org/dist/Catalyst/lib/Catalyst/Test.pm18

Test::WWW::Mechanize::Catalyst
http://search.cpan.org/dist/Test-WWW-Mechanize-Catalyst/lib/Test/WWW/Mechanize/Catalyst.p
Test::WWW::Mechanize
http://search.cpan.org/dist/Test-WWW-Mechanize/Mechanize.pm20
WWW::Mechanize
http://search.cpan.org/dist/WWW-Mechanize/lib/WWW/Mechanize.pm21
LWP::UserAgent
http://search.cpan.org/dist/libwww-perl/lib/LWP/UserAgent.pm22
HTML::Form
http://search.cpan.org/dist/libwww-perl/lib/HTML/Form.pm23
HTTP::Message
http://search.cpan.org/dist/libwww-perl/lib/HTTP/Message.pm24
HTTP::Request
http://search.cpan.org/dist/libwww-perl/lib/HTTP/Request.pm25
HTTP::Request::Common
http://search.cpan.org/dist/libwww-perl/lib/HTTP/Request/Common.pm26
HTTP::Response
http://search.cpan.org/dist/libwww-perl/lib/HTTP/Response.pm27
18

http://search.cpan.org/dist/Catalyst/lib/Catalyst/Test.pm
http://search.cpan.org/dist/Test-WWW-Mechanize-Catalyst/lib/Test/WWW/Mechanize/Catalyst.pm
20
http://search.cpan.org/dist/Test-WWW-Mechanize/Mechanize.pm
21
http://search.cpan.org/dist/WWW-Mechanize/lib/WWW/Mechanize.pm
22
http://search.cpan.org/dist/libwww-perl/lib/LWP/UserAgent.pm
23
http://search.cpan.org/dist/libwww-perl/lib/HTML/Form.pm
24
http://search.cpan.org/dist/libwww-perl/lib/HTTP/Message.pm
25
http://search.cpan.org/dist/libwww-perl/lib/HTTP/Request.pm
26
http://search.cpan.org/dist/libwww-perl/lib/HTTP/Request/Common.pm
27
http://search.cpan.org/dist/libwww-perl/lib/HTTP/Response.pm
19

AUTHORS
HTTP::Status
http://search.cpan.org/dist/libwww-perl/lib/HTTP/Status.pm28
URI
http://search.cpan.org/dist/URI/URI.pm29
Test::More
http://search.cpan.org/dist/Test-Simple/lib/Test/More.pm30
Test::Pod
http://search.cpan.org/dist/Test-Pod/Pod.pm31
Test::Pod::Coverage
http://search.cpan.org/dist/Test-Pod-Coverage/Coverage.pm32
prove (Test::Harness)
http://search.cpan.org/dist/Test-Harness/bin/prove33

More Information
http://search.cpan.org/perldoc?Catalyst::Plugin::Authorization::Roles34
http://search.cpan.org/perldoc?Catalyst::Plugin::Authorization::ACL35

AUTHORS
Sebastian Riedel sri@oook.de
Danijel Milicevic me@danijel.de
Viljo Marrandi vilts@yahoo.com
Marcus Ramberg mramberg@cpan.org
Jesse Sheidlower jester@panix.com
Andy Grundman andy@hybridized.org
Chisel Wright pause@herlpacker.co.uk
Will Hawes info@whawes.co.uk
Gavin Henry ghenry@perl.me.uk
Kieren Diment kd@totaldatasolution.com
28

http://search.cpan.org/dist/libwww-perl/lib/HTTP/Status.pm
http://search.cpan.org/dist/URI/URI.pm
30
http://search.cpan.org/dist/Test-Simple/lib/Test/More.pm
31
http://search.cpan.org/dist/Test-Pod/Pod.pm
32
http://search.cpan.org/dist/Test-Pod-Coverage/Coverage.pm
33
http://search.cpan.org/dist/Test-Harness/bin/prove
34
http://search.cpan.org/perldoc?Catalyst::Plugin::Authorization::Roles
35
http://search.cpan.org/perldoc?Catalyst::Plugin::Authorization::ACL
29

71

72

Catalyst::Manual::Cookbook

COPYRIGHT
This document is free, you can redistribute it and/or modify it under the same terms as
Perl itself.

Catalyst::Manual::DevelopmentProcess
- Administrative structure of the
Catalyst Development Process
Aims of the Catalyst Core Team
The main current goals of the Catalyst core development team continue to be stability,
performance, and a more paced addition of features, with a focus on extensibility. Extensive
improvements to the documentation are also expected in the short term.
The Catalyst Roadmap at http://dev.catalyst.perl.org/roadmap36 will remain as is, and
continues to reflect the specific priorities and schedule for future releases.

Charter for the Catalyst Core Team


Intention
The intention of the Catalyst Core Team is to maintain and support the Catalyst framework, in order for it to be a viable and stable framework for developing web-based MVC
applications. This includes both technical decisions about the Catalyst core distribution,
and public relations relating to the Catalyst framework as a whole.
The main priority for development is stability for the users of the framework, while
improving usability and extensibility, as well as improving documentation and ease of deployment.

Membership
The Catalyst Core Team consists of the developers that have full commit privileges to the
entire Catalyst source tree.
In addition, the core team may accept members that have non-technical roles such as
marketing, legal, or economic responsibilities.
At the time of conception, the Core Team consists of the following people:
36

http://dev.catalyst.perl.org/roadmap

73

74

Catalyst::Manual::DevelopmentProcess

Andy Grundman

Christian Hansen

Brian Cassidy

Marcus Ramberg

Jesse Sheidlower

Matt S. Trout

Yuval Kogman

New members of the Core Team must be accepted by a 2/3 majority by the current
members.

Technical Decisions.
Any change to the Catalyst core which can not be conceived as a correction of an error in
the current feature set will need to be accepted by at least 3 members of the Core Team
before it can be commited to the trunk (which is the basis for CPAN releases). Anyone
with access is at any time free to make a branch to develop a proof of concept for a feature
to be committed to trunk.

Organizational and Philosophical Decisions.


Any such decision should be decided by majority vote. Thus it should be a goal of the
organization that its membership number should at any time be an odd number, to render
it effective with regards to decision making. The exceptions to this rule are changes to this
charter and additions to the membership of the Core Team, which require a 2/3 majority.

CPAN Releases
Planned releases to CPAN should be performed by the release manager, at the time of
writing Marcus Ramberg, or the deputy release manager, at the time of writing Andy
Grundman. In the case of critical error correction, any member of the Core Team can
perform a rescue release.

Charter for the Catalyst Core Team

75

Public statements from the Core Team


The Core Team should strive to appear publicly as a group when answering questions or
other correspondence. In cases where this is not possible, the same order as for CPAN
Releases applies.

76

Catalyst::Manual::DevelopmentProcess

Catalyst::Manual::Internals Catalyst Internals


This document provides an overview of the internals of Catalyst. As Catalyst is still developing rapidly, details may become out of date: please treat this as a guide, and look at the
source for the last word.
The coverage is split into initialization and request lifecycle.

Initialization
Catalyst initializes itself in two stages (I may be wrong in some of the details here - AF):
1. When the Catalyst module is imported in the main application module it evaluates
any options (-Debug, -Engine=XXX) and loads any specified plugins, making the application module inherit from the plugin classes. It also sets up a default log object
and ensures that the application module inherits from Catalyst and from the selected
specialized Engine module.
2. When the application module makes the first call to __PACKAGE__->action() (implemented in Catalyst::Engine), Catalyst automatically loads all components it finds
in the $class::Controller, $class::C, $class::Model, $class::M, $class::View
and $class::V namespaces (using Module::Pluggable::Fast). A table of actions is
built up and added to on subsequent calls to action().

Request Lifecycle
For each request Catalyst builds a context object, which includes information about the
request, and then searches the action table for matching actions.
The handling of a request can be divided into three stages: preparation of the context,
processing of the request, and finalization of the response. These are the steps of a Catalyst
request in detail; every step can be overloaded to extend Catalyst.
handle_request
prepare
prepare_request
77

78

Catalyst::Manual::Internals
prepare_connection
prepare_query_parameters
prepare_headers
prepare_cookies
prepare_path
prepare_body (unless parse_on_demand)
prepare_body_parameters
prepare_parameters
prepare_uploads
prepare_action
dispatch
finalize
finalize_uploads
finalize_error (if one happened)
finalize_headers
finalize_cookies
finalize_body

These steps are normally overloaded from engine classes, and may also be extended by
plugins. Extending means using multiple inheritance with NEXT.
The specialized engine classes populate the Catalyst request object with information
from the underlying layer (Apache::Request or CGI::Simple) during the prepare phase,
then push the generated response information down to the underlying layer during the
finalize phase.

AUTHOR
Sebastian Riedel, sri@oook.de

COPYRIGHT
This program is free software, you can redistribute it and/or modify it under the same terms
as Perl itself.

Catalyst::Manual::Intro Introduction to Catalyst


This is a brief introduction to Catalyst. It explains the most important features of how
Catalyst works and shows how to get a simple application up and running quickly. For an
introduction (without code) to Catalyst itself, and why you should be using it, see Catalyst::Manual::About. For a systematic step-by-step introduction to writing an application
with Catalyst, see Catalyst::Manual::Tutorial.

What is Catalyst?
Catalyst is an elegant web application framework, extremely flexible yet extremely simple.
Its similar to Ruby on Rails, Spring (Java), and Maypole, upon which it was originally
based. Its most important design philosphy is to provide easy access to all the tools you
need to develop web applications, with few restrictions on how you need to use these tools.
However, this does mean that it is always possible to do things in a different way. Other
web frameworks are initially simpler to use, but achieve this by locking the programmer
into a single set of tools. Catalysts emphasis on flexibility means that you have to think
more to use it. We view this as a feature. For example, this leads to Catalyst being more
suited to system integration tasks than other web frameworks.

MVC
Catalyst follows the Model-View-Controller (MVC) design pattern, allowing you to easily
separate concerns, like content, presentation, and flow control, into separate modules. This
separation allows you to modify code that handles one concern without affecting code that
handles the others. Catalyst promotes the re-use of existing Perl modules that already
handle common web application concerns well.
Heres how the Model, View, and Controller map to those concerns, with examples of
well-known Perl modules you may want to use for each.
* Model
Access and modify content (data). DBIx::Class, Class::DBI, Xapian, Net::LDAP...
* View
Present content to the user. Template Toolkit, Mason, HTML::Template...
79

80

Catalyst::Manual::Intro

* Controller
Control the whole request phase, check parameters, dispatch actions, flow control.
Catalyst itself!
If youre unfamiliar with MVC and design patterns, you may want to check out the
original book on the subject, Design Patterns, by Gamma, Helm, Johnson, and Vlissides,
also known as the Gang of Four (GoF). Many, many web application frameworks are based
on MVC, which is becoming a popular design paradigm for the world wide web.

Flexibility
Catalyst is much more flexible than many other frameworks. Rest assured you can use your
favorite Perl modules with Catalyst.
* Multiple Models, Views, and Controllers
To build a Catalyst application, you handle each type of concern inside special modules
called Components. Often this code will be very simple, just calling out to Perl
modules like those listed above under MVC. Catalyst handles these components
in a very flexible way. Use as many Models, Views, and Controllers as you like,
using as many different Perl modules as you like, all in the same application. Want to
manipulate multiple databases, and retrieve some data via LDAP? No problem. Want
to present data from the same Model using Template Toolkit and PDF::Template?
Easy.
* Reuseable Components
Not only does Catalyst promote the re-use of already existing Perl modules, it also
allows you to re-use your Catalyst components in multiple Catalyst applications.
* Unrestrained URL-to-Action Dispatching
Catalyst allows you to dispatch any URLs to any application Actions, even through
regular expressions! Unlike most other frameworks, it doesnt require mod rewrite or
class and method names in URLs.
With Catalyst you register your actions and address them directly. For example:
sub hello : Global {
my ( $self, $context ) = @_;
$context->response->body(Hello World!);
}
Now http://localhost:3000/hello prints Hello World!.
* Support for CGI, mod perl, Apache::Request, FastCGI
Use Catalyst::Engine::Apache or Catalyst::Engine::CGI. Other engines are also
available.

Quickstart

81

Simplicity
The best part is that Catalyst implements all this flexibility in a very simple way.
* Building Block Interface
Components interoperate very smoothly. For example, Catalyst automatically makes
a Context object available to every component. Via the context, you can access
the request object, share data between components, and control the flow of your
application. Building a Catalyst application feels a lot like snapping together toy
building blocks, and everything just works.
* Component Auto-Discovery
No need to use all of your components. Catalyst automatically finds and loads them.
* Pre-Built Components for Popular Modules
See Catalyst::Model::DBIC::Schema for DBIx::Class, or Catalyst::View::TT for
Template Toolkit.
* Built-in Test Framework
Catalyst comes with a built-in, lightweight http server and test framework, making it
easy to test applications from the web browser, and the command line.
* Helper Scripts
Catalyst provides helper scripts to quickly generate running starter code for components and unit tests. Install Catalyst::Devel and see Catalyst::Helper.

Quickstart
Heres how to install Catalyst and get a simple application up and running, using the helper
scripts described above.

Install
Installation of Catalyst can be a time-consuming and frustrating effort, due to its large
number of dependencies. The easiest way to get up and running is to use Matt Trouts catinstall script, from http://www.shadowcatsystems.co.uk/static/cat-install37 , and then install Catalyst::Devel.
# perl cat-install
# perl -MCPAN -e install Catalyst::Devel
37

http://www.shadowcatsystems.co.uk/static/cat-install

82

Catalyst::Manual::Intro

Setup
$
#
$
$

catalyst.pl MyApp
output omitted
cd MyApp
script/myapp_create.pl controller Library::Login

Run
$ script/myapp_server.pl
Now visit these locations with your favorite browser or user agent to see Catalyst in
action:
(NOTE: Although we create a controller here, we dont actually use it. Both of these
URLs should take you to the welcome page.)
http://localhost:3000/
http://localhost:3000/library/login/

How It Works
Lets see how Catalyst works, by taking a closer look at the components and other parts of
a Catalyst application.

Components
Catalyst has an uncommonly flexible component system. You can define as many Models,
Views, and Controllers as you like. As discussed previously, the general idea is that the
View is responsible for the output of data to the user (typically via a web browser, but a
View can also generate PDFs or e-mails, for example); the Model is responsible for providing
data (typically from a relational database); and the Controller is responsible for interacting
with the user and deciding how user input determines what actions the application takes.
In the world of MVC, there are frequent discussions and disagreements about the nature
of each element - whether certain types of logic belong in the Model or the Controller, etc.
Catalysts flexibility means that this decision is entirely up to you, the programmer; Catalyst
doesnt enforce anything. See Catalyst::Manual::About for a general discussion of these
issues.
All components must inherit from Catalyst::Base, which provides a simple class structure and some common class methods like config and new (constructor).
package MyApp::Controller::Catalog;

How It Works

83

use strict;
use base Catalyst::Base;
__PACKAGE__->config( foo => bar );
1;
You dont have to use or otherwise register Models, Views, and Controllers. Catalyst
automatically discovers and instantiates them when you call setup in the main application.
All you need to do is put them in directories named for each Component type. You can use
a short alias for each one.
* MyApp/Model/
* MyApp/M/
* MyApp/View/
* MyApp/V/
* MyApp/Controller/
* MyApp/C/

In older versions of Catalyst, the recommended practice (and the one automatically
created by helper scripts) was to name the directories M/, V/, and C/. Though these still
work, we now recommend the use of the full names.

Views
To show how to define views, well use an already-existing base class for the Template
Toolkit, Catalyst::View::TT. All we need to do is inherit from this class:
package MyApp::View::TT;
use strict;
use base Catalyst::View::TT;
1;
(You can also generate this automatically by using the helper script:

84

Catalyst::Manual::Intro

script/myapp_create.pl view TT TT
where the first TT tells the script that the name of the view should be TT, and the second
that it should be a Template Toolkit view.)
This gives us a process() method and we can now just do $c>forward(MyApp::View::TT) to render our templates. The base class makes process()
implicit, so we dont have to say $c-&gt;forward(qw/MyApp::View::TT process/).
sub hello : Global {
my ( $self, $c ) = @_;
$c->stash->{template} = hello.tt;
}
sub end : Private {
my ( $self, $c ) = @_;
$c->forward( $c->view(TT) );
}
You normally render templates at the end of a request, so its a perfect use for the global
end action.
In practice, however, you would use a default end action as supplied by Catalyst::Action::RenderView.
Also, be sure to put the template under the directory specified in $c-&gt;config&gt;{root}, or youll end up looking at the debug screen.

Models
Models are providers of data. This data could come from anywhere - a search engine index,
a spreadsheet, the file system - but typically a Model represents a database table. The data
source does not intrinsically have much to do with web applications or Catalyst - it could
just as easily be used to write an offline report generator or a command-line tool.
To show how to define models, again well use an already-existing base class,
this time for DBIx::Class: Catalyst::Model::DBIC::Schema.
Well also need
DBIx::Class::Schema::Loader.
But first, we need a database.
-- myapp.sql
CREATE TABLE foo (
id INTEGER PRIMARY KEY,
data TEXT
);
CREATE TABLE bar (
id INTEGER PRIMARY KEY,
foo INTEGER REFERENCES foo,
data TEXT

How It Works

85

);
INSERT INTO foo (data) VALUES (TEST!);
% sqlite /tmp/myapp.db < myapp.sql
Now we can create a DBIC::Schema model for this database.
script/myapp_create.pl model MyModel DBIC::Schema MySchema create=static
dbi:SQLite:/tmp/myapp.db
DBIx::Class::Schema::Loader automatically loads table layouts and relationships,
and converts them into a static schema definition MySchema, which you can edit later.
Use the stash to pass data to your templates.
We add the following to MyApp/Controller/Root.pm
sub view : Global {
my ( $self, $c, $id ) = @_;
$c->stash->{item} = $c->model(MyModel::Foo)->find($id);
}
1;
sub end : Private {
my ( $self, $c ) = @_;
$c->stash->{template} ||= index.tt;
$c->forward( $c->view(TT) );
}
We then create a new template file root/index.tt containing:
The Ids data is [% item.data %]
Models do not have to be part of your Catalyst application; you can always call an
outside module that serves as your Model:
# in a Controller
sub list : Local {
my ( $self, $c ) = @_;
$c->stash->{template} = list.tt;
use Some::Outside::Database::Module;
my @records = Some::Outside::Database::Module->search({
artist => Led Zeppelin,
});

86

Catalyst::Manual::Intro

$c->stash->{records} = \@records;
}
But by using a Model that is part of your Catalyst application, you gain several things:
you dont have to use each component, Catalyst will find and load it automatically at
compile-time; you can forward to the module, which can only be done to Catalyst components. Only Catalyst components can be fetched with $c-&gt;model(SomeModel).
Happily, since many people have existing Model classes that they would like to use with
Catalyst (or, conversely, they want to write Catalyst models that can be used outside of
Catalyst, e.g. in a cron job), its trivial to write a simple component in Catalyst that slurps
in an outside Model:
package MyApp::Model::DB;
use base qw/Catalyst::Model::DBIC::Schema/;
__PACKAGE__->config(
schema_class => Some::DBIC::Schema,
connect_info => [dbi:SQLite:foo.db, , , {AutoCommit=>1}]
);
1;
and thats it! Now Some::DBIC::Schema is part of your Cat app as MyApp::Model::DB.
Within Catalyst, the common approach to writing a model for your application is wrapping a generic model (e.g. DBIx::Class::Schema, a bunch of XMLs, or anything really)
with an object that contains configuration data, convenience methods, and so forth. Thus
you will in effect have two models - a wrapper model that knows something about Catalyst
and your web application, and a generic model that is totally independent of these needs.
Technically, within Catalyst a model is a component - an instance of the models class
belonging to the application. It is important to stress that the lifetime of these objects is
per application, not per request.
While the model base class (Catalyst::Model) provides things like config to better
integrate the model into the application, sometimes this is not enough, and the model
requires access to $c itself.
Situations where this need might arise include:
Interacting with another model
Using per-request data to control behavior
Using plugins from a Model (for example Catalyst::Plugin::Cache).

From a style perspective its usually considered bad form to make your model too
smart about things - it should worry about business logic and leave the integration details
to the controllers. If, however, you find that it does not make sense at all to use an auxillary
controller around the model, and the models need to access $c cannot be sidestepped, there
exists a power tool called ACCEPT CONTEXT.

How It Works

87

Controllers
Multiple controllers are a good way to separate logical domains of your application.
package MyApp::Controller::Login;
use base qw/Catalyst::Controller/;
sub login : Path("login") { }
sub new_password : Path("new-password") { }
sub logout : Path("logout") { }
package MyApp::Controller::Catalog;
use base qw/Catalyst::Controller/;
sub view : Local { }
sub list : Local { }
package MyApp::Controller::Cart;
use base qw/Catalyst::Controller/;
sub add : Local { }
sub update : Local { }
sub order : Local { }
Note that you can also supply attributes via the Controllers config so long as you have
at least one attribute on a subref to be exported (:Action is commonly used for this) - for
example the following is equivalent to the same controller above:
package MyApp::Controller::Login;
use base qw/Catalyst::Controller/;
__PACKAGE__->config(
actions => {
sign_in => { Path => sign-in },
new_password => { Path => new-password },
sign_out => { Path => sign-out },
},
);
sub sign_in : Action { }
sub new_password : Action { }
sub sign_out : Action { }

88

Catalyst::Manual::Intro

ACCEPT CONTEXT
Whenever you call $c->component(Foo) you get back an object - the instance of the
model. If the component supports the ACCEPT_CONTEXT method instead of returning the
model itself, the return value of $model->ACCEPT_CONTEXT( $c ) will be used.
This means that whenever your model/view/controller needs to talk to $c it gets a
chance to do this when its needed.
A typical ACCEPT_CONTEXT method will either clone the model and return one with the
context object set, or it will return a thin wrapper that contains $c and delegates to the
per-application model object.
A typical ACCEPT_CONTEXT method could look like this:
sub ACCEPT_CONTEXT {
my ( $self, $c, @extra_arguments ) = @_;
bless { %$self, c => $c }, ref($self);
}
effectively treating $self as a prototype object that gets a new parameter. @extra_arguments comes from any trailing arguments to $c->component( $bah, @extra_arguments ) (or $c->model(...), $c->view(...) etc).
The life time of this value is per usage, and not per request. To make this per request
you can use the following technique:
Add a field to $c, like my_model_instance. Then write your ACCEPT_CONTEXT method
to look like this:
sub ACCEPT_CONTEXT {
my ( $self, $c ) = @_;
if ( my $per_request = $c->my_model_instance ) {
return $per_request;
} else {
my $new_instance = bless { %$self, c => $c }, ref($self);
Scalar::Util::weaken($new_instance->{c}); # or we have a circular reference
$c->my_model_instance( $new_instance );
return $new_instance;
}
}

Application Class
In addition to the Model, View, and Controller components, theres a single class that
represents your application itself. This is where you configure your application, load plugins,

How It Works

89

and extend Catalyst.


package MyApp;
use strict;
use Catalyst qw/-Debug/; # Add other plugins here, e.g.
# for session support
MyApp->config(
name => My Application,
# You can put anything else you want in here:
my_configuration_variable => something,
);
1;
In older versions of Catalyst, the application class was where you put global actions.
However, as of version 5.66, the recommended practice is to place such actions in a special
Root controller (see Actions, below), to avoid namespace collisions.
* name
The name of your application.
Optionally, you can specify a root parameter for templates and static data. If omitted,
Catalyst will try to auto-detect the directorys location. You can define as many parameters
as you want for plugins or whatever you need. You can access them anywhere in your
application via $context-&gt;config-&gt;{$param_name}.

Context
Catalyst automatically blesses a Context object into your application class and makes it
available everywhere in your application. Use the Context to directly interact with Catalyst
and glue your Components together. For example, if you need to use the Context from
within a Template Toolkit template, its already there:
<h1>Welcome to [% c.config.name %]!</h1>
As illustrated in our URL-to-Action dispatching example, the Context is always the
second method parameter, behind the Component object reference or class name itself.
Previously we called it $context for clarity, but most Catalyst developers just call it $c:
sub hello : Global {
my ( $self, $c ) = @_;
$c->res->body(Hello World!);
}
The Context contains several important objects:

90

Catalyst::Manual::Intro

* Catalyst::Request
$c->request
$c->req # alias
The request object contains all kinds of request-specific information, like query parameters, cookies, uploads, headers, and more.
$c->req->params->{foo};
$c->req->cookies->{sessionid};
$c->req->headers->content_type;
$c->req->base;
$c->req->uri_with( { page = $pager->next_page } );
* Catalyst::Response
$c->response
$c->res # alias
The response is like the request, but contains just response-specific information.
$c->res->body(Hello World);
$c->res->status(404);
$c->res->redirect(http://oook.de);
* Catalyst::Config
$c->config
$c->config->{root};
$c->config->{name};
* Catalyst::Log
$c->log
$c->log->debug(Something happened);
$c->log->info(Something you should know);
* Stash
$c->stash
$c->stash->{foo} = bar;

How It Works

91

$c->stash->{baz} = {baz => qox};


$c->stash->{fred} = [qw/wilma pebbles/];
and so on.
The last of these, the stash, is a universal hash for sharing data among application
components. For an example, we return to our hello action:
sub hello : Global {
my ( $self, $c ) = @_;
$c->stash->{message} = Hello World!;
$c->forward(show_message);
}
sub show_message : Private {
my ( $self, $c ) = @_;
$c->res->body( $c->stash->{message} );
}
Note that the stash should be used only for passing data in an individual request cycle;
it gets cleared at a new request. If you need to maintain persistent data, use a session. See
Catalyst::Plugin::Session for a comprehensive set of Catalyst-friendly session-handling
tools.

Actions
A Catalyst controller is defined by its actions. An action is a subroutine with a special attribute. Youve already seen some examples of actions in this document. The URL (for example http://localhost.3000/foo/bar) consists of two parts, the base (http://localhost:3000/
in this example) and the path (foo/bar). Please note that the trailing slash after the hostname[:port] always belongs to base and not to the action.
* Application Wide Actions
Actions which are called at the root level of the application
http://localhost:3000/ ) go in MyApp::Controller::Root, like this:

(e.g.

package MyApp::Controller::Root;
use base Catalyst::Controller;
# Sets the actions in this controller to be registered with no prefix
# so they function identically to actions created in MyApp.pm
__PACKAGE__->config->{namespace} = ;
sub default : Private {
my ( $self, $context ) = @_;
$context->response->body(Catalyst rocks!);
}

92

Catalyst::Manual::Intro
1;

Action types
Catalyst supports several types of actions:
* Literal (Path actions)
package MyApp::Controller::My::Controller;
sub bar : Path(foo/bar) { }
Literal Path actions will act relative to their current namespace. The above example
matches only http://localhost:3000/my/controller/foo/bar. If you start your path
with a forward slash, it will match from the root. Example:
package MyApp::Controller::My::Controller;
sub bar : Path(/foo/bar) { }
Matches only http://localhost:3000/foo/bar.
package MyApp::Controller::My::Controller;
sub bar : Path { }
By leaving the Path definition empty, it will match on the namespace root. The above
code matches http://localhost:3000/my/controller.
* Regex
sub bar : Regex(^item(\d+)/order(\d+)$) { }
Matches any URL that matches the pattern in the action key, e.g.
http://localhost:3000/item23/order42. The around the regexp is optional, but
perltidy likes it. :)
Regex matches act globally, i.e. without reference to the namespace from which it is
called, so that a bar method in the MyApp::Controller::Catalog::Order::Process
namespace wont match any form of bar, Catalog, Order, or Process unless you
explicitly put this in the regex. To achieve the above, you should consider using a
LocalRegex action.
* LocalRegex
sub bar : LocalRegex(^widget(\d+)$) { }

How It Works

93

LocalRegex actions act locally.


If you were to use bar in
MyApp::Controller::Catalog, the above example would match urls like
http://localhost:3000/catalog/widget23.
If you omit the ^ from your regex, then it will match any depth from the controller
and not immediately off of the controller name. The following example differs from
the above code in that it will match http://localhost:3000/catalog/foo/widget23 as
well.
package MyApp::Controller::Catalog;
sub bar : LocalRegex(widget(\d+)$) { }
For both LocalRegex and Regex actions, if you use capturing parentheses to extract
values within the matching URL, those values are available in the $c-&gt;req&gt;captures array. In the above example, widget23 would capture 23 in the
above example, and $c-&gt;req-&gt;captures-&gt;[0] would be 23. If you want
to pass arguments at the end of your URL, you must use regex action keys. See URL
Path Handling below.
* Top-level (Global)
package MyApp::Controller::Foo;
sub foo : Global { }
Matches http://localhost:3000/foo. The function name is mapped directly to the
application base. You can provide an equivalent function in this case by doing the
following:
package MyApp::Controller::Root
sub foo : Local { }

* Namespace-Prefixed (Local)
package MyApp::Controller::My::Controller;
sub foo : Local { }
Matches http://localhost:3000/my/controller/foo.
This action type indicates that the matching URL must be prefixed with a modified
form of the components class (package) name. This modified class name excludes
the parts that have a pre-defined meaning in Catalyst (MyApp::Controller in the
above example), replaces :: with /, and converts the name to lower case. See
Components for a full explanation of the pre-defined meaning of Catalyst component
class names.

94

Catalyst::Manual::Intro

* Chained
Catalyst also provides a method to build and dispatch chains of actions, like
sub catalog : Chained : CaptureArgs(1) {
my ( $self, $c, $arg ) = @_;
...
}
sub item : Chained(catalog) : Args(1) {
my ( $self, $c, $arg ) = @_;
...
}
to handle a /catalog/*/item/* path. For further information about this dispatch
type, please see Catalyst::DispatchType::Chained.
* Private
sub foo : Private { }
Matches no URL, and cannot be executed by requesting a URL that corresponds to
the action key. Private actions can be executed only inside a Catalyst application, by
calling the forward method:
$c->forward(foo);
See Flow Control for a full explanation of forward.
Note that, as
discussed there, when forwarding from another component, you must use
the absolute path to the method, so that a private bar method in your
MyApp::Controller::Catalog::Order::Process controller must, if called from elsewhere, be reached with $c-&gt;forward(/catalog/order/process/bar).
* Args
Args is not an action type per se, but an action modifier - it adds a match restriction
to any action its provided to, requiring only as many path parts as are specified for
the action to be valid - for example in MyApp::Controller::Foo,
sub bar :Local
would match any URL starting /foo/bar/. To restrict this you can do
sub bar :Local :Args(1)
to only match /foo/bar/*/

How It Works

95

Note: After seeing these examples, you probably wonder what the point is of defining
names for regex and path actions. Every public action is also a private one, so you have
one unified way of addressing components in your forwards.

Built-in Private Actions


In response to specific application states, Catalyst will automatically call these built-in
private actions in your application class:
* default : Private
Called when no other action matches. Could be used, for example, for displaying a
generic frontpage for the main app, or an error page for individual controllers.
If default isnt acting how you would expect, look at using a Literal Path action
(with an empty path string). The difference is that Path takes arguments relative from
the namespace and default always takes arguments relative from the root, regardless
of what controller its in. Indeed, this is now the recommended way of handling default
situations; the default private controller should be considered deprecated.
* index : Private
index is much like default except that it takes no arguments and it is weighted
slightly higher in the matching process. It is useful as a static entry point to a
controller, e.g. to have a static welcome page. Note that its also weighted higher
than Path.
* begin : Private
Called at the beginning of a request, before any matching actions are called.
* end : Private
Called at the end of a request, after all matching actions are called.

Built-in actions in controllers/autochaining


Package MyApp::Controller::Foo;
sub begin : Private { }
sub default : Private { }
sub auto : Private { }
You can define built-in private actions within your controllers as well. The actions will
override the ones in less-specific controllers, or your application class. In other words, for
each of the three built-in private actions, only one will be run in any request cycle. Thus,
if MyApp::Controller::Catalog::begin exists, it will be run in place of MyApp::begin
if youre in the catalog namespace, and MyApp::Controller::Catalog::Order::begin
would override this in turn.
* auto : Private
In addition to the normal built-in actions, you have a special action for making chains,

96

Catalyst::Manual::Intro
auto. Such auto actions will be run after any begin, but before your action is
processed. Unlike the other built-ins, auto actions do not override each other; they
will be called in turn, starting with the application class and going through to the
most specific class. This is the reverse of the order in which the normal built-ins
override each other.
Here are some examples of the order in which the various built-ins would be called:

for a request for /foo/foo


MyApp::begin
MyApp::auto
MyApp::Controller::Foo::default # in the absence of
MyApp::Controller::Foo::Foo
MyApp::end
for a request for /foo/bar/foo
MyApp::Controller::Foo::Bar::begin
MyApp::auto
MyApp::Controller::Foo::auto
MyApp::Controller::Foo::Bar::auto
MyApp::Controller::Foo::Bar::default # for MyApp::Controller::Foo::Bar::foo
MyApp::Controller::Foo::Bar::end
The auto action is also distinguished by the fact that you can break out of the processing
chain by returning 0. If an auto action returns 0, any remaining actions will be skipped,
except for end. So, for the request above, if the first auto returns false, the chain would
look like this:
for a request for /foo/bar/foo where first auto returns false
MyApp::Controller::Foo::Bar::begin
MyApp::auto
MyApp::Controller::Foo::Bar::end
An example of why one might use this is an authentication action: you could set up a
auto action to handle authentication in your application class (which will always be called
first), and if authentication fails, returning 0 would skip any remaining methods for that
URL.
Note: Looking at it another way, auto actions have to return a true value to continue
processing! You can also die in the auto action; in that case, the request will go straight
to the finalize stage, without processing further actions.

How It Works

97

URL Path Handling


You can pass variable arguments as part of the URL path, separated with forward slashes
(/). If the action is a Regex or LocalRegex, the $ anchor must be used. For example,
suppose you want to handle /foo/$bar/$baz, where $bar and $baz may vary:
sub foo : Regex(^foo$) { my ($self, $context, $bar, $baz) = @_; }
But what if you also defined actions for /foo/boo and /foo/boo/hoo?
sub boo : Path(foo/boo) { .. }
sub hoo : Path(foo/boo/hoo) { .. }
Catalyst matches actions in most specific to least specific order:
/foo/boo/hoo
/foo/boo
/foo # might be /foo/bar/baz but wont be /foo/boo/hoo
So Catalyst would never mistakenly dispatch the first two URLs to the foo$ action.
If a Regex or LocalRegex action doesnt use the $ anchor, the action will still match a
URL containing arguments, however the arguments wont be available via @_.

Parameter Processing
Parameters passed in the URL query string are handled with methods in the Catalyst::Request class. The param method is functionally equivalent to the param method
of CGI.pm and can be used in modules that require this.
# http://localhost:3000/catalog/view/?category=hardware&page=3
my $category = $c->req->param(category);
my $current_page = $c->req->param(page) || 1;
# multiple values for single parameter name
my @values = $c->req->param(scrolling_list);
# DFV requires a CGI.pm-like input hash
my $results = Data::FormValidator->check($c->req->params, \%dfv_profile);

Flow Control
You control the application flow with the forward method, which accepts the key of an
action to execute. This can be an action in the same or another Catalyst controller, or a
Class name, optionally followed by a method name. After a forward, the control flow will
return to the method from which the forward was issued.
A forward is similar to a method call. The main differences are that it wraps the call
in an eval to allow exception handling; it automatically passes along the context object

98

Catalyst::Manual::Intro

($c or $context); and it allows profiling of each call (displayed in the log with debugging
enabled).
sub hello : Global {
my ( $self, $c ) = @_;
$c->stash->{message} = Hello World!;
$c->forward(check_message); # $c is automatically included
}
sub check_message : Private {
my ( $self, $c ) = @_;
return unless $c->stash->{message};
$c->forward(show_message);
}
sub show_message : Private {
my ( $self, $c ) = @_;
$c->res->body( $c->stash->{message} );
}
A forward does not create a new request, so your request object ($c-&gt;req) will
remain unchanged. This is a key difference between using forward and issuing a redirect.
You can pass new arguments to a forward by adding them in an anonymous array. In
this case $c-&gt;req-&gt;args will be changed for the duration of the forward only; upon
return, the original value of $c-&gt;req-&gt;args will be reset.
sub hello : Global {
my ( $self, $c ) = @_;
$c->stash->{message} = Hello World!;
$c->forward(check_message,[qw/test1/]);
# now $c->req->args is back to what it was before
}
sub check_message : Private {
my ( $self, $c ) = @_;
my $first_argument = $c->req->args->[0]; # now = test1
# do something...
}
As you can see from these examples, you can just use the method name as long as
you are referring to methods in the same controller. If you want to forward to a method in
another controller, or the main application, you will have to refer to the method by absolute
path.
$c->forward(/my/controller/action);
$c->forward(/default); # calls default in main application

How It Works

99

Here are some examples of how to forward to classes and methods.


sub hello : Global {
my ( $self, $c ) = @_;
$c->forward(qw/MyApp::Model::Hello say_hello/);
}
sub bye : Global {
my ( $self, $c ) = @_;
$c->forward(MyApp::Model::Hello); # no method: will try process
}
package MyApp::Model::Hello;
sub say_hello {
my ( $self, $c ) = @_;
$c->res->body(Hello World!);
}
sub process {
my ( $self, $c ) = @_;
$c->res->body(Goodbye World!);
}
Note that forward returns to the calling action and continues processing after the action
finishes. If you want all further processing in the calling action to stop, use detach instead,
which will execute the detached action and not return to the calling sub. In both cases,
Catalyst will automatically try to call process() if you omit the method.

Testing
Catalyst has a built-in http server for testing or local deployment. (Later, you can easily
use a more powerful server, for example Apache/mod perl or FastCGI, in a production
environment.)
Start your application on the command line...
script/myapp_server.pl
...then visit http://localhost:3000/ in a browser to view the output.
You can also do it all from the command line:
script/myapp_test.pl http://localhost/
Catalyst has a number of tools for actual regression testing of applications. The helper
scripts will automatically generate basic tests that can be extended as you develop your
project. To write your own comprehensive test scripts, Test::WWW::Mechanize::Catalyst
is an invaluable tool.

100

Catalyst::Manual::Intro
For more testing ideas, see Catalyst::Manual::Tutorial::Testing.
Have fun!

SEE ALSO
* Catalyst::Manual::About
* Catalyst::Manual::Tutorial
* Catalyst

SUPPORT
IRC:
Join #catalyst on irc.perl.org.
Join #catalyst-dev on irc.perl.org to help with development.
Mailing lists:
http://lists.rawmode.org/mailman/listinfo/catalyst
http://lists.rawmode.org/mailman/listinfo/catalyst-dev

AUTHOR
Sebastian Riedel, sri@oook.de David Naughton, naughton@umn.edu Marcus Ramberg, mramberg@cpan.org Jesse Sheidlower, jester@panix.com Danijel Milicevic,
me@danijel.de Kieren Diment, kd@totaldatasolution.com Yuval Kogman, nothingmuch@woobling.org

COPYRIGHT
This program is free software. You can redistribute it and/or modify it under the same
terms as Perl itself.

Catalyst::Manual::Plugins Catalyst Plugins (and


Components)
This section lists the some of the plugins and components that are available to extend
the runtime functionality of Catalyst. Most plugins are not distributed with Catalyst but
should be available from CPAN. They typically require additional modules from CPAN.
This list may well be outdated by the time you read this and some plugins may be deprecated or now part of core Catalyst. Be sure to check the Catalyst::Plugin namespace for
additional plugins and consult the mailing list ( http://dev.catalyst.perl.org/wiki/Support38
) for advice on the current status or preferred use of your chosen plugin/framework.

PLUGINS
Catalyst::Plugin::Account::AutoDiscovery
Provides Account Auto-Discovery for Catalyst.

Catalyst::Plugin::Acme::Scramble
Implements a potent meme about how easily we can read scrambled text if the first and
last letters remain constant. Operates on text/plain and text/html served by your Catalyst
application.

Catalyst::Plugin::Alarm
Catalyst::Plugin::AtomPP
Allows you to dispatch AtomPP methods.

Catalyst::Plugin::AtomServer
A plugin that implements the necessary bits to make it easy to build an Atom API server
for any Catalyst-based application.
38

http://dev.catalyst.perl.org/wiki/Support

101

102

Catalyst::Manual::Plugins

Catalyst::Plugin::Authentication
An infrastructure plugin for the Catalyst authentication framework. Now the recommended
way to do any form of Authentication.

Catalyst::Plugin::Authentication::Credential::Atom
Catalyst::Plugin::Authentication::Credential::Atom is a plugin which implements WSSE and Basic authentication for Catalyst applications using Catalyst::Plugin::AtomServer

Catalyst::Plugin::Authentication::Credential::CHAP
Catalyst::Plugin::Authentication::Credential::Flickr
Provides authentication via Flickr, using its API.

Catalyst::Plugin::Authentication::Credential::Hatena
Catalyst::Plugin::Authentication::Credential::HTTP
Implements HTTP Basic authentication for Catalyst.

Catalyst::Plugin::Authentication::Credential::JugemKey
Catalyst::Plugin::Authentication::Credential::PAM
Catalyst::Plugin::Authentication::Credential::Password
Takes a username (or userid) and a password, and tries various methods of comparing a
password based on what the chosen stores user objects support. Part of the Authentication
Framework Catalyst::Plugin::Authentication.

Catalyst::Plugin::Authentication::Credential::TypeKey
Integrates Authen::TypeKey with Catalyst::Plugin::Authentication.

Catalyst::Plugin::Authentication::OpenID
Catalyst::Plugin::Authentication::OpenID is a plugin that implements support
for OpenID authentication.
For more information on OpenID, take a look at
http://www.openid.net/39 .

Catalyst::Plugin::Authentication::Store
The core authentication store documentation.
39

http://www.openid.net/

PLUGINS

103

Catalyst::Plugin::Authentication::Store::DBIC
Does authentication and authorization against a DBIx::Class or Class::DBI model.

Catalyst::Plugin::Authentication::Store::Htpasswd
Uses Authen::Htpasswd to let your application use .htpasswd files for its authentication
storage.

Catalyst::Plugin::Authentication::Store::HTTP
Catalyst::Plugin::Authentication::Store::LDAP
Authenticates users using an LDAP server.

Catalyst::Plugin::Authentication::Store::Minimal
Lets you create a very quick and dirty user database in your applications config hash. Great
for getting up and running quickly.

Catalyst::Plugin::Authentication::User::Hash
An easy authentication user object based on hashes.
lyst::Plugin::Authentication::Store::Minimal for more info.

See

Cata-

Catalyst::Plugin::Authorization::ACL
This module provides Access Control List style path protection, with arbitrary rules for
Catalyst applications. It operates only on the Catalyst private namespace, at least at the
moment.

Catalyst::Plugin::Authorization::Roles
Catalyst::Plugin::Authorization::Roles provides role based authorization for Catalyst based on Catalyst::Plugin::Authentication.

Catalyst::Plugin::AutoSession
Catalyst::Plugin::Browser
Extends Catalyst::Request by adding the capability of browser detection. It returns an
instance of HTTP::BrowserDetect, which lets you get information from the clients user
agent.

104

Catalyst::Manual::Plugins

Catalyst::Plugin::Cache::FastMmap, FileCache, BerkeleyDB, and Memcached


Catalyst::Plugin::Cache::FastMmap, Catalyst::Plugin::Cache::FileCache, Catalyst::Plugin::Cache::BerkeleyDB, and Catalyst::Plugin::Cache::Memcached all
provide a cache method enabling easy access to a shared cache.

Catalyst::Plugin::Captcha
Catalyst::Plugin::CGI::Untaint
Catalyst::Plugin::Charsets::Japanese
Catalyst::Plugin::Compress::Bzip2
Catalyst::Plugin::Compress::Deflate
Catalyst::Plugin::Compress::Gzip
Catalyst::Plugin::Compress::Zlib
Catalyst::Plugin::ConfigLoader
Provides a standard method for loading config files. Support exists for various formats. See
Catalyst::Plugin::ConfigLoader::INI,
Catalyst::Plugin::ConfigLoader::JSON,
Catalyst::Plugin::ConfigLoader::Perl,
Catalyst::Plugin::ConfigLoader::XML,
and Catalyst::Plugin::ConfigLoader::YAML

Catalyst::Plugin::ConfigurablePathTo
Catalyst::Plugin::Continuation
Catalyst::Plugin::DateTime
Catalyst::Plugin::DefaultEnd
Creates a sane, standard end method for your application.

Catalyst::Plugin::Devel::InPageLogs
Catalyst::Plugin::Devel::InPageLogs::Log
Catalyst::Plugin::Dojo
Catalyst::Plugin::Dumper
Catalyst::Plugin::Email
Sends email with Email::Send and Email::MIME::Creator.

PLUGINS

105

Catalyst::Plugin::Email::Japanese
Catalyst::Plugin::Email::Page
Catalyst::Plugin::EmailValid
Catalyst::Plugin::FillInForm
A plugin based on HTML::FillInForm, which describes itself as a module to automatically
insert data from a previous HTML form into the HTML input, textarea, radio buttons,
checkboxes, and select tags. HTML::FillInForm is a subclass of HTML::Parser and uses it
to parse the HTML and insert the values into the form tags.

Catalyst::Plugin::Flavour
Catalyst::Plugin::FormValidator
A form validator plugin that uses Data::FormValidator to validate and set up form data
from your request parameters. Its a quite thin wrapper around that module, so most of
the relevant information can be found there.

Catalyst::Plugin::FormValidator::Simple
Catalyst::Plugin::Geography
Allows you to retrieve various kinds of geographical information. You can retrieve the
country or code from the current user, from a given IP address, or from a given hostname.

Catalyst::Plugin::Geography::Implementation
Catalyst::Plugin::HashedCookies
Catalyst::Plugin::HTML::Scrubber
Catalyst::Plugin::HTML::Widget
Catalyst::Plugin::I18N
An internationalization plugin for Catalyst. Supports mo/po files and Maketext classes
under your applications I18N namespace.

106

Catalyst::Manual::Plugins

Catalyst::Plugin::JSONRPC
Catalyst::Plugin::Markdown
Catalyst::Plugin::Message
Catalyst::Plugin::MobileAgent
Catalyst::Plugin::Observe
Provides the ability to register AOP-like callbacks to specific Engine events. Subclasses
Class::Publisher.

Catalyst::Plugin::OrderedParams
Adjusts the way that parameters operate, causing them to appear in the same order they
were submitted by the browser. This can be useful for creating things such as email forms.

Catalyst::Plugin::PageCache
Helps improve the performance of slow or frequently accessed pages by caching the entire
output of your page. Subsequent requests to the page will receive the page very quickly
from cache.

Catalyst::Plugin::Params::Nested
Catalyst::Plugin::Params::Nested::Expander
Catalyst::Plugin::Pluggable
A plugin for pluggable Catalyst applications.

Catalyst::Plugin::Prototype
A plugin for the Prototype JavaScript library. This Plugin allows you to easily implement
AJAX functionality without actually knowing Javascript.

Catalyst::Plugin::Redirect
Catalyst::Plugin::RequestToken
Catalyst::Plugin::RequireSSL
Use this if you would like to force visitors to access certain pages using only SSL mode. An
attempt to access the page in non-SSL mode will receive a redirect into SSL mode. Useful
for login pages, shopping carts, user registration forms, and other sensitive data.

PLUGINS

107

Catalyst::Plugin::Scheduler
Catalyst::Plugin::Session
The Catalyst::Plugin::Session series of modules provide an easy way to include session
handling in an application. You can choose from several different backend storage methods
and combine that with your choice of client-side storage methods.

Catalyst::Plugin::Session::PerUser
Catalyst::Plugin::Session::State
Catalyst::Plugin::Session::State::Cookie
Catalyst::Plugin::Session::State::URI
Catalyst::Plugin::Session::Store
Catalyst::Plugin::Session::Store::CDBI
Catalyst::Plugin::Session::Store::DBI
Catalyst::Plugin::Session::Store::DBIC
Catalyst::Plugin::Session::Store::Dummy
Catalyst::Plugin::Session::Store::FastMmap
Catalyst::Plugin::Session::Store::File
Catalyst::Plugin::Session::Store::Memcached
Catalyst::Plugin::Session::Test::Store
Catalyst::Plugin::Singleton
Catalyst::Plugin::Snippets
Catalyst::Plugin::SRU
Allows your controller class to dispatch SRU actions (explain, scan, and searchRetrieve)
from its own class.

Catalyst::Plugin::StackTrace
Catalyst::Plugin::Static
Catalyst::Plugin::Static is a plugin to serve static files from $c->config->{root}.
Intended chiefly for development purposes.

108

Catalyst::Manual::Plugins

Catalyst::Plugin::Static::Simple
Serves static files in your application without requiring a single line of code. This plugin is
now included in the core Catalyst distribution.

Catalyst::Plugin::SubRequest
A plugin to allow subrequests to actions to be made within Catalyst. Nice for portal software
and such.

Catalyst::Plugin::SuperForm
An interface to the HTML::SuperForm module, enabling easy HTML form creation.

Catalyst::Plugin::Textile
A persistent Textile processor for Catalyst that uses Text::Textile, a Perl-based implementation of Dean Allens Textile syntax. Textile is shorthand for doing common formatting
tasks (see http://textism.com40 ).

Catalyst::Plugin::Unicode
Provides a Unicode-aware Catalyst. On request, it decodes all params from UTF-8 octets
into a sequence of logical characters. On response, it encodes the body into UTF-8 octets.

Catalyst::Plugin::Unicode::Encoding
Catalyst::Plugin::Upload::Basename
Catalyst::Plugin::Upload::MD5
Catalyst::Plugin::Upload::MIME
Catalyst::Plugin::UploadProgress
Catalyst::Plugin::XMLRPC
Allows your Controller class to dispatch XMLRPC methods from its own class.

CONTROLLERS
Catalyst::Controller::BindLex
Lets you mark lexical variables with a Stashed attribute, automatically passing them to
the stash.
40

http://textism.com

MODELS

109

MODELS
Catalyst::Model::CDBI
The Class::DBI (CDBI) model class. It is built on top of Class::DBI::Loader, which automates the definition of Class::DBI sub-classes by scanning the underlying table schemas,
setting up columns and primary keys.

Catalyst::Model::CDBI::Plain
A neutral interface to the Class::DBI module which does not attempt to automate table
setup. It allows the user to manually set up Class::DBI classes, either by doing so within
the Catalyst model classes themselves, or by inheriting from existing Class::DBI classes.

Catalyst::Model::DBIC::Schema
A DBIx::Class model class that can use either an explicit DBIx::Class::Schema or one
automatically loaded from your database via DBIx::Class::Schema::Loader.

Catalyst::Model::EVDB
Catalyst::Model::File
Catalyst::Model::Gedcom
Catalyst::Model::LDAP
Catalyst::Model::NetBlogger
Catalyst::Model::Plucene
A model class for the Plucene search engine.

Catalyst::Model::Proxy
Catalyst::Model::SVN
Catalyst::Model::Xapian
A model class for the Xapian search engine.

110

Catalyst::Manual::Plugins

VIEWS
Catalyst::View::Atom::XML
Catalyst::View::Chart::Strip
Catalyst::View::CSS::Squish
Catalyst::View::Embperl
Catalyst::View::GD::Barcode
Catalyst::View::GraphViz
Catalyst::View::HTML::Template
A view component for rendering pages with HTML::Template.

Catalyst::View::Jemplate
Catalyst::View::JSON
Catalyst::View::Mason
A view component for rendering pages with HTML::Mason.

Catalyst::View::MicroMason
Catalyst::View::PHP
Catalyst::View::PSP
A view component for rendering pages using PSP, a Perl extension implementing a JSP-like
templating system. See Text::PSP.

Catalyst::View::Petal
A view component for rendering pages using Petal, the Perl Template Attribute Language,
an XML-based templating system. See Petal.

Catalyst::View::TT
A view component for rendering pages with Template Toolkit. See Template::Manual.

OBSOLETE MODULES

111

Catalyst::View::XSLT
Catalyst::View::vCard

OBSOLETE MODULES
Catalyst::Model::DBIC
Replaced by Catalyst::Model::DBIC::Schema.

Catalyst::Plugin::Authentication::Basic::Remote
Replaced by Catalyst::Plugin::Authentication::Credential::HTTP.

Catalyst::Plugin::Authentication::CDBI
Replaced by Catalyst::Plugin::Authentication::Store::DBIC.

Catalyst::Plugin::Authentication::CDBI::Basic
Replaced by Catalyst::Plugin::Authentication::Credential::HTTP.

Catalyst::Plugin::Authentication::LDAP
Replaced by Catalyst::Plugin::Authentication::Store::LDAP.

Catalyst::Plugin::Authentication::Simple
Replaced by Catalyst::Plugin::Authentication.

Catalyst::Plugin::Authorization::CDBI::GroupToken
Catalyst::Plugin::CDBI::Transaction
Catalyst::Plugin::Config::*
The Catalyst::Plugin::Config::JSON and Catalyst::Plugin::Config::YAML modules
have been replaced by their corresponding Catalyst::Plugin::ConfigLoader modules.

Catalyst::Plugin::DefaultEnd
Replaced by Catalyst::Action::RenderView

112

Catalyst::Manual::Plugins

Catalyst::Plugin::SanitizeUrl
Catalyst::Plugin::SanitizeUrl::PrepAction
Catalyst::Plugin::Session::*
The Catalyst::Plugin::Session::CGISession, Catalyst::Plugin::Session::FastMmap,
Catalyst::Plugin::Session::Flex, and Catalyst::Plugin::Session::Manager modules have been replaced by the <Catalyst::Plugin::Session> framework.

AUTHORS
Andrew Ford <A.Ford@ford-mason.co.uk>
Gavin Henry <ghenry@suretecsystems.com>
Jesse Sheidlower <jester@panix.com>
Marcus Ramberg <mramberg@cpan.org>
David Kamholz <dkamholz@cpan.org>

COPYRIGHT
This program is free software, you can redistribute it and/or modify it under the same terms
as Perl itself.

Catalyst::Manual::Tutorial Catalyst Tutorial: Overview


The Catalyst framework is a flexible and comprehensive environment for quickly building
high-functionality web applications. This tutorial is designed to provide a rapid introduction
to its basics and its most commonly used features while focusing on real-world best practices.
The tutorial is divided into the following sections:
NOTE: CLICK THESE LINKS TO JUMP TO CHAPTERS (the index links above
only navigate inside this page).
Introduction
Catalyst Basics
Basic CRUD
Authentication
Authorization
Debugging
Testing
Advanced CRUD
Appendices

A
tarball
of
the
final
application
is
available
at
http://dev.catalyst.perl.org/repos/Catalyst/trunk/examples/Tutorial/Final Tarball/MyApp.tgz41 .

Detailed Table of Contents


Part 1: Introduction
VERSIONS AND CONVENTIONS USED IN THIS TUTORIAL
41

http://dev.catalyst.perl.org/repos/Catalyst/trunk/examples/Tutorial/Final_Tarball/MyApp.tgz

113

114

Catalyst::Manual::Tutorial
CATALYST INSTALLATION
DATABASES
WHERE TO GET WORKING CODE

Part 2: Catalyst Basics


CREATE A CATALYST PROJECT
CREATE A SQLITE DATABASE
EDIT THE LIST OF CATALYST PLUGINS
DATABASE ACCESS WITH DBIx::Class

Create a DBIC Schema File


Create the DBIC Result Source Files
Use Catalyst::Model::DBIC::Schema to Load the Model Class
CREATE A CATALYST CONTROLLER
CATALYST VIEWS

Create a Catalyst View Using TTSite


Using RenderView for the Default View
Globally Customize Every View
Create a TT Template Page
RUN THE APPLICATION
USING THE DEFAULT TEMPLATE NAME

Part 3: Basic CRUD


FORMLESS SUBMISSION

Include a Create Action in the Books Controller


Include a Template for the url create Action:
Try the url create Feature
MANUALLY BUILDING A CREATE FORM

Add a Method to Display the Form

Detailed Table of Contents

115

Add a Template for the Form


Add Method to Process Form Values and Update Database
Test Out the Form
A SIMPLE DELETE FEATURE

Include a Delete Link in the List


Add a Delete Action to the Controller
Try the Delete Feature

Part 4: Authentication
BASIC AUTHENTICATION

Add Users and Roles to the Database


Add User and Role Information to DBIC Schema
Create New Result Source Objects
Sanity-Check Reload of Development Server
Include Authentication and Session Plugins
Configure Authentication
Add Login and Logout Controllers
Add a Login Form TT Template Page
Add Valid User Check
Displaying Content Only to Authenticated Users
Try Out Authentication
USING PASSWORD HASHES

Get a SHA-1 Hash for the Password


Switch to SHA-1 Password Hashes in the Database
Enable SHA-1 Hash Passwords in Catalyst::Plugin::Authentication::Store::DBIC
Try Out the Hashed Passwords

Part 5: Authorization
BASIC AUTHORIZATION

Update Plugins to Include Support for Authorization


Add Config Information for Authorization
Add Role-Specific Logic to the Book List Template

116

Catalyst::Manual::Tutorial
Limit Books::add to admin Users
Try Out Authentication And Authorization
ENABLE ACL-BASED AUTHORIZATION

Add the Catalyst::Plugin::Authorization::ACL Plugin


Add ACL Rules to the Application Class
Add a Method to Handle Access Violations

Part 6: Debugging
LOG STATEMENTS
RUNNING CATALYST UNDER THE PERL DEBUGGER
DEBUGGING MODULES FROM CPAN

Part 7: Testing
RUNNING THE CANNED CATALYST TESTS
RUNNING A SINGLE TEST
ADDING YOUR OWN TEST SCRIPT
SUPPORTING BOTH PRODUCTION AND TEST DATABASES

Part 8: Advanced CRUD


HTML::WIDGET FORM CREATION

Add the HTML::Widget Plugin


Add a Form Creation Helper Method
Add Actions to Display and Save the Form
Update the CSS
Create a Template Page To Display The Form
Add Links for Create and Update via HTML::Widget
Test The <HTML::Widget> Create Form
HTML::WIDGET VALIDATION AND FILTERING

Add Constraints and Filters to the Widget Creation Method


Rebuild the Form Submission Method to Include Validation
Try Out the Form

THANKS

117

Enable DBIx::Class::HTMLWidget Support

Add DBIx::Class::HTMLWidget to DBIC Model


Use populate from widget in hw create do

Part 9: Appendices
APPENDIX 1: CUT AND PASTE FOR POD-BASED EXAMPLES

Un-indenting with Vi/Vim


Un-indenting with Emacs
APPENDIX 2: USING MYSQL AND POSTGRESQL

MySQL
PostgreSQL
APPENDIX 3: IMPROVED HASHING SCRIPT

THANKS
This tutorial would not have been possible without the input of many different people in
the Catalyst community. In particular, the primary author would like to thank:
Sebastian Riedel for founding the Catalyst project.
The members of the Catalyst Core Team for their tireless efforts to advance the
Catalyst project. Although all of the Core Team members have played a key role in
this tutorial, it would have never been possible without the critical contributions of:
Matt Trout, for his unfathomable knowledge of all things Perl and Catalyst (and his
willingness to answer lots of my questions); Jesse Sheidlower, for his incredible skill
with the written word and dedication to improving the Catalyst documentation; and
Yuval Kogman, for his work on the Catalyst Auth & Authz plugins (the original
focus of the tutorial) and other key Catalyst modules.
Other Catalyst documentation folks like Kieren Diment, Gavin Henry, and Jess Robinson (including their work on the original Catalyst tutorial).
Everyone on #catalyst and #catalyst-dev.
People who have emailed me with corrections and suggestions on the tutorial. As of the
most recent release, this include: Florian Ragwitz, Mauro Andreolini, Jim Howard,
Giovanni Gigante, William Moreno, Bryan Roach, Ashley Berlin, David Kamholz,
Kevin Old, Henning Sprang, Jeremy Jones, David Kurtz, and Ingo Wichmann.

118

Catalyst::Manual::Tutorial

AUTHOR
Kennedy Clark, hkclark@gmail.com
Please
report
any
errors,
issues
or
suggestions
to
the
author.
The most recent version of the Catalyst Tutorial can be
found
at
http://dev.catalyst.perl.org/repos/Catalyst/trunk/CatalystRuntime/lib/Catalyst/Manual/Tutorial/42 .
Copyright
2006,
Kennedy
Clark,
under
Creative
Commons
License
(http://creativecommons.org/licenses/by-nc-sa/2.5/43 ).

42
43

http://dev.catalyst.perl.org/repos/Catalyst/trunk/Catalyst-Runtime/lib/Catalyst/Manual/Tutorial/
http://creativecommons.org/licenses/by-nc-sa/2.5/

Catalyst::Manual::Tutorial::Intro Catalyst Tutorial - Part 1:


Introduction
This tutorial provides a multipart introduction to the Catalyst web framework. It seeks to
provide a rapid overview of many of its most commonly used features. The focus is on the
real-world best practices required in the construction of nearly all Catalyst applications.
Although the primary target of the tutorial is users new to the Catalyst framework, experienced users may wish to review specific sections (for example, how to use DBIC for their
model classes or how to add authentication and authorization to an existing application).
You can obtain the code for all the tutorial examples from the catalyst subversion
repository by issuing the command:
svn co http://dev.catalyst.perl.org/repos/Catalyst/tags/examples/Tutorial/
MyApp/5.7/ CatalystTutorial
This will download the current code for each tutorial chapter in the CatalystTutorial
directory. Each example application directory has the same name as the tutorial chapter.
Additionally, if youre reading this manual online, you can download the example
program and all the necessary dependencies to your local machine by installing the
Task::Catalyst::Tutorial distribution from CPAN:
cpan Task::Catalyst::Tutorial
This will also test to make sure the dependencies are working. If you have trouble
installing these, please ask for help on the #catalyst IRC channel, or the Catalyst mailing
list.
Subjects covered include:
A simple application that lists and adds books.
The use of DBIx::Class (DBIC) for the model.
How to write CRUD (Create, Read, Update, and Delete) operations in Catalyst.
Authentication (auth).

119

120

Catalyst::Manual::Tutorial::Intro
Role-based authorization (authz).
Attempts to provide an example showing current (5.7XXX) Catalyst practices.
For example, the use of Catalyst::Action::RenderView,
DBIC,
Catalyst::Plugin::ConfigLoader
with
myapp.yml,
the
use
of
lib/MyApp/Controller/Root.pm vs. lib/MyApp.pm, etc.
The use of Template Toolkit (TT) and the Catalyst::Helper::View::TTSite view helper.
Useful techniques for troubleshooting and debugging Catalyst applications.
The use of SQLite as a database (with code also provided for MySQL and PostgreSQL).
The use of HTML::Widget for automated form processing and validation.

This tutorial makes the learning process its main priority. For example, the level of
comments in the code found here would likely be considered excessive in a normal project.
Because of their contextual value, this tutorial will generally favor inline comments over a
separate discussion in the text. It also deliberately tries to demonstrate multiple approaches
to various features (in general, you should try to be as consistent as possible with your own
production code).
Furthermore, this tutorial tries to minimize the number of controllers, models, TT templates, and database tables. Although this does result in things being a bit contrived at
times, the concepts should be applicable to more complex environments. More complete
and complicated example applications can be found in the examples area of the Catalyst
Subversion repository at http://dev.catalyst.perl.org/repos/Catalyst/trunk/examples/44 .
Note: There are a variety of other introductory materials available through
the Catalyst web site and at http://dev.catalyst.perl.org/wiki/UserIntroductions45 and
http://dev.catalyst.perl.org/46 .

OVERVIEW
This is Part 1 of 9 of the Catalyst Tutorial.
Tutorial Overview
1. Introduction
2. Catalyst Basics
3. Basic CRUD
4. Authentication
44

http://dev.catalyst.perl.org/repos/Catalyst/trunk/examples/
http://dev.catalyst.perl.org/wiki/UserIntroductions
46
http://dev.catalyst.perl.org/
45

VERSIONS AND CONVENTIONS USED IN THIS TUTORIAL

121

5. Authorization
6. Debugging
7. Testing
8. Advanced CRUD
9. Appendices

VERSIONS AND CONVENTIONS USED IN THIS TUTORIAL


This tutorial was built using the following resources. Please note that you may need to
make adjustments for different environments and versions:
OS = CentOS 4 Linux (RHEL 4)
Catalyst v5.6902
DBIx::Class v0.06003
Catalyst Plugins

The plugins used in this tutorial all have sufficiently stable APIs that you shouldnt
need to worry about versions. However, there could be cases where the tutorial is
affected by what version of plugins you use. This tutorial has been tested against the
following set of plugins:
Catalyst::Plugin::Authentication -- 0.09
Catalyst::Plugin::Authentication::Store::DBIC -- 0.07
Catalyst::Plugin::Authorization::ACL -- 0.08
Catalyst::Plugin::Authorization::Roles -- 0.04
Catalyst::Plugin::ConfigLoader -- 0.13
Catalyst::Plugin::HTML::Widget -- 1.1
Catalyst::Plugin::Session -- 0.12
Catalyst::Plugin::Session::State::Cookie -- 0.05
Catalyst::Plugin::Session::Store::FastMmap -- 0.02
Catalyst::Plugin::StackTrace -- 0.06
Catalyst::Plugin::Static::Simple -- 0.14

122

Catalyst::Manual::Tutorial::Intro
Since the web browser is being used on the same box where Perl and the Catalyst
development server is running, the URL of http://localhost:3000 will be used
(the Catalyst development server defaults to port 3000). If you are running Perl on
a different box than where your web browser is located (or using a different port
number via the -p port number option to the development server), then you will need
to update the URL you use accordingly.
Depending on the web browser you are using, you might need to hit Shift+Reload
to pull a fresh page when testing your application at various points. Also, the k keepalive option to the development server can be necessary with some browsers
(especially Internet Explorer).

CATALYST INSTALLATION
Unfortunately, one of the most daunting tasks faced by newcomers to Catalyst is getting it
installed. Although a compelling strength of Catalyst is that it can easily make use of many
of the modules in the vast repository that is CPAN, this can result in initial installations
that are both time consuming and frustrating. However, there are a growing number of
methods that can dramatically ease this undertaking. Of these, the following are likely to
be applicable to the largest number of potential new users:
Matt Trouts cat-install

Available at http://www.shadowcatsystems.co.uk/static/cat-install47 , cat-install


can be a quick and painless way to get Catalyst up and running. Just download the
script from the link above and type perl cat-install.
Chris Lacos CatInABox

Download the tarball from http://handelframework.com/downloads/CatInABox.tar.gz48


and unpack it on your machine. Depending on your OS platform, either run start.bat
or start.sh.
Pre-Built VMWare Images

Under the VMWare community program, work is ongoing to develop a number of


VMWare images where an entire Catalyst development environment has already been
installed, complete with database engines and a full complement of Catalyst plugins.
For additional information and recommendations on Catalyst installation, please refer
to Catalyst::Manual::Installation.
NOTE: Step-by-step instructions to replicate the environment on which this tutorial
was developed can be found at Catalyst::Manual::Installation::CentOS4. Using these instructions, you should be able to build a complete CentOS 4.X server with Catalyst and all
the plugins required to run this tutorial.
47
48

http://www.shadowcatsystems.co.uk/static/cat-install
http://handelframework.com/downloads/CatInABox.tar.gz

DATABASES

123

DATABASES
This tutorial will primarily focus on SQLite because of its simplicity of installation and use;
however, modifications in the script required to support MySQL and PostgreSQL will be
presented in Appendix 2.
Note: One of the advantages of the MVC design patterns is that applications become
much more database independent. As such, you will notice that only the .sql files used
to initialize the database change between database systems: the Catalyst code generally
remains the same.

WHERE TO GET WORKING CODE


Each part of the tutorial has complete code available in the main Catalyst Subversion repository (see the note at the beginning of each part for the appropriate svn
command to use). Additionally, the final code is available as a ready-to-run tarball at
http://dev.catalyst.perl.org/repos/Catalyst/trunk/examples/Tutorial/Final Tarball/MyApp.tgz49 .
NOTE: You can run the test cases for the final code with the following commands:
wget http://dev.catalyst.perl.org/repos/Catalyst/trunk/examples/Tutorial/
Final_Tarball/MyApp.tgz
tar zxvf MyApp.tgz
cd MyApp
CATALYST_DEBUG=0 prove --lib lib t

AUTHOR
Kennedy Clark, hkclark@gmail.com
Please
report
any
errors,
issues
or
suggestions
to
the
author.
The most recent version of the Catalyst Tutorial can be
found
at
http://dev.catalyst.perl.org/repos/Catalyst/trunk/CatalystRuntime/lib/Catalyst/Manual/Tutorial/50 .
Copyright
2006,
Kennedy
Clark,
under
Creative
Commons
License
51
(http://creativecommons.org/licenses/by-nc-sa/2.5/ ).

49

http://dev.catalyst.perl.org/repos/Catalyst/trunk/examples/Tutorial/Final_Tarball/MyApp.tgz
http://dev.catalyst.perl.org/repos/Catalyst/trunk/Catalyst-Runtime/lib/Catalyst/Manual/Tutorial/
51
http://creativecommons.org/licenses/by-nc-sa/2.5/
50

124

Catalyst::Manual::Tutorial::Intro

Catalyst::Manual::Tutorial::CatalystBasics
- Catalyst Tutorial - Part 2:
Catalyst Application Development
Basics
In this part of the tutorial, we will create a very basic Catalyst web application. Though
simple in many respects, this section will already demonstrate a number of powerful capabilities such as:
* Helper Scripts
Catalyst helper scripts that can be used to rapidly bootstrap the skeletal structure of
an application.
* MVC
Model/View/Controller (MVC) provides an architecture that facilitates a clean separation of control between the different portions of your application. Given that many
other documents cover this subject in detail, MVC will not be discussed in depth
here (for an excellent introduction to MVC and general Catalyst concepts, please see
Catalyst::Manual::About. In short:
* Model
The model usually represents a data store. In most applications, the model
equates to the objects that are created from and saved to your SQL database.
* View
The view takes model objects and renders them into something for the end user
to look at. Normally this involves a template-generation tool that creates HTML
for the users web browser, but it could easily be code that generates other forms
such as PDF documents, e-mails, or Excel spreadsheets.
* Controller
As suggested by its name, the controller takes user requests and routes them to
the necessary model and view.
125

126

Catalyst::Manual::Tutorial::CatalystBasics

* ORM
The use of Object-Relational Mapping (ORM) technology for database access. Specifically, ORM provides an automated and standardized means to persist and restore
objects to/from a relational database.
You can checkout the source code for this example from the catalyst subversion repository as per the instructions in Catalyst::Manual::Tutorial::Intro

OVERVIEW
This is Part 2 of 9 for the Catalyst tutorial.
Tutorial Overview
1. Introduction
2. Catalyst Basics
3. Basic CRUD
4. Authentication
5. Authorization
6. Debugging
7. Testing
8. Advanced CRUD
9. Appendices

CREATE A CATALYST PROJECT


Catalyst provides a number of helper scripts that can be used to quickly flesh out the
basic structure of your application. All Catalyst projects begin with the catalyst.pl
helper (see Catalyst::Helper for more information on helpers). Also note that as of Catalyst
5.7000, you will not have the helper scripts unless you install both Catalyst::Runtime and
Catalyst::Devel.
In the case of this tutorial, use the Catalyst catalyst.pl script to initialize the framework for an application called MyApp:
$ catalyst.pl MyApp
created "MyApp"
created "MyApp/script"
created "MyApp/lib"
created "MyApp/root"

CREATE A CATALYST PROJECT

127

...
created "MyApp/script/myapp_create.pl"
$ cd MyApp
The catalyst.pl helper script will display the names of the directories and files it
creates.
Though its too early for any significant celebration, we already have a functioning application. Run the following command to run this application with the built-in development
web server:
$ script/myapp_server.pl
[debug] Debug messages enabled
[debug] Loaded plugins:
.---------------------------------------------------------------------------.
| Catalyst::Plugin::ConfigLoader 0.13
|
| Catalyst::Plugin::Static::Simple 0.14
|
---------------------------------------------------------------------------
[debug] Loaded dispatcher "Catalyst::Dispatcher"
[debug] Loaded engine "Catalyst::Engine::HTTP"
[debug] Found home "/home/me/MyApp"
[debug] Loaded Config "/home/me/myapp.yml"
[debug] Loaded components:
.-----------------------------------------------------------------+---------.
| Class
| Type
|
+-----------------------------------------------------------------+---------+
| MyApp::Controller::Root
| instance |
-----------------------------------------------------------------+---------
[debug] Loaded Private actions:
.----------------------+--------------------------------------+-------------.
| Private
| Class
| Method
|
+----------------------+--------------------------------------+-------------+
| /default
| MyApp::Controller::Root
| default
|

128

Catalyst::Manual::Tutorial::CatalystBasics

| /end
| MyApp::Controller::Root
| end
|
----------------------+--------------------------------------+-------------
[info] MyApp powered by Catalyst 5.7002
You can connect to your server at http://localhost:3000
NOTE: Be sure you run the script/myapp_server.pl command from the base directory of your application, not inside the script directory itself. It doesnt make a difference
at this point, but it will as soon as we get the database going in the next section.
Point your web browser to http://localhost:300052 (substituting a different hostname
or IP address as appropriate) and you should be greeted by the Catalyst welcome screen.
Information similar to the following should be appended to the logging output of the development server:
[info] *** Request 1 (0.043/s) [6003] [Fri Jul 7 13:32:53 2006] ***
[debug] "GET" request for "/" from "127.0.0.1"
[info] Request took 0.067675s (14.777/s)
.----------------------------------------------------------------+----------.
| Action
| Time
|
+----------------------------------------------------------------+----------+
| /default
|
0.002844s |
| /end
|
0.000207s |
----------------------------------------------------------------+----------
Press Ctrl-C to break out of the development server.

CREATE A SQLITE DATABASE


In this step, we make a text file with the required SQL commands to create a database
table and load some sample data. Open myapp01.sql in your editor and enter:
--- Create a very simple database to hold book and author information
-CREATE TABLE books (
id
INTEGER PRIMARY KEY,
52

http://localhost:3000

CREATE A SQLITE DATABASE


title
rating

129

TEXT ,
INTEGER

);
-- book_authors is a many-to-many join table between books & authors
CREATE TABLE book_authors (
book_id
INTEGER,
author_id
INTEGER,
PRIMARY KEY (book_id, author_id)
);
CREATE TABLE authors (
id
INTEGER PRIMARY KEY,
first_name TEXT,
last_name
TEXT
);
----- Load some sample data
--INSERT INTO books VALUES (1, CCSP SNRS Exam Certification Guide, 5);
INSERT INTO books VALUES (2, TCP/IP Illustrated, Volume 1, 5);
INSERT INTO books VALUES (3, Internetworking with TCP/IP Vol.1, 4);
INSERT INTO books VALUES (4, Perl Cookbook, 5);
INSERT INTO books VALUES (5, Designing with Web Standards, 5);
INSERT INTO authors VALUES (1, Greg, Bastien);
INSERT INTO authors VALUES (2, Sara, Nasseh);
INSERT INTO authors VALUES (3, Christian, Degu);
INSERT INTO authors VALUES (4, Richard, Stevens);
INSERT INTO authors VALUES (5, Douglas, Comer);
INSERT INTO authors VALUES (6, Tom, Christiansen);
INSERT INTO authors VALUES (7, Nathan, Torkington);
INSERT INTO authors VALUES (8, Jeffrey, Zeldman);
INSERT INTO book_authors VALUES (1, 1);
INSERT INTO book_authors VALUES (1, 2);
INSERT INTO book_authors VALUES (1, 3);
INSERT INTO book_authors VALUES (2, 4);
INSERT INTO book_authors VALUES (3, 5);
INSERT INTO book_authors VALUES (4, 6);
INSERT INTO book_authors VALUES (4, 7);
INSERT INTO book_authors VALUES (5, 8);
TIP: See Appendix 1 for tips on removing the leading spaces when cutting and pasting
example code from POD-based documents.
Then use the following command to build a myapp.db SQLite database:
$ sqlite3 myapp.db < myapp01.sql

130

Catalyst::Manual::Tutorial::CatalystBasics

If you need to create the database more than once, you probably want to issue the
rm myapp.db command to delete the database before you use the sqlite3 myapp.db <
myapp01.sql command.
Once the myapp.db database file has been created and initialized, you can use the SQLite
command line environment to do a quick dump of the database contents:
$ sqlite3 myapp.db
SQLite version 3.2.2
Enter ".help" for instructions
sqlite> select * from books;
1|CCSP SNRS Exam Certification Guide|5
2|TCP/IP Illustrated, Volume 1|5
3|Internetworking with TCP/IP Vol.1|4
4|Perl Cookbook|5
5|Designing with Web Standards|5
sqlite> .q
$
Or:
$ sqlite3 myapp.db "select * from books"
1|CCSP SNRS Exam Certification Guide|5
2|TCP/IP Illustrated, Volume 1|5
3|Internetworking with TCP/IP Vol.1|4
4|Perl Cookbook|5
5|Designing with Web Standards|5
As with most other SQL tools, if you are using the full interactive environment you
need to terminate your SQL commands with a ; (its not required if you do a single SQL
statement on the command line). Use .q to exit from SQLite from the SQLite interactive
mode and return to your OS command prompt.

EDIT THE LIST OF CATALYST PLUGINS


One of the greatest benefits of Catalyst is that it has such a large library of plugins available. Plugins are used to seamlessly integrate existing Perl modules into the overall Catalyst
framework. In general, they do this by adding additional methods to the context object
(generally written as $c) that Catalyst passes to every component throughout the framework.
By default, Catalyst enables three plugins/flags:
-Debug Flag

Enables the Catalyst debug output you saw when we started the
script/myapp_server.pl development server earlier.
You can remove this
plugin when you place your application into production.

EDIT THE LIST OF CATALYST PLUGINS

131

As you may have noticed, -Debug is not a plugin, but a flag. Although most of the
items specified on the use Catalyst line of your application class will be plugins,
Catalyst supports a limited number of flag options (of these, -Debug is the most common). See the documentation for Catalyst.pm to get details on other flags (currently
-Engine, -Home, and -Log).
If you prefer, you can use the $c-&gt;debug method to enable debug messages.
Catalyst::Plugin::ConfigLoader

ConfigLoader provides an automatic way to load configurable parameters for your


application from a central YAML file (versus having the values hard-coded inside your
Perl modules). If you have not been exposed to YAML before, it is a human-readable
data serialization format that can be used to read (and write) values to/from text
files. We will see how to use this feature of Catalyst during the authentication and
authorization sections (Part 4 and Part 5).
Catalyst::Plugin::Static::Simple

Static::Simple provides an easy method of serving static content such as images


and CSS files under the development server.
To modify the list of plugins, edit lib/MyApp.pm (this file is generally referred to as your
application class) and delete the line with:
use Catalyst qw/-Debug ConfigLoader Static::Simple/;
Replace it with:
use Catalyst qw/
-Debug
ConfigLoader
Static::Simple
StackTrace
/;
This tells Catalyst to start using one new plugin:
Catalyst::Plugin::StackTrace

Adds a stack trace to the standard Catalyst debug screen (this is the screen Catalyst
sends to your browser when an error occurs).
Note: StackTrace output appears in your browser, not in the console window from
which youre running your application, which is where logging output usually goes.
Note that when specifying plugins on the use Catalyst line, you can omit Catalyst::Plugin:: from the name. Additionally, you can spread the plugin names across
multiple lines as shown here, or place them all on one (or more) lines as with the default
configuration.

132

Catalyst::Manual::Tutorial::CatalystBasics

TIP: You may see examples that include the Catalyst::Plugin::DefaultEnd plugins.
As of Catalyst 5.7000, DefaultEnd has been deprecated in favor of Catalyst::Action::RenderView (as the name of the package suggests, RenderView is not a plugin,
but an action). The purpose of both is essentially the same: forward processing to the view
to be rendered. Applications generated under 5.7000 should automatically use RenderView
and just work for most applications. For more information on RenderView and the various options for forwarding to your view logic, please refer to the Using RenderView for the
Default View section under CATALYST VIEWS below.

DATABASE ACCESS WITH DBIx::Class


Catalyst can be used with virtually any form of persistent datastore available via Perl.
For example, Catalyst::Model::DBI can be used to easily access databases through the
traditional Perl DBI interface. However, most Catalyst applications use some form of ORM
technology to automatically create and save model objects as they are used. Although Tony
Bowdens Class::DBI has been the traditional Perl ORM engine, Matt Trouts DBIx::Class
(abbreviated as DBIC) has rapidly emerged as the Perl-based ORM technology of choice.
Most new Catalyst applications rely on DBIC, as will this tutorial.
Note: See Catalyst::Model::CDBI for more information on using Catalyst with
Class::DBI.

Create a DBIC Schema File


DBIx::Class uses a schema file to load other classes that represent the tables in your database
(DBIC refers to these table objects as result sources; see DBIx::Class::ResultSource).
In this case, we want to load the model object for the books, book_authors, and authors
tables created in the previous step.
Create lib/MyAppDB.pm in your editor and insert:
package MyAppDB;
=head1 NAME
MyAppDB - DBIC Schema Class
=cut
# Our schema needs to inherit from DBIx::Class::Schema
use base qw/DBIx::Class::Schema/;
#
#
#
#
#

Need to load the DB Model classes here.


You can use this syntax if you want:
__PACKAGE__->load_classes(qw/Book BookAuthor Author/);
Also, if you simply want to load all of the classes in a directory
of the same name as your schema class (as we do here) you can use:

DATABASE ACCESS WITH DBIx::Class

133

#
__PACKAGE__->load_classes(qw//);
# But the variation below is more flexible in that it can be used to
# load from multiple namespaces.
__PACKAGE__->load_classes({
MyAppDB => [qw/Book BookAuthor Author/]
});
1;
Note: __PACKAGE__ is just a shorthand way of referencing the name of the package
where it is used. Therefore, in MyAppDB.pm, __PACKAGE__ is equivalent to MyAppDB.
Note: As with any Perl package, we need to end the last line with a statement that
evaluates to true. This is customarily done with 1 on a line by itself as shown above.

Create the DBIC Result Source Files


In this step, we create table classes (again, these are called a result source classes in
DBIC) that act as model objects for the books, book_authors, and authors tables in our
database.
First, create a directory to hold the class:
$ mkdir lib/MyAppDB
Then create lib/MyAppDB/Book.pm in your editor and enter:
package MyAppDB::Book;
use base qw/DBIx::Class/;
# Load required DBIC stuff
__PACKAGE__->load_components(qw/PK::Auto Core/);
# Set the table name
__PACKAGE__->table(books);
# Set columns in table
__PACKAGE__->add_columns(qw/id title rating/);
# Set the primary key for the table
__PACKAGE__->set_primary_key(qw/id/);
#
# Set relationships:
#
# has_many():
#
args:
#
1) Name of relationship, DBIC will create accessor with this name
#
2) Name of the model class referenced by this relationship

134

Catalyst::Manual::Tutorial::CatalystBasics

#
3) Column name in *foreign* table
__PACKAGE__->has_many(book_authors => MyAppDB::BookAuthor, book_id);
# many_to_many():
#
args:
#
1) Name of relationship, DBIC will create accessor with this name
#
2) Name of has_many() relationship this many_to_many() is shortcut
for
#
3) Name of belongs_to() relationship in model class of has_many()
above
#
You must already have the has_many() defined to use a many_to_many().
__PACKAGE__->many_to_many(authors => book_authors, author);

=head1 NAME
MyAppDB::Book - A model object representing a book.
=head1 DESCRIPTION
This is an object that represents a row in the books table of your application
database. It uses DBIx::Class (aka, DBIC) to do ORM.
For Catalyst, this is designed to be used through MyApp::Model::MyAppDB.
Offline utilities may wish to use this class directly.
=cut
1;
This defines both a has_many and a many_to_many relationship. The many_to_many
relationship is optional, but it makes it easier to map a book to its collection of authors. Without it, we would have to walk though the book_authors table as in $book&gt;book_authors-&gt;first-&gt;author-&gt;last_name (we will see examples on how
to use DBIC objects in your code soon, but note that because $book-&gt;book_authors can
return multiple authors, we have to use first to display a single author). many_to_many allows us to use the shorter $book-&gt;authors-&gt;first-&gt;last_name. Note that you
cannot define a many_to_many relationship without also having the has_many relationship
in place.
Next, create lib/MyAppDB/Author.pm in your editor and enter:
package MyAppDB::Author;

DATABASE ACCESS WITH DBIx::Class

135

use base qw/DBIx::Class/;


# Load required DBIC stuff
__PACKAGE__->load_components(qw/PK::Auto Core/);
# Set the table name
__PACKAGE__->table(authors);
# Set columns in table
__PACKAGE__->add_columns(qw/id first_name last_name/);
# Set the primary key for the table
__PACKAGE__->set_primary_key(qw/id/);
#
# Set relationships:
#
# has_many():
#
args:
#
1) Name of relationship, DBIC will create accessor with this name
#
2) Name of the model class referenced by this relationship
#
3) Column name in *foreign* table
__PACKAGE__->has_many(book_author => MyAppDB::BookAuthor, author_id);
# many_to_many():
#
args:
#
1) Name of relationship, DBIC will create accessor with this name
#
2) Name of has_many() relationship this many_to_many() is shortcut
for
#
3) Name of belongs_to() relationship in model class of has_many()
above
#
You must already have the has_many() defined to use a many_to_many().
__PACKAGE__->many_to_many(books => book_author, book);

=head1 NAME
MyAppDB::Author - A model object representing an author of a book (if a
book has
multiple authors, each will be represented be separate Author object).
=head1 DESCRIPTION
This is an object that represents a row in the authors table of your application

136
database.

Catalyst::Manual::Tutorial::CatalystBasics
It uses DBIx::Class (aka, DBIC) to do ORM.

For Catalyst, this is designed to be used through MyApp::Model::MyAppDB.


Offline utilities may wish to use this class directly.
=cut
1;
Finally, create lib/MyAppDB/BookAuthor.pm in your editor and enter:
package MyAppDB::BookAuthor;
use base qw/DBIx::Class/;
# Load required DBIC stuff
__PACKAGE__->load_components(qw/PK::Auto Core/);
# Set the table name
__PACKAGE__->table(book_authors);
# Set columns in table
__PACKAGE__->add_columns(qw/book_id author_id/);
# Set the primary key for the table
__PACKAGE__->set_primary_key(qw/book_id author_id/);
#
# Set relationships:
#
# belongs_to():
#
args:
#
1) Name of relationship, DBIC will create accessor with this name
#
2) Name of the model class referenced by this relationship
#
3) Column name in *this* table
__PACKAGE__->belongs_to(book => MyAppDB::Book, book_id);
# belongs_to():
#
args:
#
1) Name of relationship, DBIC will create accessor with this name
#
2) Name of the model class referenced by this relationship
#
3) Column name in *this* table
__PACKAGE__->belongs_to(author => MyAppDB::Author, author_id);

=head1 NAME

DATABASE ACCESS WITH DBIx::Class

137

MyAppDB::BookAuthor - A model object representing the JOIN between an author and


a book.
=head1 DESCRIPTION
This is an object that represents a row in the book_authors table of your
application database.

It uses DBIx::Class (aka, DBIC) to do ORM.

You probably wont need to use this class directly -- it will be automatically
used by DBIC where joins are needed.
For Catalyst, this is designed to be used through MyApp::Model::MyAppDB.
Offline utilities may wish to use this class directly.
=cut
1;
Note: This sample application uses a plural form for the database tables (e.g., books
and authors) and a singular form for the model objects (e.g., Book and Author); however,
Catalyst places no restrictions on the naming conventions you wish to use.

Use Catalyst::Model::DBIC::Schema To Load The Model Class


When Catalyst::Model::DBIC::Schema is in use, Catalyst essentially reads an existing copy
of your database model and creates a new set of objects under MyApp::Model for use inside
of Catalyst.
Note: With Catalyst::Model::DBIC::Schema you essentially end up with two sets of
model classes (only one of which you write... the other set is created automatically in memory when your Catalyst application initializes). For this tutorial application, the important
points to remember are: you write the result source files in MyAppDB, but within Catalyst
you use the automatically created model classes in MyApp::Model.
Use the Catalyst::Helper::Model::DBIC::Schema helper script to create the model class
that loads up the model we created in the previous step:
$ script/myapp_create.pl model MyAppDB DBIC::Schema MyAppDB dbi:SQLite:myapp.db { AutoCommit => 1 }
exists "/root/dev/MyApp/script/../lib/MyApp/Model"
exists "/root/dev/MyApp/script/../t"
created "/root/dev/MyApp/script/../lib/MyApp/Model/MyAppDB.pm"
created "/root/dev/MyApp/script/../t/model_MyAppDB.t"

138

Catalyst::Manual::Tutorial::CatalystBasics

Where the first MyAppDB is the name of the class to be created by the helper in
lib/MyApp/Model and the second MyAppDB is the name of existing schema file we created (in
lib/MyAppDB.pm). You can see that the helper creates a model file under lib/MyApp/Model
(Catalyst has a separate directory under lib/MyApp for each of the three parts of MVC:
Model, View, and Controller [although older Catalyst applications often use the directories
M, V, and C]).

CREATE A CATALYST CONTROLLER


Controllers are where you write methods that interact with user input--typically, controller
methods respond to GET and POST messages from the users web browser.
Use the Catalyst create script to add a controller for book-related actions:
$ script/myapp_create.pl controller Books
exists "/root/dev/MyApp/script/../lib/MyApp/Controller"
exists "/root/dev/MyApp/script/../t"
created "/root/dev/MyApp/script/../lib/MyApp/Controller/Books.pm"
created "/root/dev/MyApp/script/../t/controller_Books.t"
Then edit lib/MyApp/Controller/Books.pm and add the following method to the controller:
=head2 list
Fetch all book objects and pass to books/list.tt2 in stash to be displayed
=cut
sub list : Local {
# Retrieve the usual perl OO $self for this object. $c is the Catalyst
# Context thats used to glue together the various components
# that make up the application
my ($self, $c) = @_;
# Retrieve all of the book records as book model objects and store in the
# stash where they can be accessed by the TT template
$c->stash->{books} = [$c->model(MyAppDB::Book)->all];
# Set the TT template to use. You will almost always want to do this
# in your action methods (action methods respond to user input in
# your controllers).

CATALYST VIEWS

139

$c->stash->{template} = books/list.tt2;
}
Note: Programmers experienced with object-oriented Perl should recognize $self as a
reference to the object where this method was called. On the other hand, $c will be new
to many Perl programmers who have not used Catalyst before (its sometimes written as
$context). The Context object is automatically passed to all Catalyst components. It is
used to pass information between components and provide access to Catalyst and plugin
functionality.
TIP: You may see the $c-&gt;model(MyAppDB::Book) used above written as $c&gt;model(MyAppDB)-&gt;resultset(Book). The two are equivalent.
Note: Catalyst actions are regular Perl methods, but they make use of Nicholas Clarks
attributes module (thats the : Local next to the sub list in the code above) to provide
additional information to the Catalyst dispatcher logic.

CATALYST VIEWS
Views are where you render output, typically for display in the users web browser,
but also possibly using other display output-generation systems.
As with virtually every aspect of Catalyst, options abound when it comes to the specific view
technology you adopt inside your application.
However, most Catalyst applications use the Template Toolkit, known as TT (for more information on TT, see
http://www.template-toolkit.org53 ). Other popular view technologies include Mason
(http://www.masonhq.com54 and http://www.masonbook.com55 ) and HTML::Template
(http://html-template.sourceforge.net56 ).

Create a Catalyst View Using TTSite


When using TT for the Catalyst view, there are two main helper scripts:
Catalyst::Helper::View::TT
Catalyst::Helper::View::TTSite

Both are similar, but TT merely creates the lib/MyApp/View/TT.pm file and leaves the
creation of any hierarchical template organization entirely up to you. (It also creates a
t/view_TT.t file for testing; test cases will be discussed in Part 7). The TTSite helper
creates a modular and hierarchical view layout with separate Template Toolkit (TT) files
for common header and footer information, configuration values, a CSS stylesheet, and
more.
53

http://www.template-toolkit.org
http://www.masonhq.com
55
http://www.masonbook.com
56
http://html-template.sourceforge.net
54

140

Catalyst::Manual::Tutorial::CatalystBasics

Enter the following command to enable the TTSite style of view rendering for this
tutorial:
$ script/myapp_create.pl view TT TTSite
exists "/root/dev/MyApp/script/../lib/MyApp/View"
exists "/root/dev/MyApp/script/../t"
created "/root/dev/MyApp/script/../lib/MyApp/View/TT.pm"
created "/root/dev/MyApp/script/../root/lib"
...
created "/root/dev/MyApp/script/../root/src/ttsite.css"
This puts a number of files in the root/lib and root/src directories that can be used to
customize the look and feel of your application. Also take a look at lib/MyApp/View/TT.pm
for config values set by the TTSite helper.
TIP: Note that TTSite does one thing that could confuse people who are used to
the normal TT Catalyst view: it redefines the Catalyst context object in templates from
its usual c to Catalyst. When looking at other Catalyst examples, remember that they
almost always use c. Note that Catalyst and TT do not complain when you use the wrong
name to access the context object...TT simply outputs blanks for that bogus logic (see next
tip to change this behavior with TT DEBUG options). Finally, be aware that this change
in name only applies to how the context object is accessed inside your TT templates;
your controllers will continue to use $c (or whatever name you use when fetching the
reference from @_ inside your methods). (You can change back to the default behavior be
removing the CATALYST_VAR line from lib/MyApp/View/TT.pm, but you will also have to
edit root/lib/config/main and root/lib/config/url. If you do this, be careful not to
have a collision between your own c variable and the Catalyst c variable.)
TIP: When troubleshooting TT it can be helpful to enable variable DEBUG options. You
can do this in a Catalyst environment by adding a DEBUG line to the __PACKAGE__-config>
declaration in lib/MyApp/View/TT.pm:
__PACKAGE__->config({
CATALYST_VAR => Catalyst,
...
DEBUG
=> undef,
...
});
There are a variety of options you can use, such as undef, all, service, context,
parser, provider, and service. See Template::Constants for more information (remove
the DEBUG_ portion of the name shown in the TT docs and convert to lower case for use
inside Catalyst).
NOTE: Please be sure to disable TT debug options before continuing the tutorial (especially the undef option -- leaving this enabled will conflict with several of the conventions
used by this tutorial and TTSite to leave some variables undefined on purpose).

CATALYST VIEWS

141

Using RenderView for the Default View


Once your controller logic has processed the request from a user, it forwards processing to
your view in order to generate the appropriate response output. Catalyst v5.7000 ships with
a new mechanism, Catalyst::Action::RenderView, that automatically performs this operation. If you look in lib/MyApp/Controller/Root.pm, you should see the empty definition
for the sub end method:
sub end : ActionClass(RenderView) {}
The following bullet points provide a quick overview of the RenderView process:
Root.pm is designed to hold application-wide logic.
At the end of a given user request, Catalyst will call the most specific end method
thats appropriate. For example, if the controller for a request has an end method
defined, it will be called. However, if the controller does not define a controller-specific
end method, the global end method in Root.pm will be called.
Because the definition includes an ActionClass attribute, the Catalyst::Action::RenderView logic will be executed after any code inside the definition of
sub end is run. See Catalyst::Manual::Actions for more information on ActionClass.
Because sub end is empty, this effectively just runs the default logic in RenderView.
However, you can easily extend the RenderView logic by adding your own code inside
the empty method body ({}) created by the Catalyst Helpers when we first ran the
catalyst.pl to initialize our application. See Catalyst::Action::RenderView for more
detailed information on how to extended RenderView in sub end.

The History Leading Up To RenderView


Although RenderView strikes a nice balance between default behavior and easy extensibility,
it is a new feature that wont appear in most existing Catalyst examples. This section
provides some brief background on the evolution of default view rendering logic with an eye
to how they can be migrated to RenderView:
Private end Action in Application Class

Older Catalyst-related documents often suggest that you add a private end action to your application class (MyApp.pm) or Root.pm (MyApp/Controller/Root.pm).
These examples should be easily converted to RenderView by simply adding the
attribute :ActionClass(RenderView) to the sub end definition. If end sub
is defined in your application class (MyApp.pm), you should also migrate it to
MyApp/Controller/Root.pm.
Catalyst::Plugin::DefaultEnd

142

Catalyst::Manual::Tutorial::CatalystBasics
DefaultEnd represented the next step in passing processing from your controller to
your view. It has the advantage of only requiring that DefaultEnd be added to the
list of plugins in lib/MyApp.pm. It also allowed you to add dump info=1 (precede
with ? or & depending on where it is in the URL) to force the debug screen at the
end of the Catalyst request processing cycle. However, it was more difficult to extend
than the RenderView mechanism, and is now deprecated.
Catalyst::Action::RenderView

As discussed above, the current recommended approach to handling your view logic relies on Catalyst::Action::RenderView. Although similar in first appearance to the private end action approach, it utilizes Catalysts ActionClass mechanism to provide
both automatic default behavior (you dont have to include a plugin as with DefaultEnd) and easy extensibility. As with DefaultEnd, it allows you to add dump info=1
(precede with ? or & depending on where it is in the URL) to force the debug
screen at the end of the Catalyst request processing cycle.
It is recommended that all Catalyst applications use or migrate to the RenderView
approach.

Globally Customize Every View


When using TTSite, files in the subdirectories of root/lib can be used to make changes
that will appear in every view. For example, to display optional status and error messages
in every view, edit root/lib/site/layout, updating it to match the following (the two
HTML span elements are new):
<div id="header">[% PROCESS site/header %]</div>
<div id="content">
<span class="message">[% status_msg %]</span>
<span class="error">[% error_msg %]</span>
[% content %]
</div>
<div id="footer">[% PROCESS site/footer %]</div>
If we set either message in the Catalyst stash (e.g., $c-&gt;stash-&gt;{status_msg}
= Request was successful!) it will be displayed whenever any view used by that
request is rendered. The message and error CSS styles are automatically defined in
root/src/ttsite.css and can be customized to suit your needs.
Note: The Catalyst stash only lasts for a single HTTP request. If you need to retain
information across requests you can use Catalyst::Plugin::Session (we will use Catalyst
sessions in the Authentication part of the tutorial).

CATALYST VIEWS

143

Create a TT Template Page


To add a new page of content to the TTSite view hierarchy, just create a new .tt2 file in
root/src. Only include HTML markup that goes inside the HTML <body> and </body>
tags, TTSite will use the contents of root/lib/site to add the top and bottom.
First create a directory for book-related TT templates:
$ mkdir root/src/books
Then create root/src/books/list.tt2 in your editor and enter:
[% # This is a TT comment. The - at the end "chomps" the newline. You
wont -%]
[% # see this "chomping" in your browser because HTML ignores blank lines,
but -%]
[% # it WILL eliminate a blank line if you view the HTML source. Its
purely
-%]
[%- # optional, but both the beginning and the ending TT tags support
chomping. -%]
[% # Provide a title to root/lib/site/header -%]
[% META title = Book List -%]
<table>
<tr><th>Title</th><th>Rating</th><th>Author(s)</th></tr>
[% # Display each book in a table row %]
[% FOREACH book IN books -%]
<tr>
<td>[% book.title %]</td>
<td>[% book.rating %]</td>
<td>
[% # First initialize a TT variable to hold a list. Then use a TT
FOREACH -%]
[% # loop in side effect notation to load just the last names of
the
-%]
[% # authors into the list. Note that the push TT vmethod does not
-%]
[% # a value, so nothing will be printed here. But, if you have
something -%]
[% # in TT that does return a method and you dont want it printed,
you
-%]
[% # can: 1) assign it to a bogus value, or 2) use the CALL keyword
to
-%]
[% # call it and discard the return value.
%]
[% tt_authors = [ ];

144

Catalyst::Manual::Tutorial::CatalystBasics

tt_authors.push(author.last_name) FOREACH author = book.authors %]


[% # Now use a TT virtual method to display the author count in
parens
-%]
([% tt_authors.size %])
[% # Use another TT vmethod to join & print the names & comma separators
-%]
[% tt_authors.join(, ) %]
</td>
</tr>
[% END -%]
</table>
As indicated by the inline comments above, the META title line uses TTs META
feature to provide a title to root/lib/site/header. Meanwhile, the outer FOREACH loop
iterates through each book model object and prints the title and rating fields. An inner
FOREACH loop prints the last name of each author in a comma-separated list within a single
table cell.
If you are new to TT, the [% and %] tags are used to delimit TT code. TT supports a
wide variety of directives for calling other files, looping, conditional logic, etc. In general,
TT simplifies the usual range of Perl operators down to the single dot (.) operator. This
applies to operations as diverse as method calls, hash lookups, and list index values (see
http://www.template-toolkit.org/docs/default/Manual/Variables.html57 for details and examples). In addition to the usual Template module Pod documentation, you can access the
TT manual at http://www.template-toolkit.org/docs/default/58 .
NOTE: The TTSite helper creates several TT files using an extension of .tt2. Most
other Catalyst and TT examples use an extension of .tt. You can use either extension (or
no extension at all) with TTSite and TT, just be sure to use the appropriate extension for
both the file itself and the $c-&gt;stash-&gt;{template} = ... line in your controller.
This document will use .tt2 for consistency with the files already created by the TTSite
helper.

RUN THE APPLICATION


First, lets enable an environment variable option that causes DBIx::Class to dump the
SQL statements its using to access the database (this option can provide extremely helpful
troubleshooting information):
$ export DBIC_TRACE=1
NOTE: You can also use the older export DBIX_CLASS_STORAGE_DBI_DEBUG=1, but
thats a lot more to type.
57
58

http://www.template-toolkit.org/docs/default/Manual/Variables.html
http://www.template-toolkit.org/docs/default/

RUN THE APPLICATION

145

This assumes you are using BASH as your shell -- adjust accordingly if you are using a
different shell (for example, under tcsh, use setenv DBIX_CLASS_STORAGE_DBI_DEBUG 1).
NOTE: You can also set this in your code using $class-&gt;storage-&gt;debug(1);.
See DBIx::Class::Manual::Troubleshooting for details (including options to log to file
instead of displaying to the Catalyst development server log).
Then run the Catalyst demo server script:
$ script/myapp_server.pl
Your development server log output should display something like:
$ script/myapp_server.pl
[debug] Debug messages enabled
[debug] Loaded plugins:
.---------------------------------------------------------------------------.
| Catalyst::Plugin::ConfigLoader 0.13
| Catalyst::Plugin::StackTrace 0.06
| Catalyst::Plugin::Static::Simple 0.14
---------------------------------------------------------------------------
[debug] Loaded dispatcher "Catalyst::Dispatcher"
[debug] Loaded engine "Catalyst::Engine::HTTP"
[debug] Found home "/home/me/MyApp"
[debug] Loaded Config "/home/me/myapp.yml"
[debug] Loaded components:
.-----------------------------------------------------------------+---------.
| Class
| Type
|
+-----------------------------------------------------------------+---------+
| MyApp::Controller::Books
| instance |
| MyApp::Controller::Root
| instance |
| MyApp::Model::MyAppDB
| instance |
| MyApp::Model::MyAppDB::Author
| class
|
| MyApp::Model::MyAppDB::Book
| class
|
| MyApp::Model::MyAppDB::BookAuthor
| class
|
| MyApp::View::TT
| in-

|
|
|

146

Catalyst::Manual::Tutorial::CatalystBasics

stance |
-----------------------------------------------------------------+---------
[debug] Loaded Private actions:
.----------------------+--------------------------------------+-------------.
| Private
| Class
| Method
|
+----------------------+--------------------------------------+-------------+
| /default
| MyApp::Controller::Root
| default
|
| /end
| MyApp::Controller::Root
| end
|
| /books/index
| MyApp::Controller::Books
| index
|
| /books/list
| MyApp::Controller::Books
| list
|
----------------------+--------------------------------------+-------------
[debug] Loaded Path actions:
.-------------------------------------+-------------------------------------.
| Path
| Private
+-------------------------------------+-------------------------------------+
| /books/list
| /books/list
|
-------------------------------------+-------------------------------------
[info] MyApp powered by Catalyst 5.7002
You can connect to your server at http://localhost:3000
Some things you should note in the output above:
Catalyst::Model::DBIC::Schema took our MyAppDB::Book and made it
MyApp::Model::MyAppDB::Book (and similar actions were performed on MyAppDB::Author and MyAppDB::BookAuthor).
The list action in our Books controller showed up with a path of /books/list.

USING THE DEFAULT TEMPLATE NAME

147

Point your browser to http://localhost:300059 and you should still get the Catalyst
welcome page.
Next, to view the book list, change the URL in your browser to
http://localhost:3000/books/list60 . You should get a list of the five books loaded by
the myapp01.sql script above, with TTSite providing the formatting for the very simple
output we generated in our template. The count and space-separated list of author last
names appear on the end of each row.
Also notice in the output of the script/myapp_server.pl that DBIC used the following
SQL to retrieve the data:
SELECT me.id, me.title, me.rating FROM books me
Along with a list of the following commands to retrieve the authors for each book (the
lines have been word wrapped here to improve legibility):
SELECT author.id, author.first_name, author.last_name
FROM book_authors me
JOIN authors author ON ( author.id = me.author_id )
WHERE ( me.book_id = ? ): 1
You should see 5 such lines of debug output as DBIC fetches the author information for
each book.

USING THE DEFAULT TEMPLATE NAME


By default, Catalyst::View::TT will look for a template that uses the same name as
your controller action, allowing you to save the step of manually specifying the template
name in each action. For example, this would allow us to remove the $c-&gt;stash&gt;{template} = books/list.tt2; line of our list action in the Books controller.
Open lib/MyApp/Controller/Books.pm in your editor and comment out this line to match
the following (only the $c-&gt;stash-&gt;{template} line has changed):
=head2 list
Fetch all book objects and pass to books/list.tt2 in stash to be displayed
=cut
sub list : Local {
# Retrieve the usual perl OO $self for this object. $c is the Catalyst
# Context thats used to glue together the various components
# that make up the application
my ($self, $c) = @_;
59
60

http://localhost:3000
http://localhost:3000/books/list

148

Catalyst::Manual::Tutorial::CatalystBasics

# Retrieve all of the book records as book model objects and store in the
# stash where they can be accessed by the TT template
$c->stash->{books} = [$c->model(MyAppDB::Book)->all];
# Set the TT template to use. You will almost always want to do this
# in your action methods (actions methods respond to user input in
# your controllers).
#$c->stash->{template} = books/list.tt2;
}
Catalyst::View::TT defaults to looking for a template with no extension. In our case,
we need to override this to look for an extension of .tt2. Open lib/MyApp/View/TT.pm
and add the TEMPLATE_EXTENSION definition as follows:
__PACKAGE__->config({
CATALYST_VAR => Catalyst,
INCLUDE_PATH => [
MyApp->path_to( root, src ),
MyApp->path_to( root, lib )
],
PRE_PROCESS => config/main,
WRAPPER
=> site/wrapper,
ERROR
=> error.tt2,
TIMER
=> 0,
TEMPLATE_EXTENSION => .tt2,
});
You should now be able to restart the development server as per the previous section
and access the http://localhost:3000/books/list61 as before.
NOTE: Please note that if you use the default template technique, you will not be able
to use either the $c-&gt;forward or the $c-&gt;detach mechanisms (these are discussed
in Part 2 and Part 8 of the Tutorial).

RETURN TO A MANUALLY-SPECIFIED TEMPLATE


In order to be able to use $c-&gt;forward and $c-&gt;detach later in the tutorial, you
should remove the comment from the statement in sub list:
$c->stash->{template} = books/list.tt2;
Then delete the TEMPLATE_EXTENSION line in lib/MyApp/View/TT.pm.
You should then be able to restart the development server
61

http://localhost:3000/books/list

and

access

AUTHOR

149

http://localhost:3000/books/list62 in the same manner as with earlier sections.

AUTHOR
Kennedy Clark, hkclark@gmail.com
Please
report
any
errors,
issues
or
suggestions
to
the
author.
The most recent version of the Catalyst Tutorial can be
found
at
http://dev.catalyst.perl.org/repos/Catalyst/trunk/CatalystRuntime/lib/Catalyst/Manual/Tutorial/63 .
Copyright
2006,
Kennedy
Clark,
under
Creative
Commons
License
(http://creativecommons.org/licenses/by-nc-sa/2.5/64 ).

62

http://localhost:3000/books/list
http://dev.catalyst.perl.org/repos/Catalyst/trunk/Catalyst-Runtime/lib/Catalyst/Manual/Tutorial/
64
http://creativecommons.org/licenses/by-nc-sa/2.5/
63

150

Catalyst::Manual::Tutorial::CatalystBasics

Catalyst::Manual::Tutorial::BasicCRUD
- Catalyst Tutorial - Part 3: Basic
CRUD
This part of the tutorial builds on the fairly primitive application created in Part 2 to add
basic support for Create, Read, Update, and Delete (CRUD) of Book objects. Note that
the list function in Part 2 already implements the Read portion of CRUD (although Read
normally refers to reading a single object; you could implement full read functionality using
the techniques introduced below). This section will focus on the Create and Delete aspects
of CRUD. More advanced capabilities, including full Update functionality, will be addressed
in Part 8.
You can checkout the source code for this example from the catalyst subversion repository as per the instructions in Catalyst::Manual::Tutorial::Intro

OVERVIEW
This is Part 3 of 9 for the Catalyst tutorial.
Tutorial Overview
1. Introduction
2. Catalyst Basics
3. Basic CRUD
4. Authentication
5. Authorization
6. Debugging
7. Testing
8. AdvancedCRUD
9. Appendices
151

152

Catalyst::Manual::Tutorial::BasicCRUD

FORMLESS SUBMISSION
Our initial attempt at object creation will utilize the URL arguments feature of Catalyst
(we will employ the more common form-based submission in the sections that follow).

Include a Create Action in the Books Controller


Edit lib/MyApp/Controller/Books.pm and enter the following method:
=head2 url_create
Create a book with the supplied title, rating, and author
=cut
sub url_create : Local {
# In addition to self & context, get the title, rating, &
# author_id args from the URL. Note that Catalyst automatically
# puts extra information after the "/<controller_name>/<action_name/"
# into @_
my ($self, $c, $title, $rating, $author_id) = @_;
# Call create() on the book model object. Pass the table
# columns/field values we want to set as hash values
my $book = $c->model(MyAppDB::Book)->create({
title => $title,
rating => $rating
});
# Add a record to the join table for this book, mapping to
# appropriate author
$book->add_to_book_authors({author_id => $author_id});
# Note: Above is a shortcut for this:
# $book->create_related(book_authors, {author_id => $author_id});
# Assign the Book object to the stash for display in the view
$c->stash->{book} = $book;
# This is a hack to disable XSUB processing in Data::Dumper
# (its used in the view). This is a work-around for a bug in

FORMLESS SUBMISSION

153

# the interaction of some versions or Perl, Data::Dumper & DBIC.


# You wont need this if you arent using Data::Dumper (or if
# you are running DBIC 0.06001 or greater), but adding it doesnt
# hurt anything either.
$Data::Dumper::Useperl = 1;
# Set the TT template to use
$c->stash->{template} = books/create_done.tt2;
}
Notice that Catalyst takes extra slash-separated information from the URL and passes
it as arguments in @_. The url_create action then uses a simple call to the DBIC create method to add the requested information to the database (with a separate call to
add_to_book_authors to update the join table). As do virtually all controller methods (at
least the ones that directly handle user input), it then sets the template that should handle
this request.

Include a Template for the url_create Action:


Edit root/src/books/create_done.tt2 and then enter:
[% # Use the TT Dumper plugin to Data::Dumper variables to the browser
%]
[% # Not a good idea for production use, though. :-) Indent=1 is
%]
[% # optional, but prevents "massive indenting" of deeply nested objects %]
[% USE Dumper(Indent=1) -%]
[%
%]
[%
%]
[%
%]
[%
%]
[%

# Set the page title.

META can go back and set values in templates -

# that have been processed before this template (here its for

# root/lib/site/html and root/lib/site/header).

Note that META on

# simple strings (e.g., no variable interpolation).

META title = Book Created %]

[% # Output information about the record that was added.


-%]
<p>Added book [% book.title %]
[% # Output the last name of the first author.
-%]

First title.

This is complicated by an

154

Catalyst::Manual::Tutorial::BasicCRUD

[% # issue in TT 2.15 where blessed hash objects are not handled right.
-%]
[% # First, fetch book.authors from the DB once.
%]
[% authors = book.authors %]
[% # Now use IF statements to test if authors.first is "working". If so,
-%]
[% # we use it. Otherwise we use a hack that seems to keep TT 2.15 happy.
-%]
by [% authors.first.last_name IF authors.first;
authors.list.first.value.last_name IF ! authors.first %]

[% # Output the rating for the book that was added -%]
with a rating of [% book.rating %].</p>
[% # Provide a link back to the list page
%]
[% # uri_for() builds a full URI; e.g., http://localhost:3000/books/
list -%]
<p><a href="[% Catalyst.uri_for(/books/list) %]">Return to list</a></p>
[% # Try out the TT Dumper (for development only!) -%]
<pre>
Dump of the book variable:
[% Dumper.dump(book) %]
</pre>
The TT USE directive allows access to a variety of plugin modules (TT plugins, that
is, not Catalyst plugins) to add extra functionality to the base TT capabilities. Here, the
plugin allows Data::Dumper pretty printing of objects and variables. Other than that,
the rest of the code should be familiar from the examples in Part 2.
IMPORTANT NOTE As mentioned earlier, the MyApp::View::TT.pm view class
created by TTSite redefines the name used to access the Catalyst context object in TT
templates from the usual c to Catalyst.

Try the url_create Feature


If the application is still running from before, use Ctrl-C to kill it. Then restart the server:
$ script/myapp_server.pl
Note that new path for /books/url_create appears in the startup debug output.
TIP: You can use script/myapp_server.pl -r to have the development server autodetect changed files and reload itself (if your browser acts odd, you should also try throwing
in a -k). If you make changes to the TT templates only, you do not need to reload the

MANUALLY BUILDING A CREATE FORM

155

development server (only changes to compiled code such as Controller and Model .pm files
require a reload).
Next, use your browser to enter the following URL:
http://localhost:3000/books/url_create/TCPIP_Illustrated_Vol-2/5/4
Your browser should display Added book TCPIP Illustrated Vol-2 by Stevens with
a rating of 5. along with a dump of the new book model object. You should also see the
following DBIC debug messages displayed in the development server log messages:
INSERT INTO books (rating, title) VALUES (?, ?): 5,
TCPIP_Illustrated_Vol-2
INSERT INTO book_authors (author_id, book_id) VALUES (?, ?): 4, 6
SELECT author.id, author.first_name, author.last_name
FROM book_authors me JOIN authors author
ON ( author.id = me.author_id ) WHERE ( me.book_id = ? ): 6
The INSERT statements are obviously adding the book and linking it to the existing
record for Richard Stevens. The SELECT statement results from DBIC automatically fetching
the book for the Dumper.dump(book).
If you then click the Return to list link, you should find that there are now six books
shown (if necessary, Shift-Reload your browser at the /books/list page).
Then add 2 more copies of the same book so that we have some extras for our delete
logic that will be coming up soon. Enter the same URL above two more times (or refresh
your browser twice if it still contains this URL):
http://localhost:3000/books/url_create/TCPIP_Illustrated_Vol-2/5/4
You should be able to click Return to list and now see 3 copies of TCP Illustrated Vol2.

MANUALLY BUILDING A CREATE FORM


Although the url_create action in the previous step does begin to reveal the power and
flexibility of both Catalyst and DBIC, its obviously not a very realistic example of how
users should be expected to enter data. This section begins to address that concern.

Add Method to Display The Form


Edit lib/MyApp/Controller/Books.pm and add the following method:
=head2 form_create
Display form to collect information for book to create
=cut
sub form_create : Local {

156

Catalyst::Manual::Tutorial::BasicCRUD
my ($self, $c) = @_;
# Set the TT template to use
$c->stash->{template} = books/form_create.tt2;

}
This action simply invokes a view containing a book creation form.

Add a Template for the Form


Open root/src/books/form_create.tt2 in your editor and enter:
[% META title = Manual Form Book Create -%]
<form method="post" action="[% Catalyst.uri_for(form_create_do) %]">
<table>
<tr><td>Title:</td><td><input type="text" name="title"></td></tr>
<tr><td>Rating:</td><td><input type="text" name="rating"></td></tr>
<tr><td>Author ID:</td><td><input type="text" name="author_id"></td></tr>
</table>
<input type="submit" name="Submit" value="Submit">
</form>
Note that we have specified the target of the form data as form_create_do, the method
created in the section that follows.

Add a Method to Process Form Values and Update Database


Edit lib/MyApp/Controller/Books.pm and add the following method to save the form
information to the database:
=head2 form_create_do
Take information from form and add to database
=cut
sub form_create_do : Local {
my ($self, $c) = @_;
# Retrieve the values from the form
my $title
= $c->request->params->{title}
|| N/A;
my $rating
= $c->request->params->{rating}
|| N/A;
my $author_id = $c->request->params->{author_id} || 1;
# Create the book

A SIMPLE DELETE FEATURE

157

my $book = $c->model(MyAppDB::Book)->create({
title
=> $title,
rating => $rating,
});
# Handle relationship with author
$book->add_to_book_authors({author_id => $author_id});
# Store new model object in stash
$c->stash->{book} = $book;
# Avoid Data::Dumper issue mentioned earlier
# You can probably omit this
$Data::Dumper::Useperl = 1;
# Set the TT template to use
$c->stash->{template} = books/create_done.tt2;
}

Test Out The Form


If the application is still running from before, use Ctrl-C to kill it. Then restart the server:
$ script/myapp_server.pl
Point your browser to http://localhost:3000/books/form create65 and enter TCP/IP
Illustrated, Vol 3 for the title, a rating of 5, and an author ID of 4. You should then be
forwarded to the same create_done.tt2 template seen in earlier examples. Finally, click
Return to list to view the full list of books.
Note: Having the user enter the primary key ID for the author is obviously crude; we
will address this concern with a drop-down list in Part 8.

A SIMPLE DELETE FEATURE


Turning our attention to the delete portion of CRUD, this section illustrates some basic
techniques that can be used to remove information from the database.

Include a Delete Link in the List


Edit root/src/books/list.tt2 and update it to the following (two sections have changed:
1) the additional <th>Links</th> table header, and 2) the four lines for the Delete link
near the bottom).
65

http://localhost:3000/books/form_create

158

Catalyst::Manual::Tutorial::BasicCRUD

[% # This is a TT comment. The - at the end "chomps" the newline. You


wont -%]
[% # see this "chomping" in your browser because HTML ignores blank lines,
but -%]
[% # it WILL eliminate a blank line if you view the HTML source. Its
purely
-%]
[%- # optional, but both the beginning and the ending TT tags support
chomping. -%]
[% # Provide a title to root/lib/site/header -%]
[% META title = Book List -%]
<table>
<tr><th>Title</th><th>Rating</th><th>Author(s)</th><th>Links</th></tr>
[% # Display each book in a table row %]
[% FOREACH book IN books -%]
<tr>
<td>[% book.title %]</td>
<td>[% book.rating %]</td>
<td>
[% # First initialize a TT variable to hold a list. Then use a TT
FOREACH -%]
[% # loop in side effect notation to load just the last names of
the
-%]
[% # authors into the list. Note that the push TT vmethod does not
-%]
[% # a value, so nothing will be printed here. But, if you have
something -%]
[% # in TT that does return a method and you dont want it printed,
you
-%]
[% # can: 1) assign it to a bogus value, or 2) use the CALL keyword
to
-%]
[% # call it and discard the return value.
%]
[% tt_authors = [ ];
tt_authors.push(author.last_name) FOREACH author = book.authors %]
[% # Now use a TT virtual method to display the author count in
parens
-%]
([% tt_authors.size %])
[% # Use another TT vmethod to join & print the names & comma separators
-%]
[% tt_authors.join(, ) %]
</td>
<td>

A SIMPLE DELETE FEATURE

159

[% # Add a link to delete a book %]


<a href="[% Catalyst.uri_for(delete/) _ book.id %]">Delete</a>
</td>
</tr>
[% END -%]
</table>
The additional code is obviously designed to add a new column to the right side of
the table with a Delete button (for simplicity, links will be used instead of full HTML
buttons).

Add a Delete Action to the Controller


Open lib/MyApp/Controller/Books.pm in your editor and add the following method:
=head2 delete
Delete a book
=cut
sub delete : Local {
# $id = primary key of book to delete
my ($self, $c, $id) = @_;
# Search for the book and then delete it
$c->model(MyAppDB::Book)->search({id => $id})->delete_all;
# Set a status message to be displayed at the top of the view
$c->stash->{status_msg} = "Book deleted.";
# Forward to the list action/method in this controller
$c->forward(list);
}
This method first deletes the book with the specified primary key ID. However, it also
removes the corresponding entry from the book_authors table. Note that delete_all
was used instead of delete: whereas delete_all also removes the join table entries in
book_authors, delete does not (only use delete_all if you really need the cascading
deletes... otherwise you are wasting resources).
Then, rather than forwarding to a delete done page as we did with the earlier create
example, it simply sets the status_msg to display a notification to the user as the normal
list view is rendered.
The delete action uses the context forward method to return the user to the book
list. The detach method could have also been used. Whereas forward returns to the

160

Catalyst::Manual::Tutorial::BasicCRUD

original action once it is completed, detach does not return. Other than that, the two are
equivalent.

Try the Delete Feature


If the application is still running from before, use Ctrl-C to kill it. Then restart the server:
$ script/myapp_server.pl
Then point your browser to http://localhost:3000/books/list66 and click the Delete
link next to the first TCPIP Illustrated Vol-2. A green Book deleted status message
should display at the top of the page, along with a list of the eight remaining books.

Fixing a Dangerous URL


Note the URL in your browser once you have performed the deletetion in the prior step -it is still referencing the delete action:
http://localhost:3000/books/delete/6
What if the user were to press reload with this URL still active? In this case the
redundant delete is harmless, but in other cases this could clearly be extremely dangerous.
We can improve the logic by converting to a redirect. Unlike $c-&gt;forward(list))
or $c-&gt;detach(list)) that perform a server-side alteration in the flow of processing,
a redirect is a client-side mechanism that causes the brower to issue an entirely new request.
As a result, the URL in the browser is updated to match the destination of the redirection
URL.
To convert the forward used in the previous section to a redirect, open
lib/MyApp/Controller/Books.pm and edit the existing sub delete method to match:
=head2 delete
Delete a book
=cut
sub delete : Local {
# $id = primary key of book to delete
my ($self, $c, $id) = @_;
# Search for the book and then delete it
$c->model(MyAppDB::Book)->search({id => $id})->delete_all;
# Set a status message to be displayed at the top of the view
$c->stash->{status_msg} = "Book deleted.";
66

http://localhost:3000/books/list

A SIMPLE DELETE FEATURE

161

# Redirect the user back to the list page


$c->response->redirect($c->uri_for(/books/list));
}

Try the Delete and Redirect Logic


Restart
the
development
server
and
point
your
browser
to
http://localhost:3000/books/list67 .
Delete the first copy of TCPIP Illustrated Vol2, but notice that no green Book deleted status message is displayed. Because the stash
is reset on every request (and a redirect involves a second request), the status_msg is
cleared before it can be displayed.

Using uri_for to Pass Query Parameters


There are several ways to pass information across a redirect. In general, the best option is to use the flash technique that we will see in Part 4 of the tutorial; however,
here we will pass the information via query parameters on the redirect itself. Open
lib/MyApp/Controller/Books.pm and update the existing sub delete method to match
the following:
=head2 delete
Delete a book
=cut
sub delete : Local {
# $id = primary key of book to delete
my ($self, $c, $id) = @_;
# Search for the book and then delete it
$c->model(MyAppDB::Book)->search({id => $id})->delete_all;
# Redirect the user back to the list page with status msg as an arg
$c->response->redirect($c->uri_for(/books/list,
{status_msg => "Book deleted."}));
}
This modification simply leverages the ability of uri_for to include an arbitrary number
of name/value pairs in a hash reference. Next, we need to update root/lib/site/layout
to handle status_msg as a query parameter:
67

http://localhost:3000/books/list

162

Catalyst::Manual::Tutorial::BasicCRUD

<div id="header">[% PROCESS site/header %]</div>


<div id="content">
<span class="message">[% status_msg || Catalyst.request.params.status_msg
%]</span>
<span class="error">[% error_msg %]</span>
[% content %]
</div>
<div id="footer">[% PROCESS site/footer %]</div>

Try the Delete and Redirect With Query Param Logic


Restart
the
development
server
and
point
your
browser
to
http://localhost:3000/books/list68 .
Then delete the remaining copy of
TCPIP Illustrated Vol-2. The green Book deleted status message should return.
NOTE: Although this did present an opportunity to show a handy capability of
uri_for, it would be much better to use Catalysts flash feature in this situation. Although the technique here is less dangerous than leaving the delete URL in the clients
browser, we have still exposed the status message to the user. With flash, this message
returns to its rightful place as a service-side mechanism (we will migrate this code to flash
in the next part of the tutorial).

AUTHOR
Kennedy Clark, hkclark@gmail.com
Please
report
any
errors,
issues
or
suggestions
to
the
author.
The most recent version of the Catalyst Tutorial can be
found
at
http://dev.catalyst.perl.org/repos/Catalyst/trunk/CatalystRuntime/lib/Catalyst/Manual/Tutorial/69 .
Copyright
2006,
Kennedy
Clark,
under
Creative
Commons
License
(http://creativecommons.org/licenses/by-nc-sa/2.5/70 ).

68

http://localhost:3000/books/list
http://dev.catalyst.perl.org/repos/Catalyst/trunk/Catalyst-Runtime/lib/Catalyst/Manual/Tutorial/
70
http://creativecommons.org/licenses/by-nc-sa/2.5/
69

Catalyst::Manual::Tutorial::Authentication
- Catalyst Tutorial - Part 4:
Authentication
Now that we finally have a simple yet functional application, we can focus on providing
authentication (with authorization coming next in Part 5).
This part of the tutorial is divided into two main sections: 1) basic, cleartext authentication and 2) hash-based authentication.
You can checkout the source code for this example from the catalyst subversion repository as per the instructions in Catalyst::Manual::Tutorial::Intro

OVERVIEW
This is Part 4 of 9 for the Catalyst tutorial.
Tutorial Overview
1. Introduction
2. Catalyst Basics
3. Basic CRUD
4. Authentication
5. Authorization
6. Debugging
7. Testing
8. AdvancedCRUD
9. Appendices

163

164

Catalyst::Manual::Tutorial::Authentication

BASIC AUTHENTICATION
This section explores how to add authentication logic to a Catalyst application.

Add Users and Roles to the Database


First, we add both user and role information to the database (we will add the role information here although it will not be used until the authorization section, Part 5). Create a
new SQL script file by opening myapp02.sql in your editor and insert:
--- Add users and roles tables, along with a many-to-many join table
-CREATE TABLE users (
id
INTEGER PRIMARY KEY,
username
TEXT,
password
TEXT,
email_address TEXT,
first_name
TEXT,
last_name
TEXT,
active
INTEGER
);
CREATE TABLE roles (
id
INTEGER PRIMARY KEY,
role TEXT
);
CREATE TABLE user_roles (
user_id INTEGER,
role_id INTEGER,
PRIMARY KEY (user_id, role_id)
);
--- Load up some initial test data
-INSERT INTO users VALUES (1, test01, mypass, t01@na.com, Joe,
Blow, 1);
INSERT INTO users VALUES (2, test02, mypass, t02@na.com, Jane,
Doe, 1);
INSERT INTO users VALUES (3, test03, mypass, t03@na.com, No,
Go,
0);
INSERT INTO roles VALUES (1, user);
INSERT INTO roles VALUES (2, admin);
INSERT INTO user_roles VALUES (1, 1);
INSERT INTO user_roles VALUES (1, 2);
INSERT INTO user_roles VALUES (2, 1);

BASIC AUTHENTICATION

165

INSERT INTO user_roles VALUES (3, 1);


Then load this into the myapp.db database with the following command:
$ sqlite3 myapp.db < myapp02.sql

Add User and Role Information to DBIC Schema


This step adds DBIC-based classes for the user-related database tables (the role information
will not be used until Part 5):
Edit lib/MyAppDB.pm and update the contents to match (only the MyAppDB =&gt;
[qw/Book BookAuthor Author User UserRole Role/] line has changed):
package MyAppDB;
=head1 NAME
MyAppDB -- DBIC Schema Class
=cut
# Our schema needs to inherit from DBIx::Class::Schema
use base qw/DBIx::Class::Schema/;
# Need to load the DB Model classes here.
# You can use this syntax if you want:
#
__PACKAGE__->load_classes(qw/Book BookAuthor Author User UserRole
Role/);
# Also, if you simply want to load all of the classes in a directory
# of the same name as your schema class (as we do here) you can use:
#
__PACKAGE__->load_classes(qw//);
# But the variation below is more flexible in that it can be used to
# load from multiple namespaces.
__PACKAGE__->load_classes({
MyAppDB => [qw/Book BookAuthor Author User UserRole Role/]
});
1;

166

Catalyst::Manual::Tutorial::Authentication

Create New Result Source Objects


Create the following three files with the content shown below.
lib/MyAppDB/User.pm:
package MyAppDB::User;
use base qw/DBIx::Class/;
# Load required DBIC stuff
__PACKAGE__->load_components(qw/PK::Auto Core/);
# Set the table name
__PACKAGE__->table(users);
# Set columns in table
__PACKAGE__->add_columns(qw/id username password email_address first_name
last_name/);
# Set the primary key for the table
__PACKAGE__->set_primary_key(id);
#
# Set relationships:
#
# has_many():
#
args:
#
1) Name of relationship, DBIC will create accessor with this name
#
2) Name of the model class referenced by this relationship
#
3) Column name in *foreign* table
__PACKAGE__->has_many(map_user_role => MyAppDB::UserRole, user_id);

=head1 NAME
MyAppDB::User - A model object representing a person with access to the
system.
=head1 DESCRIPTION
This is an object that represents a row in the users table of your application
database. It uses DBIx::Class (aka, DBIC) to do ORM.
For Catalyst, this is designed to be used through MyApp::Model::MyAppDB.
Offline utilities may wish to use this class directly.

BASIC AUTHENTICATION

167

=cut
1;

lib/MyAppDB/Role.pm:
package MyAppDB::Role;
use base qw/DBIx::Class/;
# Load required DBIC stuff
__PACKAGE__->load_components(qw/PK::Auto Core/);
# Set the table name
__PACKAGE__->table(roles);
# Set columns in table
__PACKAGE__->add_columns(qw/id role/);
# Set the primary key for the table
__PACKAGE__->set_primary_key(id);
#
# Set relationships:
#
# has_many():
#
args:
#
1) Name of relationship, DBIC will create accessor with this name
#
2) Name of the model class referenced by this relationship
#
3) Column name in *foreign* table
__PACKAGE__->has_many(map_user_role => MyAppDB::UserRole, role_id);

=head1 NAME
MyAppDB::Role - A model object representing a class of access permissions
to
the system.
=head1 DESCRIPTION
This is an object that represents a row in the roles table of your
application database. It uses DBIx::Class (aka, DBIC) to do ORM.

168

Catalyst::Manual::Tutorial::Authentication

For Catalyst, this is designed to be used through MyApp::Model::MyAppDB.


"Offline" utilities may wish to use this class directly.
=cut
1;

lib/MyAppDB/UserRole.pm:
package MyAppDB::UserRole;
use base qw/DBIx::Class/;
# Load required DBIC stuff
__PACKAGE__->load_components(qw/PK::Auto Core/);
# Set the table name
__PACKAGE__->table(user_roles);
# Set columns in table
__PACKAGE__->add_columns(qw/user_id role_id/);
# Set the primary key for the table
__PACKAGE__->set_primary_key(qw/user_id role_id/);
#
# Set relationships:
#
# belongs_to():
#
args:
#
1) Name of relationship, DBIC will create accessor with this name
#
2) Name of the model class referenced by this relationship
#
3) Column name in *this* table
__PACKAGE__->belongs_to(user => MyAppDB::User, user_id);
# belongs_to():
#
args:
#
1) Name of relationship, DBIC will create accessor with this name
#
2) Name of the model class referenced by this relationship
#
3) Column name in *this* table
__PACKAGE__->belongs_to(role => MyAppDB::Role, role_id);

BASIC AUTHENTICATION

169

=head1 NAME
MyAppDB::UserRole - A model object representing the JOIN between Users and
Roles.
=head1 DESCRIPTION
This is an object that represents a row in the user_roles table of your
application
database. It uses DBIx::Class (aka, DBIC) to do ORM.
You probably wont need to use this class directly -- it will be automatically
used by DBIC where joins are needed.
For Catalyst, this is designed to be used through MyApp::Model::MyAppDB.
Offline utilities may wish to use this class directly.
=cut
1;
The code for these three result source classes is obviously very familiar to the Book,
Author, and BookAuthor classes created in Part 2.

Sanity-Check Reload of Development Server


We arent ready to try out the authentication just yet; we only want to do a quick check to
be sure our model loads correctly. Press Ctrl-C to kill the previous server instance (if its
still running) and restart it:
$ script/myapp_server.pl
Look for the three new model objects in the startup debug output:
...
.-------------------------------------------------------------------+---------.
| Class
| Type
|
+-------------------------------------------------------------------+---------+
| MyApp::Controller::Books
| instance |
| MyApp::Controller::Root
| instance |

170

Catalyst::Manual::Tutorial::Authentication

| MyApp::Model::MyAppDB
| instance |
| MyApp::Model::MyAppDB::Author
| class
|
| MyApp::Model::MyAppDB::Book
| class
|
| MyApp::Model::MyAppDB::BookAuthor
| class
|
| MyApp::Model::MyAppDB::Role
| class
|
| MyApp::Model::MyAppDB::User
| class
|
| MyApp::Model::MyAppDB::UserRole
| class
|
| MyApp::View::TT
| instance |
-------------------------------------------------------------------+---------
...
Again, notice that your result source classes have been re-loaded by Catalyst under
MyApp::Model.

Include Authentication and Session Plugins


Edit lib/MyApp.pm and update it as follows (everything below StackTrace is new):
use Catalyst qw/
-Debug
ConfigLoader
Static::Simple
StackTrace
Authentication
Authentication::Store::DBIC
Authentication::Credential::Password
Session
Session::Store::FastMmap
Session::State::Cookie
/;
The three Authentication plugins work together to support Authentication while the
Session plugins are required to maintain state across multiple HTTP requests. Note that

BASIC AUTHENTICATION

171

there are several options for Session::Store (Session::Store::FastMmap is generally a good


choice if you are on Unix; try Cache::FileCache if you are on Win32) -- consult Session::Store
and its subclasses for additional information.

Configure Authentication
Although __PACKAGE__-&gt;config(name =&gt; value); is still supported, newer Catalyst applications tend to place all configuration information in myapp.yml and automatically load this information into MyApp-&gt;config using the ConfigLoader plugin. Here,
we need to load several parameters that tell Catalyst::Plugin::Authentication where to locate information in your database. To do this, edit the myapp.yml YAML and update it to
match:
--name: MyApp
authentication:
dbic:
# Note this first definition would be the same as setting
# __PACKAGE__->config->{authentication}->{dbic}->{user_class} =
MyAppDB::User
# in lib/MyApp.pm (IOW, each hash key becomes a "name:" in the YAML
file).
#
# This is the model object created by Catalyst::Model::DBIC from
your
# schema (you created MyAppDB::User but as the Catalyst startup
# debug messages show, it was loaded as MyApp::Model::MyAppDB::User).
# NOTE: Omit MyApp::Model to avoid a component lookup issue in
Catalyst 5.66
user_class: MyAppDB::User
# This is the name of the field in your users table that contains
the users name
user_field: username
# This is the name of the field in your users table that contains
the password
password_field: password
# Other options can go here for hashed passwords
Inline comments in the code above explain how each field is being used.
TIP: Although YAML uses a very simple and easy-to-ready format, it does require the
use of a consistent level of indenting. Be sure you line up everything on a given level
with the same number of indents. Also, be sure not to use tab characters (YAML does not
support them because they are handled inconsistently across editors).

172

Catalyst::Manual::Tutorial::Authentication

Add Login and Logout Controllers


Use the Catalyst create script to create two stub controller files:
$ script/myapp_create.pl controller Login
$ script/myapp_create.pl controller Logout
NOTE: You could easily use a single controller here. For example, you could have a
User controller with both login and logout actions. Remember, Catalyst is designed to
be very flexible, and leaves such matters up to you, the designer and programmer.
Then open lib/MyApp/Controller/Login.pm, locate the sub index : Private
method (this was automatically inserted by the helpers when we created the Login controller above), and delete this line:
$c->response->body(Matched MyApp::Controller::Login in Login.);
Then update it to match:
=head2 index
Login logic
=cut
sub index : Private {
my ($self, $c) = @_;
# Get the username and password from form
my $username = $c->request->params->{username} || "";
my $password = $c->request->params->{password} || "";
# If the username and password values were found in form
if ($username && $password) {
# Attempt to log the user in
if ($c->login($username, $password)) {
# If successful, then let them use the application
$c->response->redirect($c->uri_for(/books/list));
return;
} else {
# Set an error message
$c->stash->{error_msg} = "Bad username or password.";
}
}
# If either of above dont work out, send to the login page
$c->stash->{template} = login.tt2;
}

BASIC AUTHENTICATION

173

This controller fetches the username and password values from the login form and
attempts to perform a login. If successful, it redirects the user to the book list page. If the
login fails, the user will stay at the login page but receive an error message. If the username
and password values are not present in the form, the user will be taken to the empty login
form.
Note that we could have used something like sub default :Private; however, the use
of default actions is discouraged because it does not receive path args as with other actions.
The recommended practice is to only use default in MyApp::Controller::Root.
Another option would be to use something like sub base :Path :Args(0) {...}
(where the ... refers to the login code shown in sub index : Private above). We
are using sub base :Path :Args(0) {...} here to specifically match the URL /login.
Path actions (aka, literal actions) create URI matches relative to the namespace of the
controller where they are defined. Although Path supports arguments that allow relative
and absolute paths to be defined, here we use an empty Path definition to match on just the
name of the controller itself. The method name, base, is arbitrary. We make the match even
more specific with the :Args(0) action modifier -- this forces the match on only /login,
not /login/somethingelse.
Next, update the corresponding method in lib/MyApp/Controller/Logout.pm to
match:
=head2 index
Logout logic
=cut
sub index : Private {
my ($self, $c) = @_;
# Clear the users state
$c->logout;
# Send the user to the starting point
$c->response->redirect($c->uri_for(/));
}
As with the login controller, be sure to delete the $c-response->body(Matched
MyApp::Controller::Logout in Logout.);> line of the sub index.

Add a Login Form TT Template Page


Create a login form by opening root/src/login.tt2 and inserting:
[% META title = Login %]

174

Catalyst::Manual::Tutorial::Authentication

<!-- Login form -->


<form method="post" action=" [% Catalyst.uri_for(/login) %] ">
<table>
<tr>
<td>Username:</td>
<td><input type="text" name="username" size="40" /></td>
</tr>
<tr>
<td>Password:</td>
<td><input type="password" name="password" size="40" /></td>
</tr>
<tr>
<td colspan="2"><input type="submit" name="submit" value="Submit" /
></td>
</tr>
</table>
</form>

Add Valid User Check


We need something that provides enforcement for the authentication mechanism -- a global
mechanism that prevents users who have not passed authentication from reaching any pages
except the login page. This is generally done via an auto action/method (prior to Catalyst
v5.66, this sort of thing would go in MyApp.pm, but starting in v5.66, the preferred location
is lib/MyApp/Controller/Root.pm).
Edit the existing lib/MyApp/Controller/Root.pm class file and insert the following
method:
=head2 auto
Check if there is a user and, if not, forward to login page
=cut
# Note that auto runs after begin but before your actions and that
# auto "chain" (all from application path to most specific class are run)
# See the Actions section of Catalyst::Manual::Intro for more info.
sub auto : Private {
my ($self, $c) = @_;
# Allow unauthenticated users to reach the login page. This
# allows anauthenticated users to reach any action in the Login

BASIC AUTHENTICATION

175

# controller. To lock it down to a single action, we could use:


#
if ($c->action eq $c->controller(Login)->action_for(index))
# to only allow unauthenticated access to the C<index> action we
# added above.
if ($c->controller eq $c->controller(Login)) {
return 1;
}
# If a user doesnt exist, force login
if (!$c->user_exists) {
# Dump a log message to the development server debug output
$c->log->debug(***Root::auto User not found, forwarding to /login);
# Redirect the user to the login page
$c->response->redirect($c->uri_for(/login));
# Return 0 to cancel post-auto processing and prevent use of application
return 0;
}
# User found, so return 1 to continue with processing after this auto
return 1;
}
Note: Catalyst provides a number of different types of actions, such as Local, Regex,
and Private. You should refer to Catalyst::Manual::Intro for a more detailed explanation, but the following bullet points provide a quick introduction:
The majority of application use Local actions for items that respond to user requests
and Private actions for those that do not directly respond to user input.
There are five types of Private actions: begin, end, default, index, and auto.
With begin, end, default, index private actions, only the most specific action of
each type will be called. For example, if you define a begin action in your controller
it will override a begin action in your application/root controller -- only the action
in your controller will be called.
Unlike the other actions where only a single method is called for each request, every
auto action along the chain of namespaces will be called. Each auto action will be
called from the application/root controller down through the most specific class.

By placing the authentication enforcement code inside the auto method of


lib/MyApp/Controller/Root.pm (or lib/MyApp.pm), it will be called for every request
that is received by the entire application.

176

Catalyst::Manual::Tutorial::Authentication

Displaying Content Only to Authenticated Users


Lets say you want to provide some information on the login page that changes depending
on whether the user has authenticated yet. To do this, open root/src/login.tt2 in your
editor and add the following lines to the bottom of the file:
<p>
[%
# This code illustrates how certain parts of the TT
# template will only be shown to users who have logged in
%]
[% IF Catalyst.user_exists %]
Please Note: You are already logged in as [% Catalyst.user.username
%].
You can <a href="[% Catalyst.uri_for(/logout) %]">logout</a> here.
[% ELSE %]
You need to log in to use this application.
[% END %]
[%#
Note that this whole block is a comment because the "#" appears
immediate after the "[%" (with no spaces in between). Although it
can be a handy way to temporarily "comment out" a whole block of
TT code, its probably a little too subtle for use in "normal"
comments.
%]
Although most of the code is comments, the middle few lines provide a you are already
logged in reminder if the user returns to the login page after they have already authenticated. For users who have not yet authenticated, a You need to log in... message is
displayed (note the use of an IF-THEN-ELSE construct in TT).

Try Out Authentication


Press Ctrl-C to kill the previous server instance (if its still running) and restart it:
$ script/myapp_server.pl
IMPORTANT NOTE: If you happen to be using Internet Explorer, you may need
to use the command script/myapp_server.pl -k to enable the keepalive feature in the
development server. Otherwise, the HTTP redirect on successful login may not work
correctly with IE (it seems to work without -k if you are running the web browser and
development server on the same machine). If you are using browser a browser other
than IE, it should work either way. If you want to make keepalive the default, you can
edit script/myapp_server.pl and change the initialization value for $keepalive to 1.
(You will need to do this every time you create a new Catalyst application or rebuild the
myapp_server.pl script.)

USING PASSWORD HASHES

177

Now trying going to http://localhost:3000/books/list71 and you should be redirected


to the login page, hitting Shift+Reload if necessary (the You are already logged in message should not appear -- if it does, click the logout button and try again). Note the
***Root::auto User not found... debug message in the development server output.
Enter username test01 and password mypass, and you should be taken to the Book List
page.
Open root/src/books/list.tt2 and add the following lines to the bottom:
<p>
<a href="[% Catalyst.uri_for(/login) %]">Login</a>
<a href="[% Catalyst.uri_for(form_create) %]">Create</a>
</p>
Reload your browser and you should now see a Login and Create links at the bottom
of the page (as mentioned earlier, you can update template files without reloading the
development server). Click the first link to return to the login page. This time you should
see the You are already logged in message.
Finally, click the You can logout here link on the /login page. You should stay at
the login page, but the message should change to You need to log in to use this application.

USING PASSWORD HASHES


In this section we increase the security of our system by converting from cleartext passwords
to SHA-1 password hashes.
Note: This section is optional. You can skip it and the rest of the tutorial will function
normally.
Note that even with the techniques shown in this section, the browser still transmits the
passwords in cleartext to your application. We are just avoiding the storage of cleartext
passwords in the database by using a SHA-1 hash. If you are concerned about cleartext
passwords between the browser and your application, consider using SSL/TLS, made easy
with the Catalyst plugin Catalyst::Plugin:RequireSSL.

Get a SHA-1 Hash for the Password


Catalyst uses the Digest module to support a variety of hashing algorithms. Here we will
use SHA-1 (SHA = Secure Hash Algorithm). First, we should compute the SHA-1 hash
for the mypass password we are using. The following command-line Perl script provides
a quick and dirty way to do this:
$ perl -MDigest::SHA -e print Digest::SHA::sha1_hex("mypass"), "\n"
e727d1464ae12436e899a726da5b2f11d8381b26
$
71

http://localhost:3000/books/list

178

Catalyst::Manual::Tutorial::Authentication

Note: You should probably modify this code for production use to not read the password
from the command line. By having the script prompt for the cleartext password, it avoids
having the password linger in forms such as your .bash_history files (assuming you are
using BASH as your shell). An example of such a script can be found in Appendix 3.

Switch to SHA-1 Password Hashes in the Database


Next, we need to change the password column of our users table to store this hash value
vs. the existing cleartext password. Open myapp03.sql in your editor and enter:
--- Convert passwords to SHA-1 hashes
-UPDATE users SET password = e727d1464ae12436e899a726da5b2f11d8381b26
WHERE id = 1;
UPDATE users SET password = e727d1464ae12436e899a726da5b2f11d8381b26
WHERE id = 2;
UPDATE users SET password = e727d1464ae12436e899a726da5b2f11d8381b26
WHERE id = 3;
Then use the following command to update the SQLite database:
$ sqlite3 myapp.db < myapp03.sql
Note: We are using SHA-1 hashes here, but many other hashing algorithms are supported. See Digest for more information.

Enable SHA-1 Hash Passwords in Catalyst::Plugin::Authentication::Store::DBIC


Edit myapp.yml and update it to match (the password_type and password_hash_type are
new, everything else is the same):
--name: MyApp
authentication:
dbic:
# Note this first definition would be the same as setting
# __PACKAGE__->config->{authentication}->{dbic}->{user_class} =
MyAppDB::User
# in lib/MyApp.pm (IOW, each hash key becomes a "name:" in the YAML
file).
#
# This is the model object created by Catalyst::Model::DBIC from
your
# schema (you created MyAppDB::User but as the Catalyst startup
# debug messages show, it was loaded as MyApp::Model::MyAppDB::User).
# NOTE: Omit MyApp::Model here just as you would when using

USING THE SESSION FOR FLASH

179

# $c->model("MyAppDB::User)
user_class: MyAppDB::User
# This is the name of the field in your users table that contains
the users name
user_field: username
# This is the name of the field in your users table that contains
the password
password_field: password
# Other options can go here for hashed passwords
# Enabled hashed passwords
password_type: hashed
# Use the SHA-1 hashing algorithm
password_hash_type: SHA-1

Try Out the Hashed Passwords


Press Ctrl-C to kill the previous server instance (if its still running) and restart it:
$ script/myapp_server.pl
You should now be able to go to http://localhost:3000/books/list72 and login as before. When done, click the Logout link on the login page (or point your browser at
http://localhost:3000/logout73 ).
Note: If you receive the debug screen in your browser with a Cant call method
"stash" on an undefined value... error message, make sure that you are using v0.07
of Catalyst::Plugin::Authorization::ACL. The following command can be a useful way to
quickly dump the version number of this module on your system:
perl -MCatalyst::Plugin::Authorization::ACL -e print
$Catalyst::Plugin::Authorization::ACL::VERSION, "\n";

USING THE SESSION FOR FLASH


As discussed in Part 3 of the tutorial, flash allows you to set variables in a way that is very
similar to stash, but it will remain set across multiple requests. Once the value is read,
it is cleared (unless reset). Although flash has nothing to do with authentication, it does
leverage the same session plugins. Now that those plugins are enabled, lets go back and
72
73

http://localhost:3000/books/list
http://localhost:3000/logout

180

Catalyst::Manual::Tutorial::Authentication

improve the delete and redirect with query parameters code seen at the end of the Basic
CRUD part of the tutorial.
First, open lib/MyApp/Controller/Books.pm and modify sub delete to match the
following:
=head2 delete
Delete a book
=cut
sub delete : Local {
# $id = primary key of book to delete
my ($self, $c, $id) = @_;
# Search for the book and then delete it
$c->model(MyAppDB::Book)->search({id => $id})->delete_all;
# Use flash to save information across requests until its read
$c->flash->{status_msg} = "Book deleted";
# Redirect the user back to the list page with status msg as an arg
$c->response->redirect($c->uri_for(/books/list));
}

Next, open root/lib/site/layout and update the TT code to pull from flash vs. the
status_msg query parameter:
<div id="header">[% PROCESS site/header %]</div>
<div id="content">
<span class="message">[% status_msg || Catalyst.flash.status_msg %]</span>
<span class="error">[% error_msg %]</span>
[% content %]
</div>
<div id="footer">[% PROCESS site/footer %]</div>

AUTHOR

181

Try Out Flash


Restart
the
development
server
and
point
your
browser
to
74
http://localhost:3000/books/url create/Test/1/4
to create an extra book.
Click
the Return to list link and delete the Test book you just added. The flash mechanism
should retain our Book deleted status message across the redirect.
NOTE: While flash will save information across multiple requests, it does get cleared
the first time it is read. In general, this is exactly what you want -- the flash message will
get displayed on the next screen where its appropriate, but it wont keep showing up after
that first time (unless you reset it). Please refer to Catalyst::Plugin::Session for additional
information.

AUTHOR
Kennedy Clark, hkclark@gmail.com
Please
report
any
errors,
issues
or
suggestions
to
the
author.
The most recent version of the Catalyst Tutorial can be
found
at
http://dev.catalyst.perl.org/repos/Catalyst/trunk/CatalystRuntime/lib/Catalyst/Manual/Tutorial/75 .
Copyright
2006,
Kennedy
Clark,
under
Creative
Commons
License
(http://creativecommons.org/licenses/by-nc-sa/2.5/76 ).

74

http://localhost:3000/books/url_create/Test/1/4
http://dev.catalyst.perl.org/repos/Catalyst/trunk/Catalyst-Runtime/lib/Catalyst/Manual/Tutorial/
76
http://creativecommons.org/licenses/by-nc-sa/2.5/
75

182

Catalyst::Manual::Tutorial::Authentication

Catalyst::Manual::Tutorial::Authorization
- Catalyst Tutorial - Part 5:
Authorization
This part of the tutorial adds role-based authorization to the existing authentication implemented in Part 4. It provides simple examples of how to use roles in both TT templates and
controller actions. The first half looks at manually configured authorization. The second
half looks at how the ACL authorization plugin can simplify your code.
You can checkout the source code for this example from the catalyst subversion repository as per the instructions in Catalyst::Manual::Tutorial::Intro

OVERVIEW
This is Part 5 of 9 for the Catalyst tutorial.
Tutorial Overview
1. Introduction
2. Catalyst Basics
3. Basic CRUD
4. Authentication
5. Authorization
6. Debugging
7. Testing
8. AdvancedCRUD
9. Appendices

183

184

Catalyst::Manual::Tutorial::Authorization

BASIC AUTHORIZATION
In this section you learn how to manually configure authorization.

Update Plugins to Include Support for Authorization


Edit lib/MyApp.pm and add Authorization::Roles to the list:
use Catalyst qw/
-Debug
ConfigLoader
Static::Simple
StackTrace
Authentication
Authentication::Store::DBIC
Authentication::Credential::Password
Authorization::Roles
Session
Session::Store::FastMmap
Session::State::Cookie
/;

Add Config Information for Authorization


Edit myapp.yml and update it to match (everything from the authorization: line down is
new):
--name: MyApp
authentication:
dbic:
# Note this first definition would be the same as setting
# __PACKAGE__->config->{authentication}->{dbic}->{user_class} =
MyAppDB::User
# in lib/MyApp.pm (IOW, each hash key becomes a "name:" in the YAML
file).
#
# This is the model object created by Catalyst::Model::DBIC from
your
# schema (you created MyAppDB::User but as the Catalyst startup

BASIC AUTHORIZATION

185

# debug messages show, it was loaded as MyApp::Model::MyAppDB::User).


# NOTE: Omit MyApp::Model here just as you would when using
# $c->model("MyAppDB::User)
user_class: MyAppDB::User
# This is the name of the field in your users table that contains
the users name
user_field: username
# This is the name of the field in your users table that contains
the password
password_field: password
# Other options can go here for hashed passwords
# Enabled hashed passwords
password_type: hashed
# Use the SHA-1 hashing algorithm
password_hash_type: SHA-1
authorization:
dbic:
# This is the model object created by Catalyst::Model::DBIC from
your
# schema (you created MyAppDB::Role but as the Catalyst startup
# debug messages show, it was loaded as MyApp::Model::MyAppDB::Role).
# NOTE: Omit MyApp::Model here just as you would when using
# $c->model("MyAppDB::User)
role_class: MyAppDB::Role
# The name of the field in the roles table that contains the role
name
role_field: role
# The name of the accessor used to map a role to the users who have
this role
# See the has_many() in MyAppDB/Role.pm
role_rel: map_user_role
# The name of the field in the user_role table that references the
user
user_role_user_field: user_id

Add Role-Specific Logic to the Book List Template


Open root/src/books/list.tt2 in your editor and add the following lines to the bottom
of the file:
<p>Hello [% Catalyst.user.username %], you have the following roles:</p>

186

Catalyst::Manual::Tutorial::Authorization

<ul>
[% # Dump list of roles -%]
[% FOR role = Catalyst.user.roles %]<li>[% role %]</li>[% END %]
</ul>
<p>
[% # Add some simple role-specific logic to template %]
[% # Use $c->check_user_roles() to check authz -%]
[% IF Catalyst.check_user_roles(user) %]
[% # Give normal users a link for logout %]
<a href="[% Catalyst.uri_for(/logout) %]">Logout</a>
[% END %]
[% # Can also use $c->user->check_roles() to check authz -%]
[% IF Catalyst.check_user_roles(admin) %]
[% # Give admin users a link for create %]
<a href="[% Catalyst.uri_for(form_create) %]">Create</a>
[% END %]
</p>
This code displays a different combination of links depending on the roles assigned to
the user.

Limit Books::add to admin Users


IF statements in TT templates simply control the output that is sent to the users browser;
it provides no real enforcement (if users know or guess the appropriate URLs, they are still
perfectly free to hit any action within your application). We need to enhance the controller
logic to wrap restricted actions with role-validation logic.
For example, we might want to restrict the formless create action to admin-level users
by editing lib/MyApp/Controller/Books.pm and updating url_create to match the following code:
=head2 url_create
Create a book with the supplied title and rating,
with manual authorization
=cut
sub url_create : Local {
# In addition to self & context, get the title, rating & author_id args
# from the URL. Note that Catalyst automatically puts extra information
# after the "/<controller_name>/<action_name/" into @_

BASIC AUTHORIZATION

187

my ($self, $c, $title, $rating, $author_id) = @_;


# Check the users roles
if ($c->check_user_roles(admin)) {
# Call create() on the book model object. Pass the table
# columns/field values we want to set as hash values
my $book = $c->model(MyAppDB::Book)->create({
title
=> $title,
rating => $rating
});
# Add a record to the join table for this book, mapping to
# appropriate author
$book->add_to_book_authors({author_id => $author_id});
# Note: Above is a shortcut for this:
# $book->create_related(book_authors, {author_id => $author_id});
# Assign the Book object to the stash for display in the view
$c->stash->{book} = $book;
# This is a hack to disable XSUB processing in Data::Dumper
# (its used in the view). This is a work-around for a bug in
# the interaction of some versions or Perl, Data::Dumper & DBIC.
# You wont need this if you arent using Data::Dumper (or if
# you are running DBIC 0.06001 or greater), but adding it doesnt
# hurt anything either.
$Data::Dumper::Useperl = 1;
# Set the TT template to use
$c->stash->{template} = books/create_done.tt2;
} else {
# Provide very simple feedback to the user
$c->response->body(Unauthorized!);
}
}

To add authorization, we simply wrap the main code of this method in an if statement
that calls check_user_roles. If the user does not have the appropriate permissions, they
receive an Unauthorized! message. Note that we intentionally chose to display the message
this way to demonstrate that TT templates will not be used if the response body has already
been set. In reality you would probably want to use a technique that maintains the visual
continuity of your template layout (for example, using the status or error message feature

188

Catalyst::Manual::Tutorial::Authorization

added in Part 2).


TIP: If you want to keep your existing url_create method, you can create a new copy
and comment out the original by making it look like a Pod comment. For example, put
something like =begin before sub add : Local { and =end after the closing }.

Try Out Authentication And Authorization


Press Ctrl-C to kill the previous server instance (if its still running) and restart it:
$ script/myapp_server.pl
Now trying going to http://localhost:3000/books/list77 and you should be taken to the
login page (you might have to Shift+Reload your browser and/or click the Logout link
on the book list page). Try logging in with both test01 and test02 (both use a password
of mypass) and notice how the roles information updates at the bottom of the Book List
page. Also try the Logout link on the book list page.
Now the url create URL will work if you are already logged in as user test01, but
receive an authorization failure if you are logged in as test02. Try:
http://localhost:3000/books/url_create/test/1/6
while logged in as each user.
Use one of the Logout links (or go to
http://localhost:3000/logout78 in you browser directly) when you are done.

ENABLE ACL-BASED AUTHORIZATION


This section takes a brief look at how the Catalyst::Plugin::Authorization::ACL plugin can
automate much of the work required to perform role-based authorization in a Catalyst
application.

Add the Catalyst::Plugin::Authorization::ACL Plugin


Open lib/MyApp.pm in your editor and add the following plugin to the use Catalyst
statement:
Authorization::ACL
Note that the remaining use Catalyst plugins from earlier sections are not shown here,
but they should still be included.

Add ACL Rules to the Application Class


Open lib/MyApp.pm in your editor and add the following BELOW the __PACKAGE__&gt;setup; statement:
77
78

http://localhost:3000/books/list
http://localhost:3000/logout

ENABLE ACL-BASED AUTHORIZATION

189

# Authorization::ACL Rules
__PACKAGE__->deny_access_unless(
"/books/form_create",
[qw/admin/],
);
__PACKAGE__->deny_access_unless(
"/books/form_create_do",
[qw/admin/],
);
__PACKAGE__->deny_access_unless(
"/books/delete",
[qw/user admin/],
);
Each of the three statements above comprises an ACL plugin rule. The first two
rules only allow admin-level users to create new books using the form (both the form itself
and the data submission logic are protected). The third statement allows both users and
admins to delete books. The /books/url_create action will continue to be protected by
the manually configured authorization created earlier in this part of the tutorial.
The ACL plugin permits you to apply allow/deny logic in a variety of ways. The
following provides a basic overview of the capabilities:
The ACL plugin only operates on the Catalyst private namespace. You are using
the private namespace when you use Local actions. Path, Regex, and Global allow
you to specify actions where the path and the namespace differ -- the ACL plugin will
not work in these cases.
Each rule is expressed in a separate __PACKAGE__-&gt;deny_access_unless() or
__PACKAGE__-&gt;allow_access_if() line (there are several other methods that
can be used for more complex policies, see the METHODS portion of the Catalyst::Plugin::Authorization::ACL documentation for more details).
Each rule can contain multiple roles but only a single path.
The rules are tried in order (with the most specific rules tested first), and processing
stops at the first match where an allow or deny is specified. Rules fall through if
there is not a match (where a match means the user has the specified role). If a
match is found, then processing stops there and the appropriate allow/deny action
is taken.
If none of the rules match, then access is allowed.
The rules currently need to be specific in the application class lib\MyApp.pm after
the __PACKAGE__-&gt;setup; line.

190

Catalyst::Manual::Tutorial::Authorization

Add a Method to Handle Access Violations


By default, Catalyst::Plugin::Authorization::ACL throws an exception when authorization
fails. This will take the user to the Catalyst debug screen, or a Please come back later
message if you are not using the -Debug flag. This step uses the access_denied method in
order to provide more appropriate feedback to the user.
Open lib/MyApp/Controller/Books.pm in your editor and add the following method:
=head2 access_denied
Handle Catalyst::Plugin::Authorization::ACL access denied exceptions
=cut
sub access_denied : Private {
my ($self, $c) = @_;
# Set the error message
$c->stash->{error_msg} = Unauthorized!;
# Display the list
$c->forward(list);
}
Then run the Catalyst development server script:
$ script/myapp_server.pl
Log in as test02. Once at the book list, click the Create link to try the form_create
action. You should receive a red Unauthorized! error message at the top of the
list. (Note that in reality you would probably want to place the Create link code in
root/src/books/list.tt2 inside an IF statement that only displays the list to adminlevel users.) If you log in as test01 you should be able to view the form_create form and
add a new book.
When you are done, use one of the Logout links (or go to the
http://localhost:3000/logout79 URL directly) when you are done.

AUTHOR
Kennedy Clark, hkclark@gmail.com
Please
report
any
errors,
issues
or
suggestions
to
the
author.
The most recent version of the Catalyst Tutorial can be
found
at
http://dev.catalyst.perl.org/repos/Catalyst/trunk/CatalystRuntime/lib/Catalyst/Manual/Tutorial/80 .
79
80

http://localhost:3000/logout
http://dev.catalyst.perl.org/repos/Catalyst/trunk/Catalyst-Runtime/lib/Catalyst/Manual/Tutorial/

AUTHOR
Copyright
2006,
Kennedy
Clark,
under
(http://creativecommons.org/licenses/by-nc-sa/2.5/81 ).

81

http://creativecommons.org/licenses/by-nc-sa/2.5/

191
Creative

Commons

License

192

Catalyst::Manual::Tutorial::Authorization

Catalyst::Manual::Tutorial::Debugging
- Catalyst Tutorial - Part 6:
Debugging
This part of the tutorial takes a brief look at the primary options available for troubleshooting Catalyst applications.
Note that when it comes to debugging and troubleshooting, there are two camps:
Fans of log and print statements embedded in the code.
Fans of interactive debuggers.

Catalyst is able to easily accommodate both styles of debugging.

OVERVIEW
This is Part 6 of 9 for the Catalyst tutorial.
Tutorial Overview
1. Introduction
2. Catalyst Basics
3. Basic CRUD
4. Authentication
5. Authorization
6. Debugging
7. Testing
8. AdvancedCRUD
9. Appendices

193

194

Catalyst::Manual::Tutorial::Debugging

LOG STATEMENTS
Folks in the former group can use Catalysts $c-&gt;log facility. (See Catalyst::Log for
more detail.) For example, if you add the following code to a controller action method:
$c->log->info("Starting the foreach loop here");
$c->log->debug("Value of $id is: ".$id);
Then the Catalyst development server will display your message along with the other
debug output. To accomplish the same thing in a TTSite view use:
[% Catalyst.log.debug("This is a test log message") %]
You can also use Data::Dumper in both Catalyst code (use Data::Dumper;
$c-&gt;log-&gt;debug("$var is: ".Dumper($var));)) and TT templates ([%
Dumper.dump(book) %].

RUNNING CATALYST UNDER THE PERL DEBUGGER


Members of the interactive-debugger fan club will also be at home with Catalyst applications. One approach to this style of Perl debugging is to embed breakpoints in your code. For
example, open lib/MyApp/Controller/Books.pm in your editor and add the DB::single=1
line as follows inside the list method (I like to left-justify my debug statements so I dont
forget to remove them, but you can obviously indent them if you prefer):
sub list : Local {
# Retrieve the usual perl OO $self for this object. $c is the Catalyst
# Context thats used to glue together the various components
# that make up the application
my ($self, $c) = @_;
$DB::single=1;
# Retrieve all of the book records as book model objects and store in the
# stash where they can be accessed by the TT template
$c->stash->{books} = [$c->model(MyAppDB::Book)->all];
# Set the TT template to use. You will almost always want to do this
# in your action methods.
$c->stash->{template} = books/list.tt2;
}
This causes the Perl Debugger to enter single step mode when this command is encountered (it has no effect when Perl is run without the -d flag).

RUNNING CATALYST UNDER THE PERL DEBUGGER

195

To now run the Catalyst development server under the Perl debugger, simply prepend
perl -d to the front of script/myapp_server.pl:
$ perl -d script/myapp_server.pl
This will start the interactive debugger and produce output similar to:
$ perl -d script/myapp_server.pl
Loading DB routines from perl5db.pl version 1.27
Editor support available.
Enter h or h h for help, or man perldebug for more help.
main::(script/myapp_server.pl:14):

my $debug

= 0;

DB<1>
Press the c key and hit Enter to continue executing the Catalyst development server
under the debugger. Although execution speed will be slightly slower than normal, you
should soon see the usual Catalyst startup debug information.
Now point your browser to http://localhost:3000/books/list82 and log in. Once the
breakpoint is encountered in the MyApp::Controller::list method, the console session
running the development server will drop to the Perl debugger prompt:
MyApp::Controller::Books::list(/home/me/MyApp/script/../lib/MyApp/
Controller/Books.pm:40):
40:
$c->stash->{books} = [$c->model(MyAppDB::Book)->all];
DB<1>
You now have the full Perl debugger at your disposal. First use the next feature by
typing n to execute the all method on the Book model (n jumps over method/subroutine
calls; you can also use s to single-step into methods/subroutines):
DB<1> n
SELECT me.id, me.authors, me.title, me.rating FROM books me:
MyApp::Controller::Books::list(/home/me/MyApp/script/../lib/MyApp/
Controller/Books.pm:44):
44:
$c->stash->{template} = books/list.tt2;
DB<1>
This takes you to the next line of code where the template name is set. Notice that
because we enabled DBIC_TRACE=1 earlier, SQL debug output also shows up in the development server debug information.
82

http://localhost:3000/books/list

196

Catalyst::Manual::Tutorial::Debugging

Next, list the methods available on our Book model:


DB<1> m $c->model(MyAppDB::Book)
()
(0+
(bool
MODIFY_CODE_ATTRIBUTES
_attr_cache
_collapse_result
_construct_object
_count
_result_class_accessor
_result_source_accessor
all
carp
<lines removed for brevity>
DB<2>
We can also play with the model directly:
DB<2> x ($c->model(MyAppDB::Book)->all)[1]->title
SELECT me.id, me.title, me.rating FROM books me:
0 TCP/IP Illustrated, Volume 1
This uses the Perl debugger x command to display the title of a book.
Next we inspect the books element of the Catalyst stash (the 4 argument to the x
command limits the depth of the dump to 4 levels):
DB<3> x 4 $c->stash->{books}
0 ARRAY(0xa8f3b7c)
0 MyApp::Model::MyAppDB::Book=HASH(0xb8e702c)
_column_data => HASH(0xb8e5e2c)
id => 1
rating => 5
title => CCSP SNRS Exam Certification Guide
_in_storage => 1
<lines removed for brevity>
Then enter the c command to continue processing until the next breakpoint is hit (or
the application exits):
DB<4> c
SELECT author.id, author.first_name, author.last_name FROM ...
Finally, press Ctrl+C to break out of the development server. Because we are running
inside the Perl debugger, you will drop to the debugger prompt. Press q to exit the debugger
and return to your OS shell prompt:

DEBUGGING MODULES FROM CPAN

197

DB<4> q
$
For more information on using the Perl debugger, please see perldebug and perldebtut.
You can also type h or h h at the debugger prompt to view the built-in help screens.

DEBUGGING MODULES FROM CPAN


Although the techniques discussed above work well for code you are writing, what if you
want to use print/log/warn messages or set breakpoints in code that you have installed
from CPAN (or in module that ship with Perl)? One helpful approach is to place a copy of
the module inside the lib directory of your Catalyst project. When Catalyst loads, it will
load from inside your lib directory first, only turning to the global modules if a local copy
cannot be found. You can then make modifications such as adding a $DB::single=1 to the
local copy of the module without risking the copy in the original location. This can also be
a great way to locally override bugs in modules while you wait for a fix on CPAN.
Matt Trout has suggested the following shortcut to create a local copy of an installed
module:
mkdir -p lib/Module; cp perldoc -l Module::Name lib/Module/
For example, you could make a copy of Catalyst::Plugin::Authentication with the following command:
mkdir -p lib/Catalyst/Plugin; cp \
perldoc -l Catalyst::Plugin::Authentication lib/Catalyst/Plugin
Note: Matt has also suggested the following tips for Perl debugging:
Check the version of an installed module:

perl -MModule::Name -e print $Module::Name::VERSION;


For example:
$ perl -MCatalyst::Plugin::Authentication -e \
print $Catalyst::Plugin::Authentication::VERSION;
0.07
Check if a modules contains a given method:

perl -MModule::Name -e print Module::Name->can("method");


For example:
$ perl -MCatalyst::Plugin::Authentication -e \
print Catalyst::Plugin::Authentication->can("prepare");

198

Catalyst::Manual::Tutorial::Debugging
CODE(0x9c8db2c)
If the method exists, the Perl can method returns a coderef. Otherwise, it returns
undef and nothing will be printed.

AUTHOR
Kennedy Clark, hkclark@gmail.com
Please
report
any
errors,
issues
or
suggestions
to
the
author.
The most recent version of the Catalyst Tutorial can be
found
at
http://dev.catalyst.perl.org/repos/Catalyst/trunk/CatalystRuntime/lib/Catalyst/Manual/Tutorial/83 .
Copyright
2006,
Kennedy
Clark,
under
Creative
Commons
License
(http://creativecommons.org/licenses/by-nc-sa/2.5/84 ).

83
84

http://dev.catalyst.perl.org/repos/Catalyst/trunk/Catalyst-Runtime/lib/Catalyst/Manual/Tutorial/
http://creativecommons.org/licenses/by-nc-sa/2.5/

Catalyst::Manual::Tutorial::Testing
- Catalyst Tutorial - Part 7:
Testing
You may have noticed that the Catalyst Helper scripts automatically create basic .t test
scripts under the t directory. This part of the tutorial briefly looks at how these tests can be
used to not only ensure that your application is working correctly at the present time, but
also provide automated regression testing as you upgrade various pieces of your application
over time.
You can checkout the source code for this example from the catalyst subversion repository as per the instructions in Catalyst::Manual::Tutorial::Intro

OVERVIEW
This is Part 7 of 9 for the Catalyst tutorial.
Tutorial Overview
1. Introduction
2. Catalyst Basics
3. Basic CRUD
4. Authentication
5. Authorization
6. Debugging
7. Testing
8. AdvancedCRUD
9. Appendices
199

200

Catalyst::Manual::Tutorial::Testing

RUNNING THE CANNED CATALYST TESTS


There are a variety of ways to run Catalyst and Perl tests (for example, perl Makefile.PL
and make test), but one of the easiest is with the prove command. For example, to run
all of the tests in the t directory, enter:
$ prove --lib lib t
The redirection used by the Authentication plugins will cause the default t/01app.t to
fail. You can fix this by changing the line in t/01app.t that read:
ok( request(/)->is_success, Request should succeed );
to:
ok( request(/login)->is_success, Request should succeed );
So that a redirect is not necessary.
Also, the t/controller_Books.t and
t/controller_Logout.t default test cases will fail because of the authorization. You can
delete these two files to prevent false error messages:
$ rm t/controller_Books.t
$ rm t/controller_Logout.t
As you can see in the prove command line above, the --lib option is used to set the
location of the Catalyst lib directory. With this command, you will get all of the usual
development server debug output, something most people prefer to disable while running
tests cases. Although you can edit the lib/MyApp.pm to comment out the -Debug plugin, its
generally easier to simply set the CATALYST_DEBUG=0 environment variable. For example:
$ CATALYST_DEBUG=0 prove --lib lib t
During the t/02pod and t/03podcoverage tests, you might notice the all skipped:
set TEST_POD to enable this test warning message. To execute the Pod-related tests,
add TEST_POD=1 to the prove command:
$ CATALYST_DEBUG=0 TEST_POD=1 prove --lib lib t
If you omitted the Pod comments from any of the methods that were inserted, you might
have to go back and fix them to get these tests to pass. :-)
Another useful option is the verbose (-v) option to prove. It prints the name of each
test case as it is being run:
$ CATALYST_DEBUG=0 TEST_POD=1 prove --lib lib -v t

RUNNING A SINGLE TEST


You can also run a single script by appending its name to the prove command. For example:

ADDING YOUR OWN TEST SCRIPT

201

$ CATALYST_DEBUG=0 prove --lib lib t/01app.t


Note that you can also run tests directly from Perl without prove. For example:
$ CATALYST_DEBUG=0 perl -Ilib t/01app.t

ADDING YOUR OWN TEST SCRIPT


Although the Catalyst helper scripts provide a basic level of checks for free, testing can
become significantly more helpful when you write your own script to exercise the various
parts of your application. The Test::WWW::Mechanize::Catalyst module is very popular
for writing these sorts of test cases. This module extends Test::WWW::Mechanize (and
therefore WWW::Mechanize) to allow you to automate the action of a user clicking around
inside your application. It gives you all the benefits of testing on a live system without the
messiness of having to use an actual web server, and a real person to do the clicking.
To create a sample test case, open the t/live_app01.t file in your editor and enter the
following:
#!/usr/bin/perl
use strict;
use warnings;
#
#
#
#

Load testing framework and use no_plan to dynamically pick up


all tests. Better to replace "no_plan" with "tests => 30" so it
knows exactly how many tests need to be run (and will tell you if
not), but no_plan is nice for quick & dirty tests

use Test::More no_plan;


# Need to specify the name of your app as arg on next line
# Can also do:
#
use Test::WWW::Mechanize::Catalyst "MyApp";
use ok "Test::WWW::Mechanize::Catalyst" => "MyApp";
# Create two user agents to simulate two different users (test01 &
test02)
my $ua1 = Test::WWW::Mechanize::Catalyst->new;
my $ua2 = Test::WWW::Mechanize::Catalyst->new;
# Use a simplified for loop to do tests that are common to both users
# Use get_ok() to make sure we can hit the base URL
# Second arg = optional description of test (will be displayed for failed

202

Catalyst::Manual::Tutorial::Testing

tests)
# Note that in test scripts you send everything to http://localhost
$_->get_ok("http://localhost/", "Check redirect of base URL") for $ua1,
$ua2;
# Use title_is() to check the contents of the <title>...</title> tags
$_->title_is("Login", "Check for login title") for $ua1, $ua2;
# Use content_contains() to match on text in the html body
$_->content_contains("You need to log in to use this application",
"Check we are NOT logged in") for $ua1, $ua2;
# Log in as each user
# Specify username and password on the URL
$ua1->get_ok("http://localhost/login?username=test01&password=mypass", "Login test01");
# Use the form for user test02; note there is no description here
$ua2->submit_form(
fields => {
username => test02,
password => mypass,
});
# Go back to the login page and it should show that we are already logged
in
$_->get_ok("http://localhost/login", "Return to /login") for $ua1, $ua2;
$_->title_is("Login", "Check for login page") for $ua1, $ua2;
$_->content_contains("Please Note: You are already logged in as ",
"Check we ARE logged in" ) for $ua1, $ua2;
# Click the Logout link (see also text_regex and url_regex options)
$_->follow_link_ok({n => 1}, "Logout via first link on page") for $ua1,
$ua2;
$_->title_is("Login", "Check for login title") for $ua1, $ua2;
$_->content_contains("You need to log in to use this application",
"Check we are NOT logged in") for $ua1, $ua2;
# Log back in
$ua1->get_ok("http://localhost/login?username=test01&password=mypass", "Login test01");
$ua2->get_ok("http://localhost/login?username=test02&password=mypass", "Login test02");
# Should be at the Book List page... do some checks to confirm
$_->title_is("Book List", "Check for book list title") for $ua1, $ua2;
$ua1->get_ok("http://localhost/books/list", "test01 book list");

ADDING YOUR OWN TEST SCRIPT

203

$ua1->get_ok("http://localhost/login", "Login Page");


$ua1->get_ok("http://localhost/books/list", "test01 book list");
$_->content_contains("Book List", "Check for book list title") for $ua1,
$ua2;
# Make sure the appropriate logout buttons are displayed
$_->content_contains("/logout\">Logout</a>",
"Both users should have a User Logout") for $ua1, $ua2;
$ua1->content_contains("/books/form_create\">Create</a>",
"Only test01 should have a create link");
$ua1->get_ok("http://localhost/books/list", "View book list as test01");
# User test01 should be able to create a book with the "formless create"
URL
$ua1->get_ok("http://localhost/books/url_create/TestTitle/2/4",
"test01 formless create");
$ua1->title_is("Book Created", "Book created title");
$ua1->content_contains("Added book TestTitle", "Check title added OK");
$ua1->content_contains("by Stevens", "Check author added OK");
$ua1->content_contains("with a rating of 2.", "Check rating added");
# Try a regular expression to combine the previous 3 checks & account for
whitespace
$ua1->content_like(qr/Added book TestTitle\s+by Stevens\s+with a rating
of 2./, "Regex check");
# Make sure the new book shows in the list
$ua1->get_ok("http://localhost/books/list", "test01 book list");
$ua1->title_is("Book List", "Check logged in and at book list");
$ua1->content_contains("Book List", "Book List page test");
$ua1->content_contains("TestTitle", "Look for TestTitle");
# Make sure the new book can be deleted
# Get all the Delete links on the list page
my @delLinks = $ua1->find_all_links(text => Delete);
# Use the final link to delete the last book
$ua1->get_ok($delLinks[$#delLinks]->url, Delete last book);
# Check that delete worked
$ua1->content_contains("Book List", "Book List page test");
$ua1->content_contains("Book deleted", "Book was deleted");
# User test02 should not be able to add a book
$ua2->get_ok("http://localhost/books/url_create/TestTitle2/2/5", "test02
add");

204

Catalyst::Manual::Tutorial::Testing

$ua2->content_contains("Unauthorized!", "Check test02 cannot add");


The live_app.t test cases uses copious comments to explain each step of the process.
In addition to the techniques shown here, there are a variety of other methods available
in Test::WWW::Mechanize::Catalyst (for example, regex-based matching). Consult the
documentation for more detail.
TIP: For unit tests vs.
the full application tests approach used by
Test::WWW::Mechanize::Catalyst, see Catalyst::Test.
Note: The test script does not test the form_create and form_create_do actions.
That is left as an exercise for the reader (you should be able to complete that logic using
the existing code as a template).
To run the new test script, use a command such as:
$ CATALYST_DEBUG=0 prove --lib lib -v t/live_app01.t
or
$ DBIC_TRACE=0 CATALYST_DEBUG=0 prove --lib lib -v t/live_app01.t
Experiment with the DBIC_TRACE, CATALYST_DEBUG and -v settings. If you find that
there are errors, use the techniques discussed in the Catalyst Debugging section (Part 6)
to isolate and fix any problems.
If you want to run the test case under the Perl interactive debugger, try a command
such as:
$ DBIC_TRACE=0 CATALYST_DEBUG=0 perl -d -Ilib t/live_app01.t
Note that although this tutorial uses a single custom test case for simplicity, you may
wish to break your tests into different files for better organization.
TIP: If you have a test case that fails, you will receive an error similar to the following:
#
Failed test Check we are NOT logged in
#
in t/live_app01.t at line 31.
#
searched: "\x{0a}<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01
Tran"...
#
cant find: "You need to log in to use this application."
Unfortunately, this only shows us the first 50 characters of the HTML returned by the
request -- not enough to determine where the problem lies. A simple technique that can be
used in such situations is to temporarily insert a line similar to the following right after the
failed test:
warn $ua1->content;
This will cause the full HTML returned by the request to be displayed.

SUPPORTING BOTH PRODUCTION AND TEST DATABASES

SUPPORTING
DATABASES

BOTH

PRODUCTION

205

AND

TEST

You may wish to leverage the techniques discussed in this tutorial to maintain both a production database for your live application and a testing database for your test cases.
One advantage to Test::WWW::Mechanize::Catalyst is that it runs your full application;
however, this can complicate things when you want to support multiple databases. One
solution is to allow the database specification to be overridden with an environment variable. For example, open lib/MyApp/Model/MyAppDB.pm in your editor and change the
__PACKAGE__-&gt;config(... declaration to resemble:
my $dsn = $ENV{MYAPP_DSN} ||= dbi:SQLite:myapp.db;
__PACKAGE__->config(
schema_class => MyAppDB,
connect_info => [
$dsn,
,
,
{ AutoCommit => 1 },
],
);
Then, when you run your test case, you can use commands such as:
$ cp myapp.db myappTEST.db
$ CATALYST_DEBUG=0 MYAPP_DSN="dbi:SQLite:myappTEST.db" prove --lib lib -v
t/live_app01.t
This will modify the DSN only while the test case is running. If you launch your normal
application without the MYAPP_DSN environment variable defined, it will default to the same
dbi:SQLite:myapp.db as before.

AUTHOR
Kennedy Clark, hkclark@gmail.com
Please
report
any
errors,
issues
or
suggestions
to
the
author.
The most recent version of the Catalyst Tutorial can be
found
at
http://dev.catalyst.perl.org/repos/Catalyst/trunk/CatalystRuntime/lib/Catalyst/Manual/Tutorial/85 .
Copyright
2006,
Kennedy
Clark,
under
Creative
Commons
License
86
(http://creativecommons.org/licenses/by-nc-sa/2.5/ ).
85
86

http://dev.catalyst.perl.org/repos/Catalyst/trunk/Catalyst-Runtime/lib/Catalyst/Manual/Tutorial/
http://creativecommons.org/licenses/by-nc-sa/2.5/

206

Catalyst::Manual::Tutorial::Testing

Catalyst::Manual::Tutorial::AdvancedCRU
- Catalyst Tutorial - Part 8:
Advanced CRUD
This part of the tutorial explores more advanced functionality for Create, Read, Update,
and Delete (CRUD) than we saw in Part 3. In particular, it looks at a number of techniques
that can be useful for the Update portion of CRUD, such as automated form generation,
validation of user-entered data, and automated transfer of data between forms and model
objects.
In keeping with the Catalyst (and Perl) spirit of flexibility, there are many different ways
to approach advanced CRUD operations in a Catalyst environment. One alternative is to
use Catalyst::Helper::Controller::Scaffold to instantly construct a set of Controller methods
and templates for basic CRUD operations. Although a popular subject in Quicktime movies
that serve as promotional material for various frameworks, real-world applications generally
require more control. Other options include Data::FormValidator and HTML::FillInForm.
Here, we will make use of the HTML::Widget to not only ease form creation, but to also
provide validation of the submitted data. The approached used by this part of the tutorial
is to slowly incorporate additional HTML::Widget functionality in a step-wise fashion (we
start with fairly simple form creation and then move on to more complex and magical
features such as validation and auto-population/auto-saving).
Note: Part 8 of the tutorial is optional. Users who do not wish to use HTML::Widget
may skip this part.
You can checkout the source code for this example from the catalyst subversion repository as per the instructions in Catalyst::Manual::Tutorial::Intro

OVERVIEW
This is Part 8 of 9 for the Catalyst tutorial.
Tutorial Overview
1. Introduction
2. Catalyst Basics
207

208

Catalyst::Manual::Tutorial::AdvancedCRUD

3. Basic CRUD
4. Authentication
5. Authorization
6. Debugging
7. Testing
8. AdvancedCRUD
9. Appendices

HTML::WIDGET FORM CREATION


This section looks at how HTML::Widget can be used to add additional functionality to
the manually created form from Part 3.

Add the HTML::Widget Plugin


Open lib/MyApp.pm in your editor and add the following to the list of plugins (be sure to
leave the existing plugins enabled):
HTML::Widget

Add a Form Creation Helper Method


Open lib/MyApp/Controller/Books.pm in your editor and add the following method:
=head2 make_book_widget
Build an HTML::Widget form for book creation and updates
=cut
sub make_book_widget {
my ($self, $c) = @_;
# Create an HTML::Widget to build the form
my $w = $c->widget(book_form)->method(post);
# Get authors
my @authorObjs = $c->model("MyAppDB::Author")->all();
my @authors = map {$_->id => $_->last_name }
sort {$a->last_name cmp $b->last_name} @authorObjs;

HTML::WIDGET FORM CREATION


# Create the form feilds
$w->element(Textfield,
$w->element(Textfield,
$w->element(Select,
->options(@authors);
$w->element(Submit,

209

title )->label(Title)->size(60);
rating )->label(Rating)->size(1);
authors)->label(Authors)
submit )->value(submit);

# Return the widget


return $w;
}
This method provides a central location that builds an HTML::Widget-based form with
the appropriate fields. The Get authors code uses DBIC to retrieve a list of model objects
and then uses map to create a hash where the hash keys are the database primary keys from
the authors table and the associated values are the last names of the authors.

Add Actions to Display and Save the Form


Open lib/MyApp/Controller/Books.pm in your editor and add the following methods:
=head2 hw_create
Build an HTML::Widget form for book creation and updates
=cut
sub hw_create : Local {
my ($self, $c) = @_;
# Create the widget and set the action for the form
my $w = $self->make_book_widget($c);
$w->action($c->uri_for(hw_create_do));
# Write form to stash variable for use in template
$c->stash->{widget_result} = $w->result;
# Set the template
$c->stash->{template} = books/hw_form.tt2;
}

=head2 hw_create_do
Build an HTML::Widget form for book creation and updates

210

Catalyst::Manual::Tutorial::AdvancedCRUD

=cut
sub hw_create_do : Local {
my ($self, $c) = @_;
# Retrieve the data from the form
my $title
= $c->request->params->{title};
my $rating = $c->request->params->{rating};
my $authors = $c->request->params->{authors};
# Call create() on the book model object. Pass the table
# columns/field values we want to set as hash values
my $book = $c->model(MyAppDB::Book)->create({
title
=> $title,
rating => $rating
});
# Add a record to the join table for this book, mapping to
# appropriate author
$book->add_to_book_authors({author_id => $authors});
# Set a status message for the user
$c->stash->{status_msg} = Book created;
# Use hw_create to redisplay the form. As discussed in
# Part 3, detach is like forward, but it does not return
$c->detach(hw_create);
}
Note how we use make_book_widget to build the core parts of the form in one location,
but we set the action (the URL the form is sent to when the user clicks the Submit
button) separately in hw_create. Doing so allows us to have the same form submit the
data to different actions (e.g., hw_create_do for a create operation but hw_update_do to
update an existing book object).
NOTE: If you receive an error about Catalyst not being able to find the template
hw_create_do.tt2, please verify that you followed the instructions in the final section of
Catalyst Basics where you returned to a manually-specified template. You can either use
forward/detach OR default template names, but the two cannot be used together.

Update the CSS


Edit root/src/ttsite.css and add the following lines to the bottom of the file:
label {

HTML::WIDGET FORM CREATION

211

display: block;
width: 10em;
position: relative;
margin: .5em 0em;
}
label input {
position: absolute;
left: 100%;
}
label select {
position: absolute;
left: 100%;
}
.submit {
margin-top: 2em;;
}
.error_messages {
color: [% site.col.error %];
}
These changes will display form elements vertically and also show error messages in red.
Note that we are pulling the color scheme settings from the root/lib/config/col file that
was created by the TTSite helper. This allows us to change the color used by various error
styles in the CSS from a single location.

Create a Template Page To Display The Form


Open root/src/books/hw_form.tt2 in your editor and enter the following:
[% META title = Create/Update Book %]
[% widget_result.as_xml %]
<p><a href="[% Catalyst.uri_for(list) %]">Return to book list</a></p>

Add Links for Create and Update via HTML::Widget


Open root/src/books/list.tt2 in your editor and add the following to the bottom of the
existing file:
<p>
HTML::Widget:
<a href="[% Catalyst.uri_for(hw_create) %]">Create</a>
</p>

212

Catalyst::Manual::Tutorial::AdvancedCRUD

Test The <HTML::Widget> Create Form


Press Ctrl-C to kill the previous server instance (if its still running) and restart it:
$ script/myapp_server.pl
Login as test01. Once at the Book List page, click the HTML::Widget Create link
to display for form produced by make_book_widget. Fill out the form with the following
values: Title = Internetworking with TCP/IP Vol. II, Rating = 4, and Author =
Comer. Click Submit, and you will be returned to the Create/Update Book page with
a Book created status message displayed. Click Return to book list to view the newly
created book on the main list.
Also note that this implementation allows you to can create books with bogus information. Although we have constrained the authors with the drop-down list, there are no
restrictions on items such as the length of the title (for example, you can create a one-letter
title) and value for the rating (you can use any number you want, and even non-numeric
values with SQLite). The next section will address this concern.
Note: Depending on the database you are using and how you established the columns
in your tables, the database could obviously provide various levels of type enforcement on
your data. The key point being made in the previous paragraph is that the web application
itself is not performing any validation.

HTML::WIDGET VALIDATION AND FILTERING


Although the use of HTML::Widget in the previous section did provide an automated
mechanism to build the form, the real power of this module stems from functionality that
can automatically validate and filter the user input. Validation uses constraints to be sure
that users input appropriate data (for example, that the email field of a form contains a
valid email address). Filtering can be used to remove extraneous whitespace from fields or
to escape meta-characters in user input.

Add Constraints and Filters to the Widget Creation Method


Open lib/MyApp/Controller/Books.pm in your editor and update the make_book_widget
method to match the following (new sections have been marked with a *** NEW: comment):
sub make_book_widget {
my ($self, $c) = @_;
# Create an HTML::Widget to build the form
my $w = $c->widget(book_form)->method(post);
# Get authors

HTML::WIDGET VALIDATION AND FILTERING

213

my @authorObjs = $c->model("MyAppDB::Author")->all();
my @authors = map {$_->id => $_->last_name }
sort {$a->last_name cmp $b->last_name} @authorObjs;
# Create the form feilds
$w->element(Textfield, title )->label(Title)->size(60);
$w->element(Textfield, rating )->label(Rating)->size(1);
# ***NEW: Convert to multi-select list
$w->element(Select,
authors)->label(Authors)
->options(@authors)->multiple(1)->size(3);
$w->element(Submit,
submit )->value(submit);
# ***NEW: Set constraints
$w->constraint(All
=> qw/title rating authors/)
->message(Required. );
$w->constraint(Integer => qw/rating/)
->message(Must be an integer. );
$w->constraint(Range
=> qw/rating/)->min(1)->max(5)
->message(Must be a number between 1 and 5. );
$w->constraint(Length => qw/title/)->min(5)->max(50)
->message(Must be between 5 and 50 characters. );
# ***NEW: Set filters
for my $column (qw/title rating authors/) {
$w->filter( HTMLEscape => $column );
$w->filter( TrimEdges => $column );
}
# Return the widget
return $w;
}
The main changes are:

The Select element for authors is changed from a single-select drop-down to a multiselect list by adding calls to multiple (set to true) and size (set to the number of
rows to display).
Four sets of constraints are added to provide validation of the user input.
Two filters are run on every field to remove and escape unwanted input.

214

Catalyst::Manual::Tutorial::AdvancedCRUD

Rebuild the Form Submission Method to Include Validation


Edit lib/MyApp/Controller/Books.pm and change hw_create_do to match the following
code (enough of the code is different that you probably want to cut and paste this over code
the existing method):
sub hw_create_do : Local {
my ($self, $c) = @_;
# Retrieve the data from the form
my $title
= $c->request->params->{title};
my $rating = $c->request->params->{rating};
my $authors = $c->request->params->{authors};
# Create the widget and set the action for the form
my $w = $self->make_book_widget($c);
$w->action($c->uri_for(hw_create_do));
# Validate the form parameters
my $result = $w->process($c->req);
# Write form (including validation error messages) to
# stash variable for use in template
$c->stash->{widget_result} = $result;
# Were their validation errors?
if ($result->has_errors) {
# Warn the user at the top of the form that there were errors.
# Note that there will also be per-field feedback on
# validation errors because of $w->process($c->req) above.
$c->stash->{error_msg} = Validation errors!;
} else {
# Everything validated OK, so do the create
# Call create() on the book model object. Pass the table
# columns/field values we want to set as hash values
my $book = $c->model(MyAppDB::Book)->create({
title
=> $title,
rating => $rating
});
# Add a record to the join table for this book, mapping to
# appropriate author. Note that $authors will be 1 author as
# a scalar or ref to list of authors depending on how many the
# user selected; the ref $authors ?... handles both cases
foreach my $author (ref $authors ? @$authors : $authors) {

Enable DBIx::Class::HTMLWidget Support

215

$book->add_to_book_authors({author_id => $author});


}
# Set a status message for the user
$c->stash->{status_msg} = Book created;
}
# Set the template
$c->stash->{template} = books/hw_form.tt2;
}
The key changes to hw_create_do are:
hw_create_do no longer does a detach to hw_create to redisplay the form. Now
that hw_create_do has to process the form in order to perform the validation, we
go ahead and build a complete set of form presentation logic into hw_create_do (for
example, hw_create_do now has a $c-&gt;stash-&gt;{template} line). Note that
if we process the form in hw_create_do and forward/detach back to <hw create>, we
would end up with make_book_widget being called twice, resulting in a duplicate set
of elements being added to the form. (There are other ways to address the duplicate
form rendering issue -- just be aware that it exists.)
$w-&gt;process($c-&gt;req) is called to run the validation logic. Not only does
this set the has_errors flag if validation errors are encountered, it returns a string
containing any field-specific warning messages.
An if statement checks if any validation errors were encountered. If so, $c&gt;stash-&gt;{error_msg} is set and the input form is redisplayed. If no errors
were found, the object is created in a manner similar to the prior version of the
hw_create_do method.

Try Out the Form


Press Ctrl-C to kill the previous server instance (if its still running) and restart it:
$ script/myapp_server.pl
Now try adding a book with various errors: title less than 5 characters, non-numeric
rating, a rating of 0 or 6, etc. Also try selecting one, two, and zero authors. When you click
Submit, the HTML::Widget constraint items will validate the logic and insert feedback
as appropriate.

Enable DBIx::Class::HTMLWidget Support


In this section we will take advantage of some of the auto-population features of
DBIx::Class::HTMLWidget. Enabling DBIx::Class::HTMLWidget provides two additional
methods to your DBIC model classes:

216

Catalyst::Manual::Tutorial::AdvancedCRUD
fill widget()

Takes data from the database and transfers it to your form widget.
populate from widget()

Takes data from a form widget and uses it to update the corresponding records in the
database.
In other words, the two methods are a mirror image of each other: one reads from the
database while the other writes to the database.

Add DBIx::Class::HTMLWidget to DBIC Model


In order to use DBIx::Class::HTMLWidget, we need to add HTMLWidget to the
load_components line of DBIC result source files that need to use the fill_widget and
populate_from_widget methods. In this case, open lib/MyAppDB/Book.pm and update
the load_components line to match:
__PACKAGE__->load_components(qw/PK::Auto Core HTMLWidget/);

Use populate_from_widget in hw_create_do


Edit lib/MyApp/Controller/Books.pm and update hw_create_do to match the following
code:
=head2 hw_create_do
Build an HTML::Widget form for book creation and updates
=cut
sub hw_create_do : Local {
my ($self, $c) = @_;
# Create the widget and set the action for the form
my $w = $self->make_book_widget($c);
$w->action($c->uri_for(hw_create_do));
# Validate the form parameters
my $result = $w->process($c->req);
# Write form (including validation error messages) to
# stash variable for use in template
$c->stash->{widget_result} = $result;
# Were their validation errors?

Enable DBIx::Class::HTMLWidget Support

217

if ($result->has_errors) {
# Warn the user at the top of the form that there were errors.
# Note that there will also be per-field feedback on
# validation errors because of $w->process($c->req) above.
$c->stash->{error_msg} = Validation errors!;
} else {
my $book = $c->model(MyAppDB::Book)->new({});
$book->populate_from_widget($result);
# Add a record to the join table for this book, mapping to
# appropriate author. Note that $authors will be 1 author as
# a scalar or ref to list of authors depending on how many the
# user selected; the ref $authors ?... handles both cases
my $authors = $c->request->params->{authors};
foreach my $author (ref $authors ? @$authors : $authors) {
$book->add_to_book_authors({author_id => $author});
}
# Set a status message for the user
$c->flash->{status_msg} = Book created;
# Redisplay an empty form for another
$c->stash->{widget_result} = $w->result;
}
# Set the template
$c->stash->{template} = books/hw_form.tt2;
}
In this version of hw_create_do we removed the logic that manually pulled the form variables and used them to call $c-&gt;model(MyAppDB::Book)-&gt;create and replaced
it with a single call to $book-&gt;populate_from_widget. Note that we still have to call
$book-&gt;add_to_book_authors once per author because populate_from_widget does
not currently handle the relationships between tables. Also, we reset the form to an empty
fields by adding another call to $w-&gt;result and storing the output in the stash (if we
dont override the output from $w-&gt;process($c-&gt;req), the form values already entered will be retained on redisplay -- although this could be desirable for some applications,
we avoid it here to help avoid the creation of duplicate records).

Try Out the Form


Press Ctrl-C to kill the previous server instance (if its still running) and restart it:
$ script/myapp_server.pl

218

Catalyst::Manual::Tutorial::AdvancedCRUD

Try adding a book that validates. Return to the book list and the book you added
should be visible.

Rendering HTMLWidget Forms in a Table


Some developers my wish to use the old-fashioned table style of rendering a form in lieu
of the default HTML::Widget rendering that assumes you will use CSS for formatting. This
section demonstrates some techniques that can override the default rendering with a custom
class.

Add a New Element Container


Open lib/FormElementContainer.pm in your editor and enter:
package FormElementContainer;
use base HTML::Widget::Container;
sub _build_element {
my ($self, $element) = @_;
return () unless $element;
if (ref $element eq ARRAY) {
return map { $self->_build_element($_) } @{$element};
}
my $e = $element->clone;
$e = new HTML::Element(span, class => fields_with_errors)>push_content($e)
if $self->error && $e->tag eq input;
return $e ? ($e) : ();
}
1;
This simply dumps the HTML code for a given form element, followed by a span that
can contain validation error message.

Rendering HTMLWidget Forms in a Table

219

Enable the New Element Container When Building the Form


Open lib/MyApp/Controller/Books.pm in your editor. First add a use for your element
container class:
use FormElementContainer;
Note: If you forget to use your container class in your controller, then your form will
not be displayed and no error messages will be generated. Dont forget this important step!
Then tell HTML::Widget to use that class during rendering by updating
make_book_widget to match the following:
sub make_book_widget {
my ($self, $c) = @_;
# Create an HTML::Widget to build the form
my $w = $c->widget(book_form)->method(post);
# ***New: Use custom class to render each element in the form
$w->element_container_class(FormElementContainer);
# Get authors
my @authorObjs = $c->model("MyAppDB::Author")->all();
my @authors = map {$_->id => $_->last_name }
sort {$a->last_name cmp $b->last_name} @authorObjs;
# Create the form feilds
$w->element(Textfield, title )->label(Title)->size(60);
$w->element(Textfield, rating )->label(Rating)->size(1);
# Convert to multi-select list
$w->element(Select,
authors)->label(Authors)
->options(@authors)->multiple(1)->size(3);
$w->element(Submit,
submit )->value(submit);
# Set constraints
$w->constraint(All
=> qw/title rating authors/)
->message(Required. );
$w->constraint(Integer => qw/rating/)
->message(Must be an integer. );
$w->constraint(Range
=> qw/rating/)->min(1)->max(5)
->message(Must be a number between 1 and 5. );
$w->constraint(Length => qw/title/)->min(5)->max(50)
->message(Must be between 5 and 50 characters. );
# Set filters
for my $column (qw/title rating authors/) {

220

Catalyst::Manual::Tutorial::AdvancedCRUD
$w->filter( HTMLEscape => $column );
$w->filter( TrimEdges => $column );

}
# Return the widget
return $w;
}
The two new lines are marked with ***New:.

Update the TT Template


Open root/src/books/hw_form.tt2 and edit it to match:
[% META title = Create/Update Book %]
[%# Comment out the auto-rendered form %]
[%# widget_result.as_xml %]

[%# Iterate over the form elements and display each -%]
<form name="book_form" action="[% widget_result.action %]" method="post">
<table border="0">
[% FOREACH element = widget_result.elements %]
<tr>
<td class="form-label">
[% element.label.as_text %]
</td>
<td class="form-element">
[% element.element_xml %]
<span class="form-error">
[% element.error_xml %]
</span>
</td>
</tr>
[% END %]
</table>
</form>

<p><a href="[% Catalyst.uri_for(list) %]">Return to book list</a></p>

AUTHOR

221

[%# A little JavaScript to move the cursor to the first field %]


<script LANGUAGE="JavaScript">
document.book_form.book_form_title.focus();
</script>
This represents three changes:
The existing widget_result.as_xml has been commented out.
It loops through each form element, displaying the field name in the first table cell
along with the form element and validation errors in the second field.
JavaScript to position the users cursor in the first field of the form.

Try Out the Form


Press Ctrl-C to kill the previous server instance (if its still running) and restart it:
$ script/myapp_server.pl
Try adding a book that validates. Return to the book list and the book you added
should be visible.

AUTHOR
Kennedy Clark, hkclark@gmail.com
Please
report
any
errors,
issues
or
suggestions
to
the
author.
The most recent version of the Catalyst Tutorial can be
found
at
http://dev.catalyst.perl.org/repos/Catalyst/trunk/CatalystRuntime/lib/Catalyst/Manual/Tutorial/87 .
Copyright
2006,
Kennedy
Clark,
under
Creative
Commons
License
(http://creativecommons.org/licenses/by-nc-sa/2.5/88 ).

87
88

http://dev.catalyst.perl.org/repos/Catalyst/trunk/Catalyst-Runtime/lib/Catalyst/Manual/Tutorial/
http://creativecommons.org/licenses/by-nc-sa/2.5/

222

Catalyst::Manual::Tutorial::AdvancedCRUD

Catalyst::Manual::Tutorial::Appendices
- Catalyst Tutorial - Part 9:
Appendices
This part of the tutorial provides supporting information relevant to the Catalyst tutorial.

OVERVIEW
This is Part 9 of 9 of the Catalyst tutorial.
Tutorial Overview
1. Introduction
2. Catalyst Basics
3. Basic CRUD
4. Authentication
5. Authorization
6. Debugging
7. Testing
8. AdvancedCRUD
9. Appendices

APPENDIX 1: CUT AND PASTE FOR POD-BASED EXAMPLES


You may notice that Pod indents example code with four spaces. This section provides
some quick advice to un-indent this text in common editors.
223

224

Catalyst::Manual::Tutorial::Appendices

Un-indenting with Vi/Vim


When cutting and pasting multi-line text from Pod-based documents, the following vi/vim
regexs can be helpful to un-indent the inserted text (do NOT type the quotes, they are
only included to show spaces in the regex patterns). Note that all 3 of the regexs end in 4
spaces:
:0,$s/

Removes four leading spaces from the entire file (from the first line, , to the last line,
$).
%s/

A shortcut for the previous item (% specifies the entire file; so this removes four leading
spaces from every line).
:.,$s/

Removes the first four spaces from the line the cursor is on at the time the regex
command is executed (.) to the last line of the file.
:.,44s/

Removes four leading space from the current line through line 44 (obviously adjust
the 44 to the appropriate value in your example).

Un-indenting with Emacs


Although there author has not used emacs for many years (apologies to the emacs fans out
there), here is a quick hint to get you started. To replace the leading spaces of every line
in a file, use:
M-x replace-regexp<RET>
Replace regexp: ^
<RET>
with: <RET>
All of that will occur on the single line at the bottom of your screen. Note that <RET>
represents the return key/enter. Also, there are four spaces after the on the Replace
regexp: line and no spaces entered on the last line.
You can limit the replacement operation by selecting text first (depending on your
version of emacs, you can either use the mouse or experiment with commands such as CSPC to set the mark at the cursor location and C-&lt; and C-&gt; to set the mark at the
beginning and end of the file respectively.

APPENDIX 2: USING MYSQL AND POSTGRESQL


The main database used in this tutorial is the very simple yet powerful SQLite. This
section provides information that can be used to convert the tutorial to use MySQL and

APPENDIX 2: USING MYSQL AND POSTGRESQL

225

PostgreSQL. However, note that part of the beauty of the MVC architecture is that very
little database-specific code is spread throughout the system (at least when MVC is done
right). Consequently, converting from one database to another is relatively painless with
most Catalyst applications. In general, you just need to adapt the schema definition .sql
file you use to initialize your database and adjust a few configuration parameters.
Also note that the purpose of the data definition statements for this section are not
designed to take maximum advantage of the various features in each database for issues
such as referential integrity and field types/constraints.

MySQL
Use the following steps to adapt the tutorial to MySQL. Thanks to Jim Howard for the
help.
Part 2: Catalyst Basics

Install the required software:


* The MySQL database server and client utility.
* The Perl DBD::MySQL module

For CentOS users (see Catalyst::Manual::Installation::CentOS4), you can use the


following commands to install the software and start the MySQL daemon:
yum -y install mysql mysql-server
service mysqld start
Create the database and set the permissions:
$ mysql
Welcome to the MySQL monitor. Commands end with ; or \g.
Your MySQL connection id is 2 to server version: 4.1.20
Type help; or \h for help. Type \c to clear the buffer.
mysql> create database myapp;
Query OK, 1 row affected (0.01 sec)
mysql> grant all on myapp.* to tutorial@localhost;
Query OK, 0 rows affected (0.00 sec)
mysql> flush privileges;
Query OK, 0 rows affected (0.00 sec)
mysql> quit
Bye

226

Catalyst::Manual::Tutorial::Appendices
Create the .sql file and load the data:
* Open the myapp01_mysql.sql in your editor and enter:
--- Create a very simple database to hold book and author information
-DROP TABLE IF EXISTS books;
DROP TABLE IF EXISTS book_authors;
DROP TABLE IF EXISTS authors;
CREATE TABLE books (
id
INT(11) PRIMARY KEY AUTO_INCREMENT,
title
TEXT ,
rating
INT(11)
);
-- book_authors is a many-to-many join table between books &
authors
CREATE TABLE book_authors (
book_id
INT(11),
author_id
INT(11),
PRIMARY KEY (book_id, author_id)
);
CREATE TABLE authors (
id
INT(11) PRIMARY KEY AUTO_INCREMENT,
first_name TEXT,
last_name
TEXT
);
----- Load some sample data
--INSERT INTO books VALUES (1, CCSP SNRS Exam Certification
Guide, 5);
INSERT INTO books VALUES (2, TCP/IP Illustrated, Volume 1,
5);
INSERT INTO books VALUES (3, Internetworking with TCP/IP
Vol.1, 4);
INSERT INTO books VALUES (4, Perl Cookbook, 5);
INSERT INTO books VALUES (5, Designing with Web Standards,
5);
INSERT INTO authors VALUES (1, Greg, Bastien);
INSERT INTO authors VALUES (2, Sara, Nasseh);
INSERT INTO authors VALUES (3, Christian, Degu);
INSERT INTO authors VALUES (4, Richard, Stevens);
INSERT INTO authors VALUES (5, Douglas, Comer);

APPENDIX 2: USING MYSQL AND POSTGRESQL


INSERT
INSERT
INSERT
INSERT
INSERT
INSERT
INSERT
INSERT
INSERT
INSERT
INSERT

INTO
INTO
INTO
INTO
INTO
INTO
INTO
INTO
INTO
INTO
INTO

227

authors VALUES (6, Tom, Christiansen);


authors VALUES (7, Nathan, Torkington);
authors VALUES (8, Jeffrey, Zeldman);
book_authors VALUES (1, 1);
book_authors VALUES (1, 2);
book_authors VALUES (1, 3);
book_authors VALUES (2, 4);
book_authors VALUES (3, 5);
book_authors VALUES (4, 6);
book_authors VALUES (4, 7);
book_authors VALUES (5, 8);

* Load the data:


mysql -ututorial myapp < myapp01_mysql.sql
* Make sure the data loaded correctly:
$ mysql -ututorial myapp
Reading table information for completion of table and column
names
You can turn off this feature to get a quicker startup with -A

Welcome to the MySQL monitor. Commands end with ; or \g.


Your MySQL connection id is 4 to server version: 4.1.20
Type help; or \h for help. Type \c to clear the buffer.
mysql> show tables;
+-----------------+
| Tables_in_myapp |
+-----------------+
| authors
|
| book_authors
|
| books
|
+-----------------+
3 rows in set (0.00 sec)
mysql> select * from books;
+----+------------------------------------+--------+
| id | title
| rating |
+----+------------------------------------+--------+
| 1 | CCSP SNRS Exam Certification Guide |
5 |
| 2 | TCP/IP Illustrated, Volume 1
|
5 |
| 3 | Internetworking with TCP/IP Vol.1 |
4 |

228

Catalyst::Manual::Tutorial::Appendices
| 4 | Perl Cookbook
|
5 |
| 5 | Designing with Web Standards
|
5 |
+----+------------------------------------+--------+
5 rows in set (0.00 sec)
mysql>
Update the model:
* Delete the existing model:
rm lib/MyApp/Model/MyAppDB.pm
* Regenerate the model using the Catalyst create.pl script:
script/myapp_create.pl model MyAppDB DBIC::Schema MyAppDB dbi:mysql:myapp tutorial { AutoCommit => 1 }
Part 4: Authentication

Create the .sql file for the user/roles data:


Open myapp02_mysql.sql in your editor and enter:
--- Add users and roles tables, along with a many-to-many join table
-CREATE TABLE users (
id
INT(11) PRIMARY KEY,
username
TEXT,
password
TEXT,
email_address TEXT,
first_name
TEXT,
last_name
TEXT,
active
INT(11)
);
CREATE TABLE roles (
id
INTEGER PRIMARY KEY,
role TEXT
);
CREATE TABLE user_roles (
user_id INT(11),
role_id INT(11),
PRIMARY KEY (user_id, role_id)
);
--

APPENDIX 2: USING MYSQL AND POSTGRESQL

229

-- Load up some initial test data


-INSERT INTO users VALUES (1, test01, mypass, t01@na.com,
Joe, Blow, 1);
INSERT INTO users VALUES (2, test02, mypass, t02@na.com,
Jane, Doe, 1);
INSERT INTO users VALUES (3, test03, mypass, t03@na.com,
No,
Go,
0);
INSERT INTO roles VALUES (1, user);
INSERT INTO roles VALUES (2, admin);
INSERT INTO user_roles VALUES (1, 1);
INSERT INTO user_roles VALUES (1, 2);
INSERT INTO user_roles VALUES (2, 1);
INSERT INTO user_roles VALUES (3, 1);
Load the user/roles data:
mysql -ututorial myapp < myapp02_mysql.sql
Create the .sql file for the hashed password data:
Open myapp03_mysql.sql in your editor and enter:
--- Convert passwords to SHA-1 hashes
-UPDATE users SET password = e727d1464ae12436e899a726da5b2f11d8381b26
WHERE id = 1;
UPDATE users SET password = e727d1464ae12436e899a726da5b2f11d8381b26
WHERE id = 2;
UPDATE users SET password = e727d1464ae12436e899a726da5b2f11d8381b26
WHERE id = 3;
Load the user/roles data:
mysql -ututorial myapp < myapp03_mysql.sql

PostgreSQL
TODO -- Please see the latest version of this document for possible
updates:
http://dev.catalyst.perl.org/repos/Catalyst/trunk/CatalystRuntime/lib/Catalyst/Manual/Tutorial/Appendices.pod89
89

http://dev.catalyst.perl.org/repos/Catalyst/trunk/Catalyst-Runtime/lib/Catalyst/Manual/Tutorial/Appendice

230

Catalyst::Manual::Tutorial::Appendices

APPENDIX 3: IMPROVED HASHING SCRIPT


Here is an improved SHA-1 hashing script from Gavin Henry that does not expose the
passwords to capture on the command line.
#!/usr/bin/perl -w
#==========================================================================
=====
#
#
FILE: enc_pass.pl
#
#
USAGE: ./enc_pass.pl
#
# DESCRIPTION: Encrypt a Password using SHA-1
#
#
OPTIONS: --# REQUIREMENTS: --#
BUGS: --#
NOTES: --#
AUTHOR: Gavin Henry (GH), <ghenry@suretecsystems.com>
#
COMPANY: Suretec Systems Ltd.
#
VERSION: 1.0
#
CREATED: 26/06/2006
#
REVISION: --#
COPYRIGHT: http://search.cpan.org/dist/perl/pod/perlgpl.pod
#==========================================================================
=====
use
use
use
use

strict;
warnings;
Digest::SHA1;
Term::ReadKey;

sub get_pass {
ReadMode noecho;
chomp( my $pw = ReadLine 0 );
ReadMode normal;
return $pw;
}
print "Enter the password to be encrypted: ";
my $pass = get_pass();
print "\nConfirm the password: ";
my $verify = get_pass();

AUTHOR

231

if ( $pass eq $verify ) {
my $sha1_enc = Digest::SHA1->new;
$sha1_enc->add($pass);
print "\nYour encrypted password is: "
. $sha1_enc->hexdigest . "\n"
. "Paste this into your SQL INSERT/COPY Data.\n";
}
else {
print "\nPasswords do not match!\n";
}

AUTHOR
Kennedy Clark, hkclark@gmail.com
Please
report
any
errors,
issues
or
suggestions
to
the
author.
The most recent version of the Catalyst Tutorial can be
found
at
http://dev.catalyst.perl.org/repos/Catalyst/trunk/CatalystRuntime/lib/Catalyst/Manual/Tutorial/90 .
Copyright
2006,
Kennedy
Clark,
under
Creative
Commons
License
(http://creativecommons.org/licenses/by-nc-sa/2.5/91 ).

90
91

http://dev.catalyst.perl.org/repos/Catalyst/trunk/Catalyst-Runtime/lib/Catalyst/Manual/Tutorial/
http://creativecommons.org/licenses/by-nc-sa/2.5/

232

Catalyst::Manual::Tutorial::Appendices

Catalyst::Manual::WritingPlugins An introduction to writing plugins


with .
Writing an integrated plugin for Catalyst using NEXT.

WHY PLUGINS?
A Catalyst plugin is an integrated part of your application. By writing plugins you can,
for example, perform processing actions automatically, instead of having to forward to a
processing method every time you need it.

WHATS NEXT?
NEXT is used to re-dispatch a method call as if the calling method doesnt exist at all. In
other words: If the class youre inheriting from defines a method, and youre overloading
that method in your own class, NEXT gives you the possibility to call that overloaded
method.
This technique is the usual way to plug a module into Catalyst.

INTEGRATING YOUR PLUGIN


You can use NEXT for your plugin by overloading certain methods which are called by
Catalyst during a request.

The request life-cycle


Catalyst creates a context object ($context or, more usually, its alias $c) on every request,
which is passed to all the handlers that are called from preparation to finalization.
For a complete list of the methods called during a request, see Catalyst::Manual::Internals. The request can be split up in three main stages:
233

234

Catalyst::Manual::WritingPlugins

preparation
When the prepare handler is called, it initializes the request object, connections,
headers, and everything else that needs to be prepared. prepare itself calls other
methods to delegate these tasks. After this method has run, everything concerning
the request is in place.
dispatch
The dispatching phase is where the black magic happens. The dispatch handler
decides which actions have to be called for this request.
finalization
Catalyst uses the finalize method to prepare the response to give to the client. It
makes decisions according to your response (e.g. where you want to redirect the user
to). After this method, the response is ready and waiting for you to do something
with it--usually, hand it off to your View class.

What Plugins look like


Theres nothing special about a plugin except its name. A module named Catalyst::Plugin::MyPlugin will be loaded by Catalyst if you specify it in your application
class, e.g.:
# your plugin
package Catalyst::Plugin::MyPlugin;
use warnings;
use strict;
...
# MyApp.pm, your application class
use Catalyst qw/-Debug MyPlugin/;
This does nothing but load your module. Well now see how to overload stages of the
request cycle, and provide accessors.

Calling methods from your Plugin


Methods that do not overload a handler are available directly in the $c context object; they
dont need to be qualified with namespaces, and you dont need to use them.
package Catalyst::Plugin::Foobar;
use strict;
sub foo { return bar; }
# anywhere else in your Catalyst application:
$c->foo(); # will return bar

EXAMPLE

235

Thats it.

Overloading - Plugging into Catalyst


If you dont just want to provide methods, but want to actually plug your module into the
request cycle, you have to overload the handler that suits your needs.
Every handler gets the context object passed as its first argument. Pass the rest of the
arguments to the next handler in row by calling it via
$c->NEXT::handler-name( @_ );
if you already shifted it out of @_. Remember to use NEXT.

Storage and Configuration


Some Plugins use their accessor names as a storage point, e.g.
sub my_accessor {
my $c = shift;
$c->{my_accessor} = ..
but it is more safe and clear to put your data in your configuration hash:
$c->config->{my_plugin}{ name } = $value;
If you need to maintain data for more than one request, you should store it in a session.

EXAMPLE
Heres a simple example Plugin that shows how to overload prepare to add a unique ID to
every request:
package Catalyst::Plugin::RequestUUID;
use warnings;
use strict;
use Catalyst::Request;
use Data::UUID;
use NEXT;
our $VERSION = 0.01;
{

# create a uuid accessor


package Catalyst::Request;
__PACKAGE__->mk_accessors(uuid);

236

Catalyst::Manual::WritingPlugins

sub prepare {
my $class = shift;
# Turns the engine-specific request into a Catalyst context .
my $c = $class->NEXT::prepare( @_ );
$c->request->uuid( Data::UUID->new->create_str );
$c->log->debug( Request UUID ". $c->request->uuid ." );
return $c;
}
1;
Lets just break it down into pieces:
package Catalyst::Plugin::RequestUUID;
The package name has to start with Catalyst::Plugin:: to make sure you can load
your plugin by simply specifying
use Catalyst qw/RequestUUID/;
in the application class. warnings and strict are recommended for all Perl applications.
use NEXT;
use Data::UUID;
our $VERSION = 0.01;
NEXT must be explicitly used. Data::UUID generates our unique ID. The $VERSION
gets set because its a) a good habit and b) ExtUtils::ModuleMaker likes it.
sub prepare {
These methods are called without attributes (Private, Local, etc.).
my $c = shift;
We get the context object for this request as the first argument.
Hint!:Be sure you shift the context object out of @_ in this. If you just do a
my ( $c ) = @_;
it remains there, and you may run into problems if youre not aware of what you pass
to the handler youve overloaded. If you take a look at
$c = $c->NEXT::prepare( @_ );
you see you would pass the context twice here if you dont shift it out of your parameter
list.

SEE ALSO

237

This line is the main part of the plugin procedure. We call the overloaded prepare
method and pass along the parameters we got. We also overwrite the context object $c
with the one returned by the called method returns. Well return our modified context
object at the end.
Note that that if we modify $c before this line, we also modify it before the original
(overloaded) prepare is run. If we modify it after, we modify an already prepared context.
And, of course, its no problem to do both, if you need to. Another example of working
on the context before calling the actual handler would be setting header information before
finalize does its job.
$c->req->{req_uuid} = Data::UUID->new->create_str;
This line creates a new Data::UUID object and calls the create_str method. The value
is saved in our request, under the key req_uuid. We can use that to access it in future in
our application.
$c->log->debug( Request UUID ". $c->req->{req_uuid} ." );
This sends our UUID to the debug log.
The final line
return $c;
passes our modified context object back to whoever has called us. This could be Catalyst
itself, or the overloaded handler of another plugin.

SEE ALSO
Catalyst, NEXT, ExtUtils::ModuleMaker,
lyst::Manual::Internals.

Catalyst::Manual::Plugins,

Cata-

THANKS TO
Sebastian Riedel and his team of Catalyst developers as well as all the helpful people in
#catalyst.

COPYRIGHT
This program is free software, you can redistribute it and/or modify it under the same terms
as Perl itself.

AUTHOR
Robert Sedlacek, phaylon@dunkelheit.at with a lot of help from the people on #catalyst.

You might also like