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 directories
110 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" or "script/hello_server.pl --help" for
159 additional options you might find helpful. Most of the rest of the
160 tutorial will assume that you are using "-r" when you start the
161 development server, but feel free to manually start and stop it (use
162 "Ctrl-C" to breakout of the dev server) if you 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.30 |
170 '----------------------------------------------------------------------------'
171
172 [debug] Loaded dispatcher "Catalyst::Dispatcher"
173 [debug] Loaded engine "Catalyst::Engine"
174 [debug] Found home "/home/catalyst/Hello"
175 [debug] Loaded Config "/home/catalyst/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.90002
201 HTTP::Server::PSGI: Accepting connections at http://0: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] Hello powered by Catalyst 5.90002
211 HTTP::Server::PSGI: Accepting connections at http://0:3000/
212 [info] *** Request 1 (0.067/s) [19026] [Tue Aug 30 17:24:32 2011] ***
213 [debug] "GET" request for "/" from "192.168.245.2"
214 [debug] Path is "/"
215 [debug] Response Code: 200; Content-Type: text/html; charset=utf-8; Content-Length: 5613
216 [info] Request took 0.040895s (24.453/s)
217 .------------------------------------------------------------+-----------.
218 | Action | Time |
219 +------------------------------------------------------------+-----------+
220 | /index | 0.000916s |
221 | /end | 0.000877s |
222 '------------------------------------------------------------+-----------'
223
224 Note: Press "Ctrl-C" to break out of the development server if
225 necessary.
226
228 The Simplest Way
229 The Root.pm controller is a place to put global actions that usually
230 execute on the root URL. Open the lib/Hello/Controller/Root.pm file in
231 your editor. You will see the "index" subroutine, which is responsible
232 for displaying the welcome screen that you just saw in your browser.
233
234 sub index :Path :Args(0) {
235 my ( $self, $c ) = @_;
236
237 # Hello World
238 $c->response->body( $c->welcome_message );
239 }
240
241 Later on you'll want to change that to something more reasonable, such
242 as a "404" message or a redirect, but for now just leave it alone.
243
244 The "$c" here refers to the Catalyst context, which is used to access
245 the Catalyst application. In addition to many other things, the
246 Catalyst context provides access to "response" and "request" objects.
247 (See Catalyst::Runtime, Catalyst::Response, and Catalyst::Request)
248
249 "$c->response->body" sets the HTTP response (see Catalyst::Response),
250 while "$c->welcome_message" is a special method that returns the
251 welcome message that you saw in your browser.
252
253 The "":Path :Args(0)"" after the method name are attributes which
254 determine which URLs will be dispatched to this method. (You might see
255 ":Private" if you are using an older version of Catalyst, but using
256 that with "default" or "index" is currently deprecated. If so, you
257 should also probably upgrade before continuing the tutorial.)
258
259 Some MVC frameworks handle dispatching in a central place. Catalyst, by
260 policy, prefers to handle URL dispatching with attributes on controller
261 methods. There is a lot of flexibility in specifying which URLs to
262 match. This particular method will match all URLs, because it doesn't
263 specify the path (nothing comes after "Path"), but will only accept a
264 URL without any args because of the ":Args(0)".
265
266 The default is to map URLs to controller names, and because of the way
267 that Perl handles namespaces through package names, it is simple to
268 create hierarchical structures in Catalyst. This means that you can
269 create controllers with deeply nested actions in a clean and logical
270 way. For example, the URL "http://hello.com/admin/articles/create" maps
271 to the package "Hello::Controller::Admin::Articles", and the "create"
272 method.
273
274 While you leave the "script/hello_server.pl -r" command running the
275 development server in one window (don't forget the "-r" at the end!),
276 open another window and add the following subroutine to your
277 lib/Hello/Controller/Root.pm file:
278
279 sub hello :Global {
280 my ( $self, $c ) = @_;
281
282 $c->response->body("Hello, World!");
283 }
284
285 TIP: See Appendix 1 for tips on removing the leading spaces when
286 cutting and pasting example code from POD-based documents.
287
288 Notice in the window running the Development Server that you should get
289 output similar to the following:
290
291 Saw changes to the following files:
292 - /home/catalyst/Hello/lib/Hello/Controller/Root.pm (modify)
293
294 Attempting to restart the server
295 ...
296 [debug] Loaded Private actions:
297 .----------------------+--------------------------------------+--------------.
298 | Private | Class | Method |
299 +----------------------+--------------------------------------+--------------+
300 | /default | Hello::Controller::Root | default |
301 | /end | Hello::Controller::Root | end |
302 | /index | Hello::Controller::Root | index |
303 | /hello | Hello::Controller::Root | hello |
304 '----------------------+--------------------------------------+--------------'
305 ...
306
307 The development server noticed the change in "Hello::Controller::Root"
308 and automatically restarted itself.
309
310 Go to <http://localhost:3000/hello> to see "Hello, World!". Also
311 notice that the newly defined 'hello' action is listed under "Loaded
312 Private actions" in the development server debug output.
313
314 Hello, World! Using a View and a Template
315 In the Catalyst world a "View" itself is not a page of XHTML or a
316 template designed to present a page to a browser. Rather, it is the
317 module that determines the type of view -- HTML, PDF, XML, etc. For the
318 thing that generates the content of that view (such as a Template
319 Toolkit template file), the actual templates go under the "root"
320 directory.
321
322 To create a TT view, run:
323
324 $ script/hello_create.pl view HTML TT
325
326 This creates the lib/Hello/View/HTML.pm module, which is a subclass of
327 Catalyst::View::TT.
328
329 • The "view" keyword tells the create script that you are creating a
330 view.
331
332 • The first argument "HTML" tells the script to name the View module
333 "HTML.pm", which is a commonly used name for TT views. You can
334 name it anything you want, such as "MyView.pm". If you have more
335 than one view, be sure to set the default_view in Hello.pm (See
336 Catalyst::View::TT for more details on setting this).
337
338 • The final "TT" tells Catalyst the type of the view, with "TT"
339 indicating that you want to use a Template Toolkit view.
340
341 If you look at lib/Hello/View/HTML.pm you will find that it only
342 contains a config statement to set the TT extension to ".tt".
343
344 Now that the HTML.pm "View" exists, Catalyst will autodiscover it and
345 be able to use it to display the view templates using the "process"
346 method that it inherits from the Catalyst::View::TT class.
347
348 Template Toolkit is a very full-featured template facility, with
349 excellent documentation at <http://template-toolkit.org/>, but since
350 this is not a TT tutorial, we'll stick to only basic TT usage here (and
351 explore some of the more common TT features in later chapters of the
352 tutorial).
353
354 Create a root/hello.tt template file (put it in the "root" under the
355 "Hello" directory that is the base of your application). Here is a
356 simple sample:
357
358 <p>
359 This is a TT view template, called '[% template.name %]'.
360 </p>
361
362 [% and %] are markers for the TT parts of the template. Inside you can
363 access Perl variables and classes, and use TT directives. In this case,
364 we're using a special TT variable that defines the name of the template
365 file (hello.tt). The rest of the template is normal HTML.
366
367 Change the hello method in lib/Hello/Controller/Root.pm to the
368 following:
369
370 sub hello :Global {
371 my ( $self, $c ) = @_;
372
373 $c->stash(template => 'hello.tt');
374 }
375
376 This time, instead of doing "$c->response->body()", you are setting the
377 value of the "template" hash key in the Catalyst "stash", an area for
378 putting information to share with other parts of your application. The
379 "template" key determines which template will be displayed at the end
380 of the request cycle. Catalyst controllers have a default "end" action
381 for all methods which causes the first (or default) view to be rendered
382 (unless there's a "$c->response->body()" statement). So your template
383 will be magically displayed at the end of your method.
384
385 After saving the file, the development server should automatically
386 restart (again, the tutorial is written to assume that you are using
387 the "-r" option -- manually restart it if you aren't), and look at
388 <http://localhost:3000/hello> in your web browser again. You should see
389 the template that you just created.
390
391 TIP: If you keep the server running with "-r" in a "background window,"
392 don't let that window get totally hidden... if you have a syntax error
393 in your code, the debug server output will contain the error
394 information.
395
396 Note: You will probably run into a variation of the "stash" statement
397 above that looks like:
398
399 $c->stash->{template} = 'hello.tt';
400
401 Although this style is still relatively common, the approach we used
402 previous is becoming more common because it allows you to set multiple
403 stash variables in one line. For example:
404
405 $c->stash(template => 'hello.tt', foo => 'bar',
406 another_thing => 1);
407
408 You can also set multiple stash values with a hashref:
409
410 $c->stash({template => 'hello.tt', foo => 'bar',
411 another_thing => 1});
412
413 Any of these formats work, but the "$c->stash(name => value);" style is
414 growing in popularity -- you may wish to use it all the time (even when
415 you are only setting a single value).
416
418 Create a controller named "Site" by executing the create script:
419
420 $ script/hello_create.pl controller Site
421
422 This will create a lib/Hello/Controller/Site.pm file (and a test file).
423 If you bring Site.pm up in your editor, you can see that there's not
424 much there to see.
425
426 In lib/Hello/Controller/Site.pm, add the following method:
427
428 sub test :Local {
429 my ( $self, $c ) = @_;
430
431 $c->stash(username => 'John',
432 template => 'site/test.tt');
433 }
434
435 Notice the "Local" attribute on the "test" method. This will cause the
436 "test" action (now that we have assigned an "action type" to the method
437 it appears as a "controller action" to Catalyst) to be executed on the
438 "controller/method" URL, or, in this case, "site/test". We will see
439 additional information on controller actions throughout the rest of the
440 tutorial, but if you are curious take a look at "Actions" in
441 Catalyst::Manual::Intro.
442
443 It's not actually necessary to set the template value as we do here.
444 By default TT will attempt to render a template that follows the naming
445 pattern "controller/method.tt", and we're following that pattern here.
446 However, in other situations you will need to specify the template
447 (such as if you've "forwarded" to the method, or if it doesn't follow
448 the default naming convention).
449
450 We've also put the variable "username" into the stash, for use in the
451 template.
452
453 Make a subdirectory "site" in the "root" directory.
454
455 $ mkdir root/site
456
457 Create a new template file in that directory named root/site/test.tt
458 and include a line like:
459
460 <p>Hello, [% username %]!</p>
461
462 Once the server automatically restarts, notice in the server output
463 that "/site/test" is listed in the Loaded Path actions. Go to
464 <http://localhost:3000/site/test> in your browser and you should see
465 your test.tt file displayed, including the name "John" that you set in
466 the controller.
467
468 You can jump to the next chapter of the tutorial here: More Catalyst
469 Basics
470
472 Gerda Shank, "gerda.shank@gmail.com" Kennedy Clark, "hkclark@gmail.com"
473
474 Feel free to contact the author for any errors or suggestions, but the
475 best way to report issues is via the CPAN RT Bug system at
476 <https://rt.cpan.org/Public/Dist/Display.html?Name=Catalyst-Manual>.
477
478 Copyright 2006-2011, Kennedy Clark, under the Creative Commons
479 Attribution Share-Alike License Version 3.0
480 (<https://creativecommons.org/licenses/by-sa/3.0/us/>).
481
482
483
484perl v5.32.1 Cata2l0y2s1t-:0:1M-a2n6ual::Tutorial::02_CatalystBasics(3)