1Catalyst::Manual::TutorUisaelr::C0o2n_tCCraaittbaaulltyyessdtt:BP:aeMsrailncusDa(ol3c:)u:mTeunttoartiiaoln::02_CatalystBasics(3)
2
3
4
6 Catalyst::Manual::Tutorial::02_CatalystBasics - Catalyst Tutorial -
7 Chapter 2: Catalyst Application Development Basics
8
10 This is Chapter 2 of 10 for the Catalyst tutorial.
11
12 Tutorial Overview
13
14 1. Introduction
15
16 2. 02_Catalyst Basics
17
18 3. More Catalyst Basics
19
20 4. Basic CRUD
21
22 5. Authentication
23
24 6. Authorization
25
26 7. Debugging
27
28 8. Testing
29
30 9. Advanced CRUD
31
32 10. Appendices
33
35 In this chapter of the tutorial, we will create a very basic Catalyst
36 web application, demonstrating a number of powerful capabilities, such
37 as:
38
39 · Helper Scripts
40
41 Catalyst helper scripts that can be used to rapidly bootstrap the
42 skeletal structure of an application.
43
44 · MVC
45
46 Model/View/Controller (MVC) provides an architecture that
47 facilitates a clean "separation of control" between the different
48 portions of your application. Given that many other documents cover
49 this subject in detail, MVC will not be discussed in depth here
50 (for an excellent introduction to MVC and general Catalyst
51 concepts, please see Catalyst::Manual::About). In short:
52
53 · Model
54
55 The model usually represents a data store. In most
56 applications, the model equates to the objects that are created
57 from and saved to your SQL database.
58
59 · View
60
61 The view takes model objects and renders them into something
62 for the end user to look at. Normally this involves a template-
63 generation tool that creates HTML for the user's web browser,
64 but it could easily be code that generates other forms such as
65 PDF documents, e-mails, spreadsheets, or even "behind the
66 scenes" formats such as XML and JSON.
67
68 · Controller
69
70 As suggested by its name, the controller takes user requests
71 and routes them to the necessary model and view.
72
73 · ORM
74
75 The use of Object-Relational Mapping (ORM) technology for database
76 access. Specifically, ORM provides an automated and standardized
77 means to persist and restore objects to/from a relational database
78 and will automatically create our Catalyst model for use with a
79 database.
80
81 You can checkout the source code for this example from the catalyst
82 subversion repository as per the instructions in
83 Catalyst::Manual::Tutorial::01_Intro.
84
86 Catalyst provides a number of helper scripts that can be used to
87 quickly flesh out the basic structure of your application. All Catalyst
88 projects begin with the "catalyst.pl" helper (see Catalyst::Helper for
89 more information on helpers). Also note that as of Catalyst 5.7000,
90 you will not have the helper scripts unless you install both
91 Catalyst::Runtime and Catalyst::Devel.
92
93 In this first chapter of the tutorial, use the Catalyst "catalyst.pl"
94 script to initialize the framework for an application called "Hello":
95
96 $ catalyst.pl Hello
97 created "Hello"
98 created "Hello/script"
99 created "Hello/lib"
100 created "Hello/root"
101 ...
102 created "Hello/script/hello_create.pl"
103 Change to application directory and Run "perl Makefile.PL" to make sure your install is complete
104 $ cd Hello
105
106 Note: If you are using Strawberry Perl on Win32, drop the ".pl" from
107 the end of the "catalyst.pl" command and simply use "catalyst Hello".
108
109 The "catalyst.pl" helper script will display the names of the
110 directories and files it creates:
111
112 Changes # Record of application changes
113 lib # Lib directory for your app's Perl modules
114 Hello # Application main code directory
115 Controller # Directory for Controller modules
116 Model # Directory for Models
117 View # Directory for Views
118 Hello.pm # Base application module
119 Makefile.PL # Makefile to build application
120 hello.conf # Application configuration file
121 README # README file
122 root # Equiv of htdocs, dir for templates, css, javascript
123 favicon.ico
124 static # Directory for static files
125 images # Directory for image files used in welcome screen
126 script # Directory for Perl scripts
127 hello_cgi.pl # To run your app as a cgi (not recommended)
128 hello_create.pl # To create models, views, controllers
129 hello_fastcgi.pl # To run app as a fastcgi program
130 hello_server.pl # The normal development server
131 hello_test.pl # Test your app from the command line
132 t # Directory for tests
133 01app.t # Test scaffold
134 02pod.t
135 03podcoverage.t
136
137 Catalyst will "auto-discover" modules in the Controller, Model, and
138 View directories. When you use the hello_create.pl script it will
139 create Perl module scaffolds in those directories, plus test files in
140 the "t" directory. The default location for templates is in the "root"
141 directory. The scripts in the script directory will always start with
142 the lowercased version of your application name. If your app is MaiTai,
143 then the create script would be "maitai_create.pl".
144
145 Though it's too early for any significant celebration, we already have
146 a functioning application. We can use the Catalyst supplied script to
147 start up a development server and view the default Catalyst page in
148 your browser. All scripts in the script directory should be run from
149 the base directory of your application, so change to the Hello
150 directory.
151
152 Run the following command to start up the built-in development web
153 server (make sure you didn't forget the ""cd Hello"" from the previous
154 step):
155
156 Note: The "-r" argument enables reloading on code changes so you don't
157 have to stop and start the server when you update code. See "perldoc
158 script/hello_server.pl" for additional options you might find helpful.
159 Most of the rest of the tutorial will assume that you are using "-r"
160 when you start the development server, but feel free to manually start
161 and stop it (use "Ctrl-C" to break out of the dev server) if you
162 prefer.
163
164 $ script/hello_server.pl -r
165 [debug] Debug messages enabled
166 [debug] Statistics enabled
167 [debug] Loaded plugins:
168 .----------------------------------------------------------------------------.
169 | Catalyst::Plugin::ConfigLoader 0.27 |
170 '----------------------------------------------------------------------------'
171
172 [debug] Loaded dispatcher "Catalyst::Dispatcher"
173 [debug] Loaded engine "Catalyst::Engine::HTTP"
174 [debug] Found home "/home/me/Hello"
175 [debug] Loaded Config "/home/me/Hello/hello.conf"
176 [debug] Loaded components:
177 .-----------------------------------------------------------------+----------.
178 | Class | Type |
179 +-----------------------------------------------------------------+----------+
180 | Hello::Controller::Root | instance |
181 '-----------------------------------------------------------------+----------'
182
183 [debug] Loaded Private actions:
184 .----------------------+--------------------------------------+--------------.
185 | Private | Class | Method |
186 +----------------------+--------------------------------------+--------------+
187 | /default | Hello::Controller::Root | default |
188 | /end | Hello::Controller::Root | end |
189 | /index | Hello::Controller::Root | index |
190 '----------------------+--------------------------------------+--------------'
191
192 [debug] Loaded Path actions:
193 .-------------------------------------+--------------------------------------.
194 | Path | Private |
195 +-------------------------------------+--------------------------------------+
196 | / | /index |
197 | / | /default |
198 '-------------------------------------+--------------------------------------'
199
200 [info] Hello powered by Catalyst 5.80020
201 You can connect to your server at http://debian:3000
202
203 Point your web browser to <http://localhost:3000> (substituting a
204 different hostname or IP address as appropriate) and you should be
205 greeted by the Catalyst welcome screen (if you get some other welcome
206 screen or an "Index" screen, you probably forgot to specify port 3000
207 in your URL). Information similar to the following should be appended
208 to the logging output of the development server:
209
210 [info] *** Request 1 (0.001/s) [23194] [Sat Jan 16 11:09:18 2010] ***
211 [debug] "GET" request for "/" from "127.0.0.1"
212 [debug] Path is "/"
213 [info] Request took 0.004851s (206.143/s)
214 .------------------------------------------------------------+-----------.
215 | Action | Time |
216 +------------------------------------------------------------+-----------+
217 | /index | 0.000395s |
218 | /end | 0.000425s |
219 '------------------------------------------------------------+-----------'
220
221 Note: Press "Ctrl-C" to break out of the development server if
222 necessary.
223
225 The Simplest Way
226 The Root.pm controller is a place to put global actions that usually
227 execute on the root URL. Open the "lib/Hello/Controller/Root.pm" file
228 in your editor. You will see the "index" subroutine, which is
229 responsible for displaying the welcome screen that you just saw in your
230 browser.
231
232 sub index :Path :Args(0) {
233 my ( $self, $c ) = @_;
234
235 # Hello World
236 $c->response->body( $c->welcome_message );
237 }
238
239 Later on you'll want to change that to something more reasonable, such
240 as a "404" message or a redirect, but for now just leave it alone.
241
242 The "$c" here refers to the Catalyst context, which is used to access
243 the Catalyst application. In addition to many other things, the
244 Catalyst context provides access to "response" and "request" objects.
245 (See Catalyst, Catalyst::Response, and Catalyst::Request)
246
247 "$c->response->body" sets the HTTP response (see Catalyst::Response),
248 while "$c->welcome_message" is a special method that returns the
249 welcome message that you saw in your browser.
250
251 The ":Path :Args(0)" after the method name are attributes which
252 determine which URLs will be dispatched to this method. (You might see
253 ":Private" if you are using an older version of Catalyst, but using
254 that with "default" or "index" is currently deprecated. If so, you
255 should also probably upgrade before continuing the tutorial.)
256
257 Some MVC frameworks handle dispatching in a central place. Catalyst, by
258 policy, prefers to handle URL dispatching with attributes on controller
259 methods. There is a lot of flexibility in specifying which URLs to
260 match. This particular method will match all URLs, because it doesn't
261 specify the path (nothing comes after "Path"), but will only accept a
262 URL without any args because of the ":Args(0)".
263
264 The default is to map URLs to controller names, and because of the way
265 that Perl handles namespaces through package names, it is simple to
266 create hierarchical structures in Catalyst. This means that you can
267 create controllers with deeply nested actions in a clean and logical
268 way. For example, the URL "http://hello.com/admin/articles/create" maps
269 to the package "Hello::Controller::Admin::Articles", and the "create"
270 method.
271
272 Add the following subroutine to your "lib/Hello/Controller/Root.pm"
273 file:
274
275 sub hello :Global {
276 my ( $self, $c ) = @_;
277
278 $c->response->body("Hello, World!");
279 }
280
281 TIP: See Appendix 1 for tips on removing the leading spaces when
282 cutting and pasting example code from POD-based documents.
283
284 Here you're sending your own string to the webpage.
285
286 Save the file, and you should notice the following in your server
287 output:
288
289 Saw changes to the following files:
290 - /home/me/Hello/lib/Hello/Controller/Root.pm (modify)
291
292 Attempting to restart the server
293 ...
294 [debug] Loaded Private actions:
295 .----------------------+--------------------------------------+--------------.
296 | Private | Class | Method |
297 +----------------------+--------------------------------------+--------------+
298 | /default | Hello::Controller::Root | default |
299 | /end | Hello::Controller::Root | end |
300 | /index | Hello::Controller::Root | index |
301 | /hello | Hello::Controller::Root | hello |
302 '----------------------+--------------------------------------+--------------'
303
304 [debug] Loaded Path actions:
305 .-------------------------------------+--------------------------------------.
306 | Path | Private |
307 +-------------------------------------+--------------------------------------+
308 | / | /index |
309 | / | /default |
310 | /hello | /hello |
311 '-------------------------------------+--------------------------------------'
312 ...
313
314 Go to <http://localhost:3000/hello> to see "Hello, World!". Also
315 notice that the newly defined 'hello' action is listed under "Loaded
316 Private actions" in the development server debug output.
317
318 Hello, World! Using a View and a Template
319 In the Catalyst world a "View" itself is not a page of XHTML or a
320 template designed to present a page to a browser. Rather, it is the
321 module that determines the type of view -- HTML, pdf, XML, etc. For the
322 thing that generates the content of that view (such as the a Toolkit
323 Template template file), the actual templates go under the "root"
324 directory.
325
326 To create a TT view, run:
327
328 $ script/hello_create.pl view TT TT
329
330 This creates the "lib/Hello/View/TT.pm" module, which is a subclass of
331 "Catalyst::View::TT".
332
333 · The "view" keyword tells the create script that you are creating a
334 view.
335
336 · The first "TT" tells the script to name the View module "TT.pm",
337 which is a commonly used name for TT views. (You can name it
338 anything you want, such as "HTML.pm".)
339
340 · The final "TT" tells Catalyst the type of the view, with "TT"
341 indicating that you want to a Template Toolkit view.
342
343 If you look at "lib/Hello/View/TT.pm" you will find that it only
344 contains a config statement to set the TT extension to ".tt".
345
346 Now that the TT.pm "View" exists, Catalyst will autodiscover it and be
347 able to use it to display the view templates using the "process" method
348 that it inherits from the "Catalyst::View::TT" class.
349
350 Template Toolkit is a very full featured template facility, with
351 excellent documentation at http://template-toolkit.org/
352 <http://template-toolkit.org/>, but since this is not a TT tutorial,
353 we'll stick to only basic TT usage here (and explore some of the more
354 common TT features in later chapters of the tutorial).
355
356 Create a "root/hello.tt" template file (put it in the "root" under the
357 "Hello" directory that is the base of your application). Here is a
358 simple sample:
359
360 <p>
361 This is a TT view template, called '[% template.name %]'.
362 </p>
363
364 [% and %] are markers for the TT parts of the template. Inside you can
365 access Perl variables and classes, and use TT directives. In this case,
366 we're using a special TT variable that defines the name of the template
367 file ("hello.tt"). The rest of the template is normal HTML.
368
369 Change the hello method in "lib/Hello/Controller/Root.pm" to the
370 following:
371
372 sub hello :Global {
373 my ( $self, $c ) = @_;
374
375 $c->stash(template => 'hello.tt');
376 }
377
378 This time, instead of doing "$c->response->body()", you are setting the
379 value of the "template" hash key in the Catalyst "stash", an area for
380 putting information to share with other parts of your application. The
381 "template" key determines which template will be displayed at the end
382 of the request cycle. Catalyst controllers have a default "end" action
383 for all methods which causes the first (or default) view to be rendered
384 (unless there's a "$c->response- >body()" statement). So your template
385 will be magically displayed at the end of your method.
386
387 After saving the file, the development server should automatically
388 restart (again, the tutorial is written to assume that you are using
389 the "-r" option -- manually restart it if you aren't), and look at
390 <http://localhost:3000/hello> in your again. You should see the
391 template that you just made.
392
393 TIP: If you keep the server running with "-r" in a "background window,"
394 don't let that window get totally hidden... if you have an syntax error
395 in your code, the debug server output will contain the error
396 information.
397
398 Note: You will probably run into a variation of the "stash" statement
399 above that looks like:
400
401 $c->stash->{template} = 'hello.tt';
402
403 Although this style is still relatively common, the approach we used
404 previous is becoming more common because it allows you to set multiple
405 stash variables in one line. For example:
406
407 $c->stash(template => 'hello.tt', foo => 'bar',
408 another_thing => 1);
409
410 You can also set multiple stash values with a hashref:
411
412 $c->stash({template => 'hello.tt', foo => 'bar',
413 another_thing => 1});
414
415 Any of these formats work, but the "$c->stash(name => value);" style is
416 growing in popularity -- you may wish to use it all the time (even when
417 you are only setting a single value).
418
420 Create a controller named "Site" by executing the create script:
421
422 $ script/hello_create.pl controller Site
423
424 This will create a "lib/Hello/Controller/Site.pm" file (and a test
425 file). Bring Site.pm up in your editor, and you can see that there's
426 not much there.
427
428 In "lib/Hello/Controller/Site.pm", add the following method:
429
430 sub test :Local {
431 my ( $self, $c ) = @_;
432
433 $c->stash(username => 'John',
434 template => 'site/test.tt');
435 }
436
437 Notice the "Local" attribute on the "test" method. This will cause the
438 "test" action (now that we have assigned an "action type" to the method
439 it appears as a "controller action" to Catalyst) to be executed on the
440 "controller/method" URL, or, in this case, "site/test". We will see
441 additional information on controller actions throughout the rest of the
442 tutorial, but if you are curious take a look at "Actions" in
443 Catalyst::Manual::Intro.
444
445 It's not actually necessary to set the template value as we do here.
446 By default TT will attempt to render a template that follows the naming
447 pattern "controller/method.tt", and we're following that pattern here.
448 However, in other situations you will need to specify the template
449 (such as if you've "forwarded" to the method, or if it doesn't follow
450 the default naming convention).
451
452 We've also put the variable "username" into the stash, for use in the
453 template.
454
455 Make a subdirectory "site" in the "root" directory. Copy the hello.tt
456 file into the directory as "root/site/test.tt", or create a new
457 template file at that location. Include a line like:
458
459 <p>Hello, [% username %]!</p>
460
461 You should see your test.tt file displayed, including the name "John"
462 that you set in the controller.
463
464 Once the server automatically restarts, notice in the server output
465 that "/site/test" is listed in the Loaded Path actions. Go to
466 <http://localhost:3000/site/test> in your browser.
467
469 Gerda Shank, "gerda.shank@gmail.com" Kennedy Clark, "hkclark@gmail.com"
470
471 Please report any errors, issues or suggestions to the author. The
472 most recent version of the Catalyst Tutorial can be found at
473 http://dev.catalyst.perl.org/repos/Catalyst/Catalyst-Manual/5.80/trunk/lib/Catalyst/Manual/Tutorial/
474 <http://dev.catalyst.perl.org/repos/Catalyst/Catalyst-
475 Manual/5.80/trunk/lib/Catalyst/Manual/Tutorial/>.
476
477 Copyright 2006-2008, Kennedy Clark & Gerda Shank, under Creative
478 Commons License (http://creativecommons.org/licenses/by-sa/3.0/us/
479 <http://creativecommons.org/licenses/by-sa/3.0/us/>).
480
481
482
483perl v5.12.0 Cata2l0y1s0t-:0:2M-a1n7ual::Tutorial::02_CatalystBasics(3)