Professional Documents
Culture Documents
Catalyst Manual: April 20, 2007
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
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
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.
18
Catalyst::Manual::About
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.
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.
http://www.rubyonrails.org
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.
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).
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.
RECIPES
Basics
These recipes cover some basic stuff that is worth knowing for catalyst developers.
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 { }
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
/;
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
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
29
30
Catalyst::Manual::Cookbook
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
/;
31
Cata-
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.
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
}
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
35
36
Catalyst::Manual::Cookbook
}
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.
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.
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
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
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!
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.
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.
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;
}
52
Catalyst::Manual::Cookbook
Deployment
53
Deployment
The recipes below describe aspects of the deployment process, including web server engines
and tips to improve application efficiency.
Pros
Speed
mod perl is very fast and your app will benefit from being loaded in memory within each
Apache process.
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.
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.
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.
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.
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.
http://www.fastcgi.com/
58
Catalyst::Manual::Cookbook
More Info
Catalyst::Engine::FastCGI.
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.
60
Catalyst::Manual::Cookbook
Deployment
61
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->res->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
Deployment
65
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.
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.
70
Catalyst::Manual::Cookbook
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.
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.
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.
75
76
Catalyst::Manual::DevelopmentProcess
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.
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->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->config>{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->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
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
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
* 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->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.
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:
How It Works
97
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->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->req->args will be changed for the duration of the forward only; upon
return, the original value of $c->req->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
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.
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::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.
A
tarball
of
the
final
application
is
available
at
http://dev.catalyst.perl.org/repos/Catalyst/trunk/examples/Tutorial/Final Tarball/MyApp.tgz41 .
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
115
Part 4: Authentication
BASIC AUTHENTICATION
Part 5: Authorization
BASIC AUTHORIZATION
116
Catalyst::Manual::Tutorial
Limit Books::add to admin Users
Try Out Authentication And Authorization
ENABLE ACL-BASED AUTHORIZATION
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
THANKS
117
Part 9: Appendices
APPENDIX 1: CUT AND PASTE FOR POD-BASED EXAMPLES
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/
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
121
5. Authorization
6. Debugging
7. Testing
8. Advanced CRUD
9. Appendices
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
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.
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
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.
http://localhost:3000
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.
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.
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->debug method to enable debug messages.
Catalyst::Plugin::ConfigLoader
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.
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.
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>book_authors->first->author->last_name (we will see examples on how
to use DBIC objects in your code soon, but note that because $book->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->authors->first->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;
135
=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.
=head1 NAME
137
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.
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]).
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->model(MyAppDB::Book) used above written as $c>model(MyAppDB)->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 ).
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
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.
CATALYST VIEWS
143
144
Catalyst::Manual::Tutorial::CatalystBasics
http://www.template-toolkit.org/docs/default/Manual/Variables.html
http://www.template-toolkit.org/docs/default/
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->storage->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.
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.
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->forward or the $c->detach mechanisms (these are discussed
in Part 2 and Part 8 of the Tutorial).
http://localhost:3000/books/list
and
access
AUTHOR
149
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).
FORMLESS SUBMISSION
153
# that have been processed before this template (here its for
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.
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.
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.
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;
}
http://localhost:3000/books/form_create
158
Catalyst::Manual::Tutorial::BasicCRUD
159
160
Catalyst::Manual::Tutorial::BasicCRUD
original action once it is completed, detach does not return. Other than that, the two are
equivalent.
http://localhost:3000/books/list
161
http://localhost:3000/books/list
162
Catalyst::Manual::Tutorial::BasicCRUD
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.
BASIC AUTHENTICATION
165
166
Catalyst::Manual::Tutorial::Authentication
=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
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.
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.
BASIC AUTHENTICATION
171
Configure Authentication
Although __PACKAGE__->config(name => value); is still supported, newer Catalyst applications tend to place all configuration information in myapp.yml and automatically load this information into MyApp->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
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.
174
Catalyst::Manual::Tutorial::Authentication
BASIC AUTHENTICATION
175
176
Catalyst::Manual::Tutorial::Authentication
177
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.
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
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
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.
BASIC AUTHORIZATION
185
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.
BASIC AUTHORIZATION
187
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
http://localhost:3000/books/list
http://localhost:3000/logout
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__->deny_access_unless() or
__PACKAGE__->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__->setup; line.
190
Catalyst::Manual::Tutorial::Authorization
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.
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->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->log->debug("$var is: ".Dumper($var));)) and TT templates ([%
Dumper.dump(book) %].
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
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.
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
201
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");
203
204
Catalyst::Manual::Tutorial::Testing
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__->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
209
title )->label(Title)->size(60);
rating )->label(Rating)->size(1);
authors)->label(Authors)
submit )->value(submit);
=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.
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.
212
Catalyst::Manual::Tutorial::AdvancedCRUD
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
215
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.
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->model(MyAppDB::Book)->create and replaced
it with a single call to $book->populate_from_widget. Note that we still have to call
$book->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->result and storing the output in the stash (if we
dont override the output from $w->process($c->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).
218
Catalyst::Manual::Tutorial::AdvancedCRUD
Try adding a book that validates. Return to the book list and the book you added
should be visible.
219
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:.
[%# 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>
AUTHOR
221
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
224
Catalyst::Manual::Tutorial::Appendices
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).
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
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);
INTO
INTO
INTO
INTO
INTO
INTO
INTO
INTO
INTO
INTO
INTO
227
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
229
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
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
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.
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.
EXAMPLE
235
Thats it.
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;
{
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.