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