Commit | Line | Data |
3533daff |
1 | =head1 NAME |
2 | |
3ab6187c |
3 | Catalyst::Manual::Tutorial::03_MoreCatalystBasics - Catalyst Tutorial - Chapter 3: More Catalyst Application Development Basics |
3533daff |
4 | |
5 | |
6 | =head1 OVERVIEW |
7 | |
4b4d3884 |
8 | This is B<Chapter 3 of 10> for the Catalyst tutorial. |
3533daff |
9 | |
10 | L<Tutorial Overview|Catalyst::Manual::Tutorial> |
11 | |
12 | =over 4 |
13 | |
14 | =item 1 |
15 | |
3ab6187c |
16 | L<Introduction|Catalyst::Manual::Tutorial::01_Intro> |
3533daff |
17 | |
18 | =item 2 |
19 | |
3ab6187c |
20 | L<Catalyst Basics|Catalyst::Manual::Tutorial::02_CatalystBasics> |
3533daff |
21 | |
22 | =item 3 |
23 | |
3ab6187c |
24 | B<03_More Catalyst Basics> |
3533daff |
25 | |
26 | =item 4 |
27 | |
3ab6187c |
28 | L<Basic CRUD|Catalyst::Manual::Tutorial::04_BasicCRUD> |
3533daff |
29 | |
30 | =item 5 |
31 | |
3ab6187c |
32 | L<Authentication|Catalyst::Manual::Tutorial::05_Authentication> |
3533daff |
33 | |
34 | =item 6 |
35 | |
3ab6187c |
36 | L<Authorization|Catalyst::Manual::Tutorial::06_Authorization> |
3533daff |
37 | |
38 | =item 7 |
39 | |
3ab6187c |
40 | L<Debugging|Catalyst::Manual::Tutorial::07_Debugging> |
3533daff |
41 | |
42 | =item 8 |
43 | |
3ab6187c |
44 | L<Testing|Catalyst::Manual::Tutorial::08_Testing> |
3533daff |
45 | |
46 | =item 9 |
47 | |
3ab6187c |
48 | L<Advanced CRUD|Catalyst::Manual::Tutorial::09_AdvancedCRUD> |
3533daff |
49 | |
50 | =item 10 |
51 | |
3ab6187c |
52 | L<Appendices|Catalyst::Manual::Tutorial::10_Appendices> |
3533daff |
53 | |
54 | =back |
55 | |
56 | |
57 | =head1 DESCRIPTION |
58 | |
a8f4e284 |
59 | This chapter of the tutorial builds on the work done in Chapter 2 to |
60 | explore some features that are more typical of "real world" web |
61 | applications. From this chapter of the tutorial onward, we will be |
62 | building a simple book database application. Although the application |
63 | will be too limited to be of use to anyone, it should provide a basic |
64 | environment where we can explore a variety of features used in virtually |
65 | all web applications. |
3533daff |
66 | |
4d63a0d5 |
67 | You can check out the source code for this example from the Catalyst |
68 | Subversion repository as per the instructions in |
2217b252 |
69 | L<Catalyst::Manual::Tutorial::01_Intro>. |
3533daff |
70 | |
a8f4e284 |
71 | Please take a look at |
01df1cc9 |
72 | L<Catalyst::Manual::Tutorial::01_Intro/STARTING WITH THE TUTORIAL VIRTUAL MACHINE> |
73 | before doing the rest of this tutorial. Although the tutorial should |
74 | work correctly under most any recent version of Perl running on any |
75 | operating system, the tutorial has been written using the virtual |
76 | machine that is available for download. The entire tutorial has been |
77 | tested to be sure it runs correctly in this environment, so it is |
78 | the most trouble-free way to get started with Catalyst. |
a586a09f |
79 | |
3533daff |
80 | |
81 | =head1 CREATE A NEW APPLICATION |
82 | |
1390ef0e |
83 | The remainder of the tutorial will build an application called C<MyApp>. |
84 | First use the Catalyst C<catalyst.pl> script to initialize the framework |
85 | for the C<MyApp> application (make sure you aren't still inside the |
4b4d3884 |
86 | directory of the C<Hello> application from the previous chapter of the |
acbd7bdd |
87 | tutorial or in a directory that already has a "MyApp" subdirectory): |
3533daff |
88 | |
89 | $ catalyst.pl MyApp |
90 | created "MyApp" |
91 | created "MyApp/script" |
92 | created "MyApp/lib" |
93 | created "MyApp/root" |
94 | ... |
95 | created "MyApp/script/myapp_create.pl" |
444d6b27 |
96 | Change to application directory and Run "perl Makefile.PL" to make sure your install is complete |
c988c8b0 |
97 | |
98 | And change the "MyApp" directory the helper created: |
99 | |
3533daff |
100 | $ cd MyApp |
101 | |
4b4d3884 |
102 | This creates a similar skeletal structure to what we saw in Chapter 2 of |
a8f4e284 |
103 | the tutorial, except with C<MyApp> and C<myapp> substituted for C<Hello> |
104 | and C<hello>. (As noted in Chapter 2, omit the ".pl" from the command |
105 | if you are using Strawberry Perl.) |
3533daff |
106 | |
107 | |
108 | =head1 EDIT THE LIST OF CATALYST PLUGINS |
109 | |
a8f4e284 |
110 | One of the greatest benefits of Catalyst is that it has such a large |
111 | library of bases classes and plugins available that you can use easily |
112 | add functionality to your application. Plugins are used to seamlessly |
113 | integrate existing Perl modules into the overall Catalyst framework. In |
114 | general, they do this by adding additional methods to the C<context> |
115 | object (generally written as C<$c>) that Catalyst passes to every |
116 | component throughout the framework. |
f058768a |
117 | |
c988c8b0 |
118 | Take a look at the file C<lib/MyApp.pm> that the helper created above. |
3533daff |
119 | By default, Catalyst enables three plugins/flags: |
120 | |
121 | =over 4 |
122 | |
1390ef0e |
123 | =item * |
3533daff |
124 | |
125 | C<-Debug> Flag |
126 | |
127 | Enables the Catalyst debug output you saw when we started the |
128 | C<script/myapp_server.pl> development server earlier. You can remove |
79a529cc |
129 | this item when you place your application into production. |
3533daff |
130 | |
a8f4e284 |
131 | To be technically correct, it turns out that C<-Debug> is not a plugin, |
c988c8b0 |
132 | but a I<flag>. Although most of the items specified on the C<use |
133 | Catalyst> line of your application class will be plugins, Catalyst |
134 | supports a limited number of flag options (of these, C<-Debug> is the |
135 | most common). See the documentation for |
136 | C<https://metacpan.org/module/Catalyst|Catalyst.pm> to get details on |
137 | other flags (currently C<-Engine>, C<-Home>, C<-Log>, and C<-Stats>). |
3533daff |
138 | |
444d6b27 |
139 | If you prefer, there are several other ways to enable debug output: |
140 | |
141 | =over 4 |
142 | |
143 | =item * |
144 | |
c988c8b0 |
145 | Use the C<$c-E<gt>debug> method on the C<$c> Catalyst context object |
444d6b27 |
146 | |
147 | =item * |
148 | |
149 | The C<-d> option to C<script/myapp_server.pl> |
150 | |
151 | =item * |
152 | |
c988c8b0 |
153 | The C<CATALYST_DEBUG=1> environment variable (or use C<CATALYST_DEBUG=0> |
154 | to temporarily disable debug output). |
444d6b27 |
155 | |
156 | =back |
3533daff |
157 | |
a8f4e284 |
158 | B<TIP>: Depending on your needs, it can be helpful to permanently remove |
159 | C<-Debug> from C<lib/MyApp.pm> and then use the C<-d> option to |
c988c8b0 |
160 | C<script/myapp_server.pl> to re-enable it when needed. We will not be |
161 | using that approach in the tutorial, but feel free to make use of it in |
162 | your own projects. |
3533daff |
163 | |
164 | =item * |
165 | |
2217b252 |
166 | L<Catalyst::Plugin::ConfigLoader> |
3533daff |
167 | |
168 | C<ConfigLoader> provides an automatic way to load configurable |
c010ae0d |
169 | parameters for your application from a central |
2217b252 |
170 | L<Config::General> file (versus having the values |
a8f4e284 |
171 | hard-coded inside your Perl modules). Config::General uses syntax very |
172 | similar to Apache configuration files. We will see how to use this |
173 | feature of Catalyst during the authentication and authorization sections |
c988c8b0 |
174 | (L<Chapter 5|Catalyst::Manual::Tutorial::05_Authentication> and |
175 | L<Chapter 6|Catalyst::Manual::Tutorial::06_Authorization>). |
a8f4e284 |
176 | |
177 | B<IMPORTANT NOTE:> If you are using a version of |
2217b252 |
178 | L<Catalyst::Devel> prior to version 1.06, be aware that |
a8f4e284 |
179 | Catalyst changed the default format from YAML to the more |
180 | straightforward C<Config::General> style. This tutorial uses the newer |
181 | C<myapp.conf> file for C<Config::General>. However, Catalyst supports |
182 | both formats and will automatically use either C<myapp.conf> or |
183 | C<myapp.yml> (or any other format supported by |
2217b252 |
184 | L<Catalyst::Plugin::ConfigLoader> and |
185 | L<Config::Any>). If you are using a version of |
a8f4e284 |
186 | Catalyst::Devel prior to 1.06, you can convert to the newer format by |
187 | simply creating the C<myapp.conf> file manually and deleting |
188 | C<myapp.yml>. The default contents of the C<myapp.conf> you create |
189 | should only consist of one line: |
1435672d |
190 | |
191 | name MyApp |
15e1d0b2 |
192 | |
1390ef0e |
193 | B<TIP>: This script can be useful for converting between configuration |
15e1d0b2 |
194 | formats: |
195 | |
1390ef0e |
196 | perl -Ilib -e 'use MyApp; use Config::General; |
15e1d0b2 |
197 | Config::General->new->save_file("myapp.conf", MyApp->config);' |
198 | |
3533daff |
199 | =item * |
200 | |
2217b252 |
201 | L<Catalyst::Plugin::Static::Simple> |
3533daff |
202 | |
a8f4e284 |
203 | C<Static::Simple> provides an easy way to serve static content, such as |
204 | images and CSS files, from the development server. |
3533daff |
205 | |
206 | =back |
207 | |
a8f4e284 |
208 | For our application, we want to add one new plugin into the mix. To do |
209 | this, edit C<lib/MyApp.pm> (this file is generally referred to as your |
210 | I<application class>) and delete the lines with: |
3533daff |
211 | |
1dc333c7 |
212 | use Catalyst qw/ |
213 | -Debug |
214 | ConfigLoader |
215 | Static::Simple |
216 | /; |
3533daff |
217 | |
1390ef0e |
218 | Then replace it with: |
b411df01 |
219 | |
acbd7bdd |
220 | # Load plugins |
fce83e5f |
221 | use Catalyst qw/ |
1dc333c7 |
222 | -Debug |
223 | ConfigLoader |
224 | Static::Simple |
225 | |
226 | StackTrace |
227 | /; |
1390ef0e |
228 | |
a8f4e284 |
229 | B<Note:> Recent versions of C<Catalyst::Devel> have used a variety of |
230 | techniques to load these plugins/flags. For example, you might see the |
231 | following: |
94d8da41 |
232 | |
acbd7bdd |
233 | __PACKAGE__->setup(qw/-Debug ConfigLoader Static::Simple/); |
94d8da41 |
234 | |
a8f4e284 |
235 | Don't let these variations confuse you -- they all accomplish the same |
94d8da41 |
236 | result. |
237 | |
a8f4e284 |
238 | This tells Catalyst to start using one additional plugin, |
239 | L<Catalyst::Plugin::StackTrace>, to add a stack trace to the standard |
240 | Catalyst "debug screen" (the screen Catalyst sends to your browser when |
241 | an error occurs). Be aware that |
242 | L<StackTrace|Catalyst::Plugin::StackTrace> output appears in your |
243 | browser, not in the console window from which you're running your |
1390ef0e |
244 | application, which is where logging output usually goes. |
3533daff |
245 | |
444d6b27 |
246 | Make sure when adding new plugins you also include them as a new |
a8f4e284 |
247 | dependency within the Makefile.PL file. For example, after adding the |
248 | StackTrace plugin the Makefile.PL should include the following line: |
3b1fa91b |
249 | |
250 | requires 'Catalyst::Plugin::StackTrace'; |
251 | |
252 | |
a8f4e284 |
253 | B<Notes:> |
3533daff |
254 | |
255 | =over 4 |
256 | |
1390ef0e |
257 | =item * |
258 | |
a8f4e284 |
259 | C<__PACKAGE__> is just a shorthand way of referencing the name of the |
260 | package where it is used. Therefore, in C<MyApp.pm>, C<__PACKAGE__> is |
261 | equivalent to C<MyApp>. |
3533daff |
262 | |
1390ef0e |
263 | =item * |
3533daff |
264 | |
a8f4e284 |
265 | You will want to disable L<StackTrace|Catalyst::Plugin::StackTrace> |
266 | before you put your application into production, but it can be helpful |
1390ef0e |
267 | during development. |
3533daff |
268 | |
1390ef0e |
269 | =item * |
3533daff |
270 | |
a8f4e284 |
271 | When specifying plugins, you can omit C<Catalyst::Plugin::> from the |
272 | name. Additionally, you can spread the plugin names across multiple |
444d6b27 |
273 | lines as shown here or place them all on one line. |
cca5cd98 |
274 | |
c988c8b0 |
275 | =item * |
276 | |
277 | If you want to see what the StackTrace error screen looks like, edit |
278 | C<lib/MyApp/Controller/Root.pm> and put a C<die "Oops";> command in the |
279 | C<sub index :Path :Args(0)> method. Then start the development server |
280 | and open C<http://localhost:3000/> in your browser. You should get a |
281 | screen that starts with "Caught exception in |
282 | MyApp::Controller::Root->index" with sections showing a stacktrace, |
283 | information about the Request and Response objects, the stash (something |
284 | we will learn about soon), the applications configuration configuration. |
285 | B<Just don't forget to remove the die before you continue the tutorial!> |
286 | :-) |
287 | |
3533daff |
288 | =back |
289 | |
3533daff |
290 | |
291 | =head1 CREATE A CATALYST CONTROLLER |
292 | |
1390ef0e |
293 | As discussed earlier, controllers are where you write methods that |
294 | interact with user input. Typically, controller methods respond to |
4d63a0d5 |
295 | C<GET> and C<POST> requests from the user's web browser. |
3533daff |
296 | |
297 | Use the Catalyst C<create> script to add a controller for book-related |
298 | actions: |
299 | |
300 | $ script/myapp_create.pl controller Books |
01df1cc9 |
301 | exists "/root/MyApp/script/../lib/MyApp/Controller" |
302 | exists "/root/MyApp/script/../t" |
303 | created "/root/MyApp/script/../lib/MyApp/Controller/Books.pm" |
304 | created "/root/MyApp/script/../t/controller_Books.t" |
3533daff |
305 | |
c988c8b0 |
306 | Then edit C<lib/MyApp/Controller/Books.pm> (as discussed in |
307 | L<Chapter 2|Catalyst::Manual::Tutorial::02_CatalystBasics> of |
1390ef0e |
308 | the Tutorial, Catalyst has a separate directory under C<lib/MyApp> for |
309 | each of the three parts of MVC: C<Model>, C<View>, and C<Controller>) |
310 | and add the following method to the controller: |
3533daff |
311 | |
312 | =head2 list |
313 | |
314 | Fetch all book objects and pass to books/list.tt2 in stash to be displayed |
315 | |
316 | =cut |
1390ef0e |
317 | |
f058768a |
318 | sub list :Local { |
3533daff |
319 | # Retrieve the usual Perl OO '$self' for this object. $c is the Catalyst |
320 | # 'Context' that's used to 'glue together' the various components |
321 | # that make up the application |
322 | my ($self, $c) = @_; |
323 | |
324 | # Retrieve all of the book records as book model objects and store in the |
325 | # stash where they can be accessed by the TT template |
0ed3df53 |
326 | # $c->stash(books => [$c->model('DB::Book')->all]); |
1390ef0e |
327 | # But, for now, use this code until we create the model later |
0ed3df53 |
328 | $c->stash(books => ''); |
1390ef0e |
329 | |
3533daff |
330 | # Set the TT template to use. You will almost always want to do this |
331 | # in your action methods (action methods respond to user input in |
332 | # your controllers). |
61cb69fd |
333 | $c->stash(template => 'books/list.tt2'); |
3533daff |
334 | } |
335 | |
c988c8b0 |
336 | B<TIP>: See L<Appendix 1|Catalyst::Manual::Tutorial::10_Appendices> for |
337 | tips on removing the leading spaces when cutting and pasting example |
338 | code from POD-based documents. |
3533daff |
339 | |
a8f4e284 |
340 | Programmers experienced with object-oriented Perl should recognize |
341 | C<$self> as a reference to the object where this method was called. On |
342 | the other hand, C<$c> will be new to many Perl programmers who have not |
c988c8b0 |
343 | used Catalyst before. This is the "Catalyst Context object", and it is |
344 | automatically passed as the second argument to all Catalyst action |
345 | methods. It is used to pass information between components and provide |
346 | access to Catalyst and plugin functionality. |
347 | |
348 | Catalyst Controller actions are regular Perl methods, but they make use |
349 | of attributes (the "C<:Local>" next to the "C<sub list>" in the code |
350 | above) to provide additional information to the Catalyst dispatcher |
351 | logic (note that there can be an optional space between the colon and |
352 | the attribute name; you will see attributes written both ways). Most |
353 | Catalyst Controllers use one of five action types: |
0416017e |
354 | |
355 | =over 4 |
356 | |
357 | =item * |
358 | |
a8f4e284 |
359 | B<:Private> -- Use C<:Private> for methods that you want to make into an |
c988c8b0 |
360 | action, but you do not want Catalyst to directly expose the method to |
a8f4e284 |
361 | your users. Catalyst will not map C<:Private> methods to a URI. Use |
362 | them for various sorts of "special" methods (the C<begin>, C<auto>, etc. |
363 | discussed below) or for methods you want to be able to C<forward> or |
c988c8b0 |
364 | C<detach> to. (If the method is a "plain old method" that you |
a8f4e284 |
365 | don't want to be an action at all, then just define the method without |
366 | any attribute -- you can call it in your code, but the Catalyst |
c988c8b0 |
367 | dispatcher will ignore it. You will also have to manually include |
368 | C<$c> if you want access to the context object in the method vs. having |
369 | Catalyst automatically include C<$c> in the argument list for you |
370 | if it's a full-fledged action.) |
0416017e |
371 | |
8fd01b0e |
372 | There are five types of "special" built-in C<:Private> actions: |
245b41d1 |
373 | C<begin>, C<end>, C<default>, C<index>, and C<auto>. |
0416017e |
374 | |
26c9cad5 |
375 | =over 4 |
376 | |
0416017e |
377 | =item * |
378 | |
379 | With C<begin>, C<end>, C<default>, C<index> private actions, only the |
380 | most specific action of each type will be called. For example, if you |
381 | define a C<begin> action in your controller it will I<override> a |
382 | C<begin> action in your application/root controller -- I<only> the |
383 | action in your controller will be called. |
384 | |
385 | =item * |
386 | |
387 | Unlike the other actions where only a single method is called for each |
388 | request, I<every> auto action along the chain of namespaces will be |
389 | called. Each C<auto> action will be called I<from the application/root |
390 | controller down through the most specific class>. |
391 | |
392 | =back |
393 | |
394 | =item * |
395 | |
a8f4e284 |
396 | B<:Path> -- C<:Path> actions let you map a method to an explicit URI |
397 | path. For example, "C<:Path('list')>" in |
398 | C<lib/MyApp/Controller/Books.pm> would match on the URL |
399 | C<http://localhost:3000/books/list>, but "C<:Path('/list')>" would match |
400 | on C<http://localhost:3000/list> (because of the leading slash). You |
401 | can use C<:Args()> to specify how many arguments an action should |
402 | accept. See L<Catalyst::Manual::Intro/Action_types> for more |
444d6b27 |
403 | information and examples. |
0416017e |
404 | |
405 | =item * |
406 | |
a8f4e284 |
407 | B<:Local> -- C<:Local> is merely a shorthand for |
245b41d1 |
408 | "C<:Path('_name_of_method_')>". For example, these are equivalent: |
c988c8b0 |
409 | "C<sub create_book :Local {...}>" and |
410 | "C<sub create_book :Path('create_book') {...}>". |
245b41d1 |
411 | |
412 | =item * |
413 | |
a8f4e284 |
414 | B<:Global> -- C<:Global> is merely a shorthand for |
245b41d1 |
415 | "C<:Path('/_name_of_method_')>". For example, these are equivalent: |
a8f4e284 |
416 | "C<sub create_book :Global {...}>" and "C<sub create_book |
417 | :Path('/create_book') {...}>". |
245b41d1 |
418 | |
419 | =item * |
420 | |
a8f4e284 |
421 | B<:Chained> -- Newer Catalyst applications tend to use the Chained |
422 | dispatch form of action types because of its power and flexibility. It |
c988c8b0 |
423 | allows a series of controller methods to be automatically dispatched |
424 | when servicing a single user request. See |
425 | L<Catalyst::Manual::Tutorial::04_BasicCRUD> and |
426 | L<Catalyst::DispatchType::Chained> for more information on chained |
427 | actions. |
0416017e |
428 | |
429 | =back |
430 | |
c988c8b0 |
431 | You should refer to L<Catalyst::Manual::Intro/Action-types> for |
a8f4e284 |
432 | additional information and for coverage of some lesser-used action types |
433 | not discussed here (C<Regex> and C<LocalRegex>). |
3533daff |
434 | |
435 | |
436 | =head1 CATALYST VIEWS |
437 | |
c988c8b0 |
438 | As mentioned in L<Chapter 2|Catalyst::Manual::Tutorial::02_CatalystBasics> |
439 | of the tutorial, views are where you render output, typically for |
440 | display in the user's web browser (but can generate other types of |
441 | output such as PDF or JSON). The code in C<lib/MyApp/View> selects the |
442 | I<type> of view to use, with the actual rendering template found in the |
443 | C<root> directory. As with virtually every aspect of Catalyst, options |
444 | abound when it comes to the specific view technology you adopt inside |
445 | your application. However, most Catalyst applications use the Template |
446 | Toolkit, known as TT (for more information on TT, see |
447 | L<http://www.template-toolkit.org>). Other somewhat popular view |
448 | technologies include Mason (L<http://www.masonhq.com> and |
449 | L<http://www.masonbook.com>) and L<HTML::Template> |
450 | (L<http://html-template.sourceforge.net>). |
1390ef0e |
451 | |
452 | |
453 | =head2 Create a Catalyst View |
3533daff |
454 | |
a8f4e284 |
455 | When using TT for the Catalyst view, the main helper script is |
c988c8b0 |
456 | L<Catalyst::Helper::View::TT>. You may also come across references to |
457 | L<Catalyst::Helper::View::TTSite>, but its use is now deprecated. |
1390ef0e |
458 | |
c988c8b0 |
459 | For our book application, enter the following command to enable the |
460 | C<TT> style of view rendering: |
3533daff |
461 | |
1edbdee6 |
462 | $ script/myapp_create.pl view HTML TT |
01df1cc9 |
463 | exists "/root/MyApp/script/../lib/MyApp/View" |
464 | exists "/root/MyApp/script/../t" |
465 | created "/root/MyApp/script/../lib/MyApp/View/HTML.pm" |
466 | created "/root/MyApp/script/../t/view_HTML.t" |
1edbdee6 |
467 | |
c988c8b0 |
468 | This creates a view called C<HTML> (the first argument) in a file called |
469 | C<HTML.pm> that uses L<Catalyst::View::TT> (the second argument) as the |
470 | "rendering engine". |
471 | |
472 | It is now up to you to decide how you want to structure your view |
473 | layout. For the tutorial, we will start with a very simple TT template |
474 | to initially demonstrate the concepts, but quickly migrate to a more |
475 | typical "wrapper page" type of configuration (where the "wrapper" |
476 | controls the overall "look and feel" of your site from a single file or |
477 | set of files). |
1edbdee6 |
478 | |
a8f4e284 |
479 | Edit C<lib/MyApp/View/HTML.pm> and you should see something similar to |
480 | the following: |
3533daff |
481 | |
c062293d |
482 | __PACKAGE__->config( |
483 | TEMPLATE_EXTENSION => '.tt', |
484 | render_die => 1, |
485 | ); |
3533daff |
486 | |
1390ef0e |
487 | And update it to match: |
488 | |
489 | __PACKAGE__->config( |
490 | # Change default TT extension |
491 | TEMPLATE_EXTENSION => '.tt2', |
c062293d |
492 | render_die => 1, |
493 | ); |
494 | |
495 | This changes the default extension for Template Toolkit from '.tt' to |
496 | '.tt2'. |
497 | |
a8f4e284 |
498 | You can also configure components in your application class. For |
c988c8b0 |
499 | example, Edit C<lib/MyApp.pm> and you should see the default |
500 | configuration above the call to C<_PACKAGE__-E<gt>setup> (your defaults |
501 | could be different depending on the version of Catalyst you are using): |
502 | |
503 | __PACKAGE__->config( |
504 | name => 'MyApp', |
505 | # Disable deprecated behavior needed by old applications |
506 | disable_component_resolution_regex_fallback => 1, |
507 | ); |
c062293d |
508 | |
c062293d |
509 | |
01df1cc9 |
510 | Change this to match the following (insert a new |
511 | C<__PACKAGE__-E<gt>config> below the existing statement): |
c062293d |
512 | |
513 | __PACKAGE__->config( |
c988c8b0 |
514 | name => 'MyApp', |
515 | # Disable deprecated behavior needed by old applications |
516 | disable_component_resolution_regex_fallback => 1, |
01df1cc9 |
517 | ); |
518 | __PACKAGE__->config( |
c988c8b0 |
519 | # Configure the view |
c062293d |
520 | 'View::HTML' => { |
521 | #Set the location for TT files |
522 | INCLUDE_PATH => [ |
523 | __PACKAGE__->path_to( 'root', 'src' ), |
1390ef0e |
524 | ], |
c062293d |
525 | }, |
1390ef0e |
526 | ); |
3533daff |
527 | |
a8f4e284 |
528 | This changes the base directory for your template files from C<root> to |
529 | C<root/src>. |
1390ef0e |
530 | |
a8f4e284 |
531 | Please stick with the settings above for the duration of the tutorial, |
532 | but feel free to use whatever options you desire in your applications |
533 | (as with most things Perl, there's more than one way to do it...). |
1390ef0e |
534 | |
a8f4e284 |
535 | B<Note:> We will use C<root/src> as the base directory for our template |
536 | files, with a full naming convention of |
537 | C<root/src/_controller_name_/_action_name_.tt2>. Another popular option |
538 | is to use C<root/> as the base (with a full filename pattern of |
acbd7bdd |
539 | C<root/_controller_name_/_action_name_.tt2>). |
540 | |
a8f4e284 |
541 | |
1390ef0e |
542 | =head2 Create a TT Template Page |
3533daff |
543 | |
544 | First create a directory for book-related TT templates: |
545 | |
1390ef0e |
546 | $ mkdir -p root/src/books |
3533daff |
547 | |
548 | Then create C<root/src/books/list.tt2> in your editor and enter: |
549 | |
c988c8b0 |
550 | [% # This is a TT comment. -%] |
3533daff |
551 | |
c988c8b0 |
552 | [%- # Provide a title -%] |
3533daff |
553 | [% META title = 'Book List' -%] |
554 | |
c988c8b0 |
555 | [% # Note That the '-' at the beginning or end of TT code -%] |
556 | [% # "chomps" the whitespace/newline at that end of the -%] |
557 | [% # output (use View Source in browser to see the effect) -%] |
558 | |
559 | [% # Some basic HTML with a loop to display books -%] |
3533daff |
560 | <table> |
561 | <tr><th>Title</th><th>Rating</th><th>Author(s)</th></tr> |
562 | [% # Display each book in a table row %] |
563 | [% FOREACH book IN books -%] |
564 | <tr> |
565 | <td>[% book.title %]</td> |
566 | <td>[% book.rating %]</td> |
a46b474e |
567 | <td></td> |
3533daff |
568 | </tr> |
569 | [% END -%] |
570 | </table> |
571 | |
572 | As indicated by the inline comments above, the C<META title> line uses |
1390ef0e |
573 | TT's META feature to provide a title to the "wrapper" that we will |
c988c8b0 |
574 | create later (and essentially does nothing at the moment). Meanwhile, |
575 | the C<FOREACH> loop iterates through each C<book> model object and |
576 | prints the C<title> and C<rating> fields. |
3533daff |
577 | |
4d63a0d5 |
578 | The C<[%> and C<%]> tags are used to delimit Template Toolkit code. TT |
579 | supports a wide variety of directives for "calling" other files, |
580 | looping, conditional logic, etc. In general, TT simplifies the usual |
444d6b27 |
581 | range of Perl operators down to the single dot (".") operator. This |
4d63a0d5 |
582 | applies to operations as diverse as method calls, hash lookups, and list |
c988c8b0 |
583 | index values (see L<Template::Manual::Variables> for details and |
584 | examples). In addition to the usual L<Template> module Pod |
4d63a0d5 |
585 | documentation, you can access the TT manual at |
8c848468 |
586 | L<https://metacpan.org/module/Template::Manual>. |
3533daff |
587 | |
a8f4e284 |
588 | B<TIP:> While you can build all sorts of complex logic into your TT |
589 | templates, you should in general keep the "code" part of your templates |
590 | as simple as possible. If you need more complex logic, create helper |
591 | methods in your model that abstract out a set of code into a single call |
592 | from your TT template. (Note that the same is true of your controller |
593 | logic as well -- complex sections of code in your controllers should |
c988c8b0 |
594 | often be pulled out and placed into your model objects.) In |
595 | L<Chapter 4|Catalyst::Manual::Tutorial::04_BasicCRUD> of the tutorial we |
596 | will explore some extremely helpful and powerful features of |
597 | L<DBIx::Class> that allow you to pull code out of your views and |
598 | controllers and place it where it rightfully belongs in a model class. |
1390ef0e |
599 | |
600 | |
601 | =head2 Test Run The Application |
602 | |
603 | To test your work so far, first start the development server: |
604 | |
f058768a |
605 | $ script/myapp_server.pl -r |
1390ef0e |
606 | |
a8f4e284 |
607 | Then point your browser to L<http://localhost:3000> and you should still |
608 | get the Catalyst welcome page. Next, change the URL in your browser to |
609 | L<http://localhost:3000/books/list>. If you have everything working so |
610 | far, you should see a web page that displays nothing other than our |
611 | column headers for "Title", "Rating", and "Author(s)" -- we will not see |
612 | any books until we get the database and model working below. |
1390ef0e |
613 | |
614 | If you run into problems getting your application to run correctly, it |
615 | might be helpful to refer to some of the debugging techniques covered in |
fce83e5f |
616 | the L<Debugging|Catalyst::Manual::Tutorial::07_Debugging> chapter of the |
1390ef0e |
617 | tutorial. |
3533daff |
618 | |
619 | |
620 | =head1 CREATE A SQLITE DATABASE |
621 | |
622 | In this step, we make a text file with the required SQL commands to |
a8f4e284 |
623 | create a database table and load some sample data. We will use SQLite |
624 | (L<http://www.sqlite.org>), a popular database that is lightweight and |
625 | easy to use. Be sure to get at least version 3. Open C<myapp01.sql> in |
626 | your editor and enter: |
3533daff |
627 | |
628 | -- |
629 | -- Create a very simple database to hold book and author information |
630 | -- |
f058768a |
631 | PRAGMA foreign_keys = ON; |
3b1fa91b |
632 | CREATE TABLE book ( |
3533daff |
633 | id INTEGER PRIMARY KEY, |
634 | title TEXT , |
635 | rating INTEGER |
636 | ); |
3b1fa91b |
637 | -- 'book_author' is a many-to-many join table between books & authors |
638 | CREATE TABLE book_author ( |
b66dd084 |
639 | book_id INTEGER REFERENCES book(id) ON DELETE CASCADE ON UPDATE CASCADE, |
640 | author_id INTEGER REFERENCES author(id) ON DELETE CASCADE ON UPDATE CASCADE, |
3533daff |
641 | PRIMARY KEY (book_id, author_id) |
642 | ); |
3b1fa91b |
643 | CREATE TABLE author ( |
3533daff |
644 | id INTEGER PRIMARY KEY, |
645 | first_name TEXT, |
646 | last_name TEXT |
647 | ); |
648 | --- |
649 | --- Load some sample data |
650 | --- |
3b1fa91b |
651 | INSERT INTO book VALUES (1, 'CCSP SNRS Exam Certification Guide', 5); |
652 | INSERT INTO book VALUES (2, 'TCP/IP Illustrated, Volume 1', 5); |
653 | INSERT INTO book VALUES (3, 'Internetworking with TCP/IP Vol.1', 4); |
654 | INSERT INTO book VALUES (4, 'Perl Cookbook', 5); |
655 | INSERT INTO book VALUES (5, 'Designing with Web Standards', 5); |
656 | INSERT INTO author VALUES (1, 'Greg', 'Bastien'); |
657 | INSERT INTO author VALUES (2, 'Sara', 'Nasseh'); |
658 | INSERT INTO author VALUES (3, 'Christian', 'Degu'); |
659 | INSERT INTO author VALUES (4, 'Richard', 'Stevens'); |
660 | INSERT INTO author VALUES (5, 'Douglas', 'Comer'); |
661 | INSERT INTO author VALUES (6, 'Tom', 'Christiansen'); |
662 | INSERT INTO author VALUES (7, 'Nathan', 'Torkington'); |
663 | INSERT INTO author VALUES (8, 'Jeffrey', 'Zeldman'); |
664 | INSERT INTO book_author VALUES (1, 1); |
665 | INSERT INTO book_author VALUES (1, 2); |
666 | INSERT INTO book_author VALUES (1, 3); |
667 | INSERT INTO book_author VALUES (2, 4); |
668 | INSERT INTO book_author VALUES (3, 5); |
669 | INSERT INTO book_author VALUES (4, 6); |
670 | INSERT INTO book_author VALUES (4, 7); |
671 | INSERT INTO book_author VALUES (5, 8); |
3533daff |
672 | |
3533daff |
673 | Then use the following command to build a C<myapp.db> SQLite database: |
674 | |
675 | $ sqlite3 myapp.db < myapp01.sql |
676 | |
677 | If you need to create the database more than once, you probably want to |
678 | issue the C<rm myapp.db> command to delete the database before you use |
1390ef0e |
679 | the C<sqlite3 myapp.db E<lt> myapp01.sql> command. |
3533daff |
680 | |
681 | Once the C<myapp.db> database file has been created and initialized, you |
682 | can use the SQLite command line environment to do a quick dump of the |
683 | database contents: |
684 | |
685 | $ sqlite3 myapp.db |
c988c8b0 |
686 | SQLite version 3.7.3 |
3533daff |
687 | Enter ".help" for instructions |
f058768a |
688 | Enter SQL statements terminated with a ";" |
3b1fa91b |
689 | sqlite> select * from book; |
3533daff |
690 | 1|CCSP SNRS Exam Certification Guide|5 |
691 | 2|TCP/IP Illustrated, Volume 1|5 |
692 | 3|Internetworking with TCP/IP Vol.1|4 |
693 | 4|Perl Cookbook|5 |
694 | 5|Designing with Web Standards|5 |
695 | sqlite> .q |
696 | $ |
697 | |
698 | Or: |
699 | |
3b1fa91b |
700 | $ sqlite3 myapp.db "select * from book" |
3533daff |
701 | 1|CCSP SNRS Exam Certification Guide|5 |
702 | 2|TCP/IP Illustrated, Volume 1|5 |
703 | 3|Internetworking with TCP/IP Vol.1|4 |
704 | 4|Perl Cookbook|5 |
705 | 5|Designing with Web Standards|5 |
706 | |
707 | As with most other SQL tools, if you are using the full "interactive" |
708 | environment you need to terminate your SQL commands with a ";" (it's not |
709 | required if you do a single SQL statement on the command line). Use |
710 | ".q" to exit from SQLite from the SQLite interactive mode and return to |
711 | your OS command prompt. |
712 | |
a8f4e284 |
713 | Please note that here we have chosen to use 'singular' table names. This |
714 | is because the default inflection code for older versions of |
715 | L<DBIx::Class::Schema::Loader> does NOT handle plurals. There has been |
716 | much philosophical discussion on whether table names should be plural or |
717 | singular. There is no one correct answer, as long as one makes a choice |
718 | and remains consistent with it. If you prefer plural table names (e.g. |
719 | you think that they are easier to read) then see the documentation in |
658b8c29 |
720 | L<DBIx::Class::Schema::Loader::Base/naming> (version 0.05 or greater). |
3b1fa91b |
721 | |
a8f4e284 |
722 | For using other databases, such as PostgreSQL or MySQL, see |
3ab6187c |
723 | L<Appendix 2|Catalyst::Manual::Tutorial::10_Appendices>. |
3533daff |
724 | |
acbd7bdd |
725 | |
8a472b34 |
726 | =head1 DATABASE ACCESS WITH DBIx::Class |
3533daff |
727 | |
a8f4e284 |
728 | Catalyst can be used with virtually any form of datastore available via |
c988c8b0 |
729 | Perl. For example, L<Catalyst::Model::DBI> can be used to access |
730 | databases through the traditional Perl L<DBI> interface or you can use a |
731 | model to access files of any type on the filesystem. However, most |
732 | Catalyst applications use some form of object-relational mapping (ORM) |
733 | technology to create objects associated with tables in a relational |
734 | database, and Matt Trout's L<DBIx::Class> (abbreviated as "DBIC") is the |
735 | usual choice (this tutorial will use L<DBIx::Class>). |
a8f4e284 |
736 | |
737 | Although DBIx::Class has included support for a C<create=dynamic> mode |
738 | to automatically read the database structure every time the application |
739 | starts, its use is no longer recommended. While it can make for |
740 | "flashy" demos, the use of the C<create=static> mode we use below can be |
741 | implemented just as quickly and provides many advantages (such as the |
742 | ability to add your own methods to the overall DBIC framework, a |
c988c8b0 |
743 | technique that we see in |
744 | L<Chapter 4|Catalyst::Manual::Tutorial::04_BasicCRUD>). |
3533daff |
745 | |
1390ef0e |
746 | |
01df1cc9 |
747 | =head2 Create Static DBIx::Class Schema Files |
27909ed4 |
748 | |
01df1cc9 |
749 | B<Note:> If you are not following along in the Tutorial Virtual Machine, |
750 | please be sure that you have version 1.27 or higher of DBD::SQLite and |
751 | version 0.39 or higher of Catalyst::Model::DBIC::Schema. (The Tutorial |
752 | VM already has versions that are known to work.) You can get your |
753 | currently installed version numbers with the following commands. |
27909ed4 |
754 | |
c988c8b0 |
755 | $ perl -MCatalyst::Model::DBIC::Schema\ 999 |
c988c8b0 |
756 | $ perl -MDBD::SQLite\ 999 |
27909ed4 |
757 | |
a8f4e284 |
758 | Before you continue, make sure your C<myapp.db> database file is in the |
759 | application's topmost directory. Now use the model helper with the |
760 | C<create=static> option to read the database with |
2217b252 |
761 | L<DBIx::Class::Schema::Loader> and |
27909ed4 |
762 | automatically build the required files for us: |
3533daff |
763 | |
4ab6212d |
764 | $ script/myapp_create.pl model DB DBIC::Schema MyApp::Schema \ |
b66dd084 |
765 | create=static dbi:SQLite:myapp.db \ |
766 | on_connect_do="PRAGMA foreign_keys = ON" |
01df1cc9 |
767 | exists "/root/MyApp/script/../lib/MyApp/Model" |
768 | exists "/root/MyApp/script/../t" |
769 | Dumping manual schema for MyApp::Schema to directory /root/MyApp/script/../lib ... |
27909ed4 |
770 | Schema dump completed. |
01df1cc9 |
771 | created "/root/MyApp/script/../lib/MyApp/Model/DB.pm" |
772 | created "/root/MyApp/script/../t/model_DB.t" |
3533daff |
773 | |
a8f4e284 |
774 | Please note the '\' above. Depending on your environment, you might be |
775 | able to cut and paste the text as shown or need to remove the '\' |
fce83e5f |
776 | character to that the command is all on a single line. |
3b1fa91b |
777 | |
27909ed4 |
778 | The C<script/myapp_create.pl> command breaks down like this: |
779 | |
780 | =over 4 |
781 | |
782 | =item * |
783 | |
a8f4e284 |
784 | C<DB> is the name of the model class to be created by the helper in |
c988c8b0 |
785 | the C<lib/MyApp/Model> directory. |
27909ed4 |
786 | |
787 | =item * |
788 | |
c988c8b0 |
789 | C<DBIC::Schema> is the type of the model to create. This equates to |
790 | L<Catalyst::Model::DBIC::Schema>, the standard way to use a DBIC-based |
791 | model inside of Catalyst. |
27909ed4 |
792 | |
793 | =item * |
794 | |
795 | C<MyApp::Schema> is the name of the DBIC schema file written to |
796 | C<lib/MyApp/Schema.pm>. |
797 | |
798 | =item * |
799 | |
c988c8b0 |
800 | C<create=static> causes L<DBIx::Class::Schema::Loader> to load the |
801 | schema as it runs and then write that information out into |
802 | C<lib/MyApp/Schema.pm> and files under the C<lib/MyApp/Schema> |
803 | directory. |
27909ed4 |
804 | |
805 | =item * |
806 | |
a8f4e284 |
807 | C<dbi:SQLite:myapp.db> is the standard DBI connect string for use with |
808 | SQLite. |
27909ed4 |
809 | |
f058768a |
810 | =item * |
811 | |
a8f4e284 |
812 | And finally, the C<on_connect_do> string requests that |
2217b252 |
813 | L<DBIx::Class::Schema::Loader> create |
a8f4e284 |
814 | foreign key relationships for us (this is not needed for databases such |
815 | as PostgreSQL and MySQL, but is required for SQLite). If you take a look |
816 | at C<lib/MyApp/Model/DB.pm>, you will see that the SQLite pragma is |
c988c8b0 |
817 | propagated to the Model, so that SQLite's recent (and optional) foreign |
a8f4e284 |
818 | key enforcement is enabled at the start of every database connection. |
f058768a |
819 | |
27909ed4 |
820 | =back |
821 | |
01df1cc9 |
822 | |
a8f4e284 |
823 | If you look in the C<lib/MyApp/Schema.pm> file, you will find that it |
824 | only contains a call to the C<load_namespaces> method. You will also |
825 | find that C<lib/MyApp> contains a C<Schema> subdirectory, which then has |
826 | a subdirectory called "Result". This "Result" subdirectory then has |
827 | files named according to each of the tables in our simple database |
828 | (C<Author.pm>, C<BookAuthor.pm>, and C<Book.pm>). These three files are |
c988c8b0 |
829 | called "Result Classes" (or |
830 | "L<ResultSource Classes|DBIx::Class::ResultSource>") in DBIx::Class |
831 | nomenclature. Although the Result Class files are named after tables in |
832 | our database, the classes correspond to the I<row-level data> that is |
833 | returned by DBIC (more on this later, especially in |
3ab6187c |
834 | L<Catalyst::Manual::Tutorial::04_BasicCRUD/EXPLORING THE POWER OF DBIC>). |
27909ed4 |
835 | |
a8f4e284 |
836 | The idea with the Result Source files created under |
837 | C<lib/MyApp/Schema/Result> by the C<create=static> option is to only |
838 | edit the files below the C<# DO NOT MODIFY THIS OR ANYTHING ABOVE!> |
839 | warning. If you place all of your changes below that point in the file, |
840 | you can regenerate the automatically created information at the top of |
841 | each file should your database structure get updated. |
842 | |
843 | Also note the "flow" of the model information across the various files |
844 | and directories. Catalyst will initially load the model from |
845 | C<lib/MyApp/Model/DB.pm>. This file contains a reference to |
846 | C<lib/MyApp/Schema.pm>, so that file is loaded next. Finally, the call |
847 | to C<load_namespaces> in C<Schema.pm> will load each of the "Result |
848 | Class" files from the C<lib/MyApp/Schema/Result> subdirectory. The |
849 | final outcome is that Catalyst will dynamically create three |
850 | table-specific Catalyst models every time the application starts (you |
851 | can see these three model files listed in the debug output generated |
27909ed4 |
852 | when you launch the application). |
853 | |
c988c8b0 |
854 | Additionally, the C<lib/MyApp/Schema.pm> model can easily be loaded |
855 | outside of Catalyst, for example, in command-line utilities and/or cron |
856 | jobs. C<lib/MyApp/Model/DB.pm> provides a very thin "bridge" between |
857 | Catalyst this external database model. Once you see how we can add some |
858 | powerful features to our DBIC model in |
859 | L<Chapter 4|Catalyst::Manual::Tutorial::04_BasicCRUD>, the elegance |
860 | of this approach will start to become more obvious. |
861 | |
a8f4e284 |
862 | B<NOTE:> Older versions of |
2217b252 |
863 | L<Catalyst::Model::DBIC::Schema> use the |
a8f4e284 |
864 | deprecated DBIx::Class C<load_classes> technique instead of the newer |
865 | C<load_namespaces>. For new applications, please try to use |
866 | C<load_namespaces> since it more easily supports a very useful DBIC |
867 | technique called "ResultSet Classes." If you need to convert an |
868 | existing application from "load_classes" to "load_namespaces," you can |
b66dd084 |
869 | use this process to automate the migration, but first make sure you have |
870 | version C<0.39> of L<Catalyst::Model::DBIC::Schema> and |
871 | L<DBIx::Class::Schema::Loader> version C<0.05000> or later. |
27909ed4 |
872 | |
b66dd084 |
873 | $ # Re-run the helper to upgrade for you |
27909ed4 |
874 | $ script/myapp_create.pl model DB DBIC::Schema MyApp::Schema \ |
b66dd084 |
875 | create=static naming=current use_namespaces=1 \ |
876 | dbi:SQLite:myapp.db \ |
877 | on_connect_do="PRAGMA foreign_keys = ON" |
dc9a0503 |
878 | |
f058768a |
879 | |
1390ef0e |
880 | =head1 ENABLE THE MODEL IN THE CONTROLLER |
881 | |
a8f4e284 |
882 | Open C<lib/MyApp/Controller/Books.pm> and un-comment the model code we |
acbd7bdd |
883 | left disabled earlier so that your version matches the following (un- |
a8f4e284 |
884 | comment the line containing C<[$c-E<gt>model('DB::Book')-E<gt>all]> and |
885 | delete the next 2 lines): |
1390ef0e |
886 | |
887 | =head2 list |
888 | |
889 | Fetch all book objects and pass to books/list.tt2 in stash to be displayed |
890 | |
891 | =cut |
892 | |
f058768a |
893 | sub list :Local { |
1390ef0e |
894 | # Retrieve the usual Perl OO '$self' for this object. $c is the Catalyst |
895 | # 'Context' that's used to 'glue together' the various components |
896 | # that make up the application |
897 | my ($self, $c) = @_; |
898 | |
f058768a |
899 | # Retrieve all of the book records as book model objects and store |
900 | # in the stash where they can be accessed by the TT template |
0ed3df53 |
901 | $c->stash(books => [$c->model('DB::Book')->all]); |
1390ef0e |
902 | |
903 | # Set the TT template to use. You will almost always want to do this |
904 | # in your action methods (action methods respond to user input in |
905 | # your controllers). |
61cb69fd |
906 | $c->stash(template => 'books/list.tt2'); |
1390ef0e |
907 | } |
908 | |
a8f4e284 |
909 | B<TIP>: You may see the C<$c-E<gt>model('DB::Book')> un-commented above |
910 | written as C<$c-E<gt>model('DB')-E<gt>resultset('Book')>. The two are |
911 | equivalent. Either way, C<$c-E<gt>model> returns a |
2217b252 |
912 | L<DBIx::Class::ResultSet> which handles queries |
a8f4e284 |
913 | against the database and iterating over the set of results that is |
c93b5eaa |
914 | returned. |
915 | |
a8f4e284 |
916 | We are using the C<-E<gt>all> to fetch all of the books. DBIC supports |
917 | a wide variety of more advanced operations to easily do things like |
918 | filtering and sorting the results. For example, the following could be |
919 | used to sort the results by descending title: |
c93b5eaa |
920 | |
3b1fa91b |
921 | $c->model('DB::Book')->search({}, {order_by => 'title DESC'}); |
c93b5eaa |
922 | |
a8f4e284 |
923 | Some other examples are provided in |
924 | L<DBIx::Class::Manual::Cookbook/Complex WHERE clauses>, with additional |
925 | information found at L<DBIx::Class::ResultSet/search>, |
c988c8b0 |
926 | L<DBIx::Class::Manual::FAQ/Searching>, L<DBIx::Class::Manual::Intro> and |
2217b252 |
927 | L<Catalyst::Model::DBIC::Schema>. |
1390ef0e |
928 | |
929 | |
930 | =head2 Test Run The Application |
3533daff |
931 | |
c988c8b0 |
932 | First, let's enable an environment variable that causes L<DBIx::Class> |
933 | to dump the SQL statements used to access the database. This is a |
934 | helpful trick when you are trying to debug your database-oriented code. |
935 | Press C<Ctrl-C> to break out of the development server and enter: |
3533daff |
936 | |
937 | $ export DBIC_TRACE=1 |
c988c8b0 |
938 | $ script/myapp_server.pl -r |
f33d1dd7 |
939 | |
4d63a0d5 |
940 | This assumes you are using bash as your shell -- adjust accordingly if |
3533daff |
941 | you are using a different shell (for example, under tcsh, use |
942 | C<setenv DBIC_TRACE 1>). |
943 | |
d0496197 |
944 | B<NOTE:> You can also set this in your code using |
3533daff |
945 | C<$class-E<gt>storage-E<gt>debug(1);>. See |
946 | L<DBIx::Class::Manual::Troubleshooting> for details (including options |
a8f4e284 |
947 | to log to a file instead of displaying to the Catalyst development |
948 | server log). |
3533daff |
949 | |
1390ef0e |
950 | Then launch the Catalyst development server. The log output should |
951 | display something like: |
3533daff |
952 | |
f058768a |
953 | $ script/myapp_server.pl -r |
3533daff |
954 | [debug] Debug messages enabled |
1390ef0e |
955 | [debug] Statistics enabled |
3533daff |
956 | [debug] Loaded plugins: |
957 | .----------------------------------------------------------------------------. |
01df1cc9 |
958 | | Catalyst::Plugin::ConfigLoader 0.30 | |
a467a714 |
959 | | Catalyst::Plugin::StackTrace 0.11 | |
3533daff |
960 | '----------------------------------------------------------------------------' |
961 | |
962 | [debug] Loaded dispatcher "Catalyst::Dispatcher" |
01df1cc9 |
963 | [debug] Loaded engine "Catalyst::Engine" |
964 | [debug] Found home "/root/MyApp" |
965 | [debug] Loaded Config "/root/MyApp/myapp.conf" |
3533daff |
966 | [debug] Loaded components: |
967 | .-----------------------------------------------------------------+----------. |
968 | | Class | Type | |
969 | +-----------------------------------------------------------------+----------+ |
970 | | MyApp::Controller::Books | instance | |
971 | | MyApp::Controller::Root | instance | |
d0496197 |
972 | | MyApp::Model::DB | instance | |
3b1fa91b |
973 | | MyApp::Model::DB::Author | class | |
974 | | MyApp::Model::DB::Book | class | |
975 | | MyApp::Model::DB::BookAuthor | class | |
1edbdee6 |
976 | | MyApp::View::HTML | instance | |
3533daff |
977 | '-----------------------------------------------------------------+----------' |
978 | |
979 | [debug] Loaded Private actions: |
980 | .----------------------+--------------------------------------+--------------. |
981 | | Private | Class | Method | |
982 | +----------------------+--------------------------------------+--------------+ |
983 | | /default | MyApp::Controller::Root | default | |
984 | | /end | MyApp::Controller::Root | end | |
1390ef0e |
985 | | /index | MyApp::Controller::Root | index | |
3533daff |
986 | | /books/index | MyApp::Controller::Books | index | |
987 | | /books/list | MyApp::Controller::Books | list | |
988 | '----------------------+--------------------------------------+--------------' |
989 | |
990 | [debug] Loaded Path actions: |
991 | .-------------------------------------+--------------------------------------. |
992 | | Path | Private | |
993 | +-------------------------------------+--------------------------------------+ |
1390ef0e |
994 | | / | /default | |
995 | | / | /index | |
996 | | /books | /books/index | |
3533daff |
997 | | /books/list | /books/list | |
998 | '-------------------------------------+--------------------------------------' |
999 | |
f058768a |
1000 | [info] MyApp powered by Catalyst 5.80020 |
01df1cc9 |
1001 | HTTP::Server::PSGI: Accepting connections at http://0:3000 |
3533daff |
1002 | |
a8f4e284 |
1003 | B<NOTE:> Be sure you run the C<script/myapp_server.pl> command from the |
1004 | 'base' directory of your application, not inside the C<script> directory |
1005 | itself or it will not be able to locate the C<myapp.db> database file. |
1006 | You can use a fully qualified or a relative path to locate the database |
1007 | file, but we did not specify that when we ran the model helper earlier. |
3533daff |
1008 | |
1009 | Some things you should note in the output above: |
1010 | |
1011 | =over 4 |
1012 | |
1390ef0e |
1013 | =item * |
3533daff |
1014 | |
c988c8b0 |
1015 | L<Catalyst::Model::DBIC::Schema> dynamically created three model |
1016 | classes, one to represent each of the three tables in our database |
a8f4e284 |
1017 | (C<MyApp::Model::DB::Author>, C<MyApp::Model::DB::BookAuthor>, and |
1018 | C<MyApp::Model::DB::Book>). |
3533daff |
1019 | |
1390ef0e |
1020 | =item * |
3533daff |
1021 | |
1022 | The "list" action in our Books controller showed up with a path of |
1023 | C</books/list>. |
1024 | |
1025 | =back |
1026 | |
1027 | Point your browser to L<http://localhost:3000> and you should still get |
1028 | the Catalyst welcome page. |
1029 | |
1030 | Next, to view the book list, change the URL in your browser to |
1031 | L<http://localhost:3000/books/list>. You should get a list of the five |
1390ef0e |
1032 | books loaded by the C<myapp01.sql> script above without any formatting. |
1033 | The rating for each book should appear on each row, but the "Author(s)" |
191dee29 |
1034 | column will still be blank (we will fill that in later). |
3533daff |
1035 | |
a8f4e284 |
1036 | Also notice in the output of the C<script/myapp_server.pl> that |
c988c8b0 |
1037 | L<DBIx::Class> used the following SQL to retrieve the data: |
3533daff |
1038 | |
fce83e5f |
1039 | SELECT me.id, me.title, me.rating FROM book me |
3533daff |
1040 | |
1041 | because we enabled DBIC_TRACE. |
1042 | |
0c51850e |
1043 | You now have the beginnings of a simple but workable web application. |
a8f4e284 |
1044 | Continue on to future sections and we will develop the application more |
1045 | fully. |
3533daff |
1046 | |
1047 | |
1390ef0e |
1048 | =head1 CREATE A WRAPPER FOR THE VIEW |
1049 | |
a8f4e284 |
1050 | When using TT, you can (and should) create a wrapper that will literally |
1051 | wrap content around each of your templates. This is certainly useful as |
1052 | you have one main source for changing things that will appear across |
1053 | your entire site/application instead of having to edit many individual |
1054 | files. |
1390ef0e |
1055 | |
1056 | |
1edbdee6 |
1057 | =head2 Configure HTML.pm For The Wrapper |
1390ef0e |
1058 | |
a8f4e284 |
1059 | In order to create a wrapper, you must first edit your TT view and tell |
1060 | it where to find your wrapper file. |
1390ef0e |
1061 | |
a8f4e284 |
1062 | Edit your TT view in C<lib/MyApp/View/HTML.pm> and change it to match |
1063 | the following: |
1390ef0e |
1064 | |
1065 | __PACKAGE__->config( |
1066 | # Change default TT extension |
1067 | TEMPLATE_EXTENSION => '.tt2', |
1068 | # Set the location for TT files |
1069 | INCLUDE_PATH => [ |
c2dfb562 |
1070 | MyApp->path_to( 'root', 'src' ), |
1390ef0e |
1071 | ], |
1072 | # Set to 1 for detailed timer stats in your HTML as comments |
1073 | TIMER => 0, |
1074 | # This is your wrapper template located in the 'root/src' |
1075 | WRAPPER => 'wrapper.tt2', |
1076 | ); |
1077 | |
1078 | |
1079 | =head2 Create the Wrapper Template File and Stylesheet |
1080 | |
1081 | Next you need to set up your wrapper template. Basically, you'll want |
a8f4e284 |
1082 | to take the overall layout of your site and put it into this file. For |
1083 | the tutorial, open C<root/src/wrapper.tt2> and input the following: |
1390ef0e |
1084 | |
1085 | <?xml version="1.0" encoding="UTF-8"?> |
c988c8b0 |
1086 | <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" [%# |
1087 | %]"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> |
1390ef0e |
1088 | <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en"> |
1089 | <head> |
1090 | <title>[% template.title or "My Catalyst App!" %]</title> |
1091 | <link rel="stylesheet" href="[% c.uri_for('/static/css/main.css') %]" /> |
1092 | </head> |
1093 | |
1094 | <body> |
1095 | <div id="outer"> |
1096 | <div id="header"> |
1097 | [%# Your logo could go here -%] |
1098 | <img src="[% c.uri_for('/static/images/btn_88x31_powered.png') %]" /> |
1099 | [%# Insert the page title -%] |
1100 | <h1>[% template.title or site.title %]</h1> |
1101 | </div> |
1102 | |
1103 | <div id="bodyblock"> |
1104 | <div id="menu"> |
1105 | Navigation: |
1106 | <ul> |
1107 | <li><a href="[% c.uri_for('/books/list') %]">Home</a></li> |
c988c8b0 |
1108 | <li><a href="[% c.uri_for('/') |
1109 | %]" title="Catalyst Welcome Page">Welcome</a></li> |
1390ef0e |
1110 | </ul> |
1111 | </div><!-- end menu --> |
1112 | |
1113 | <div id="content"> |
1114 | [%# Status and error messages %] |
1115 | <span class="message">[% status_msg %]</span> |
1116 | <span class="error">[% error_msg %]</span> |
1117 | [%# This is where TT will stick all of your template's contents. -%] |
1118 | [% content %] |
1119 | </div><!-- end content --> |
1120 | </div><!-- end bodyblock --> |
1121 | |
1122 | <div id="footer">Copyright (c) your name goes here</div> |
c2dfb562 |
1123 | </div><!-- end outer --> |
1390ef0e |
1124 | |
1125 | </body> |
1126 | </html> |
1127 | |
1128 | Notice the status and error message sections in the code above: |
1129 | |
1130 | <span class="status">[% status_msg %]</span> |
1131 | <span class="error">[% error_msg %]</span> |
1132 | |
1133 | If we set either message in the Catalyst stash (e.g., |
a8f4e284 |
1134 | C<$c-E<gt>stash-E<gt>{status_msg} = 'Request was successful!'>) it will |
1135 | be displayed whenever any view used by that request is rendered. The |
1136 | C<message> and C<error> CSS styles can be customized to suit your needs |
1137 | in the C<root/static/css/main.css> file we create below. |
1390ef0e |
1138 | |
a8f4e284 |
1139 | B<Notes:> |
1390ef0e |
1140 | |
1141 | =over 4 |
1142 | |
1143 | =item * |
1144 | |
a8f4e284 |
1145 | The Catalyst stash only lasts for a single HTTP request. If you need to |
1146 | retain information across requests you can use |
c988c8b0 |
1147 | L<Catalyst::Plugin::Session> (we will use Catalyst sessions in the |
1148 | Authentication chapter of the tutorial). |
1390ef0e |
1149 | |
1150 | =item * |
1151 | |
a8f4e284 |
1152 | Although it is beyond the scope of this tutorial, you may wish to use a |
1153 | JavaScript or AJAX tool such as jQuery (L<http://www.jquery.com>) or |
1390ef0e |
1154 | Dojo (L<http://www.dojotoolkit.org>). |
1155 | |
1156 | =back |
1157 | |
1158 | |
1159 | =head3 Create A Basic Stylesheet |
1160 | |
1161 | First create a central location for stylesheets under the static |
1162 | directory: |
1163 | |
1164 | $ mkdir root/static/css |
1165 | |
1166 | Then open the file C<root/static/css/main.css> (the file referenced in |
1167 | the stylesheet href link of our wrapper above) and add the following |
1168 | content: |
1169 | |
1170 | #header { |
1171 | text-align: center; |
1172 | } |
1173 | #header h1 { |
1174 | margin: 0; |
1175 | } |
1176 | #header img { |
1177 | float: right; |
1178 | } |
1179 | #footer { |
1180 | text-align: center; |
1181 | font-style: italic; |
1182 | padding-top: 20px; |
1183 | } |
1184 | #menu { |
1185 | font-weight: bold; |
1186 | background-color: #ddd; |
1187 | } |
1188 | #menu ul { |
1189 | list-style: none; |
1190 | float: left; |
1191 | margin: 0; |
1192 | padding: 0 0 50% 5px; |
1193 | font-weight: normal; |
1194 | background-color: #ddd; |
1195 | width: 100px; |
1196 | } |
1197 | #content { |
1198 | margin-left: 120px; |
1199 | } |
1200 | .message { |
1201 | color: #390; |
1202 | } |
1203 | .error { |
1204 | color: #f00; |
1205 | } |
1206 | |
1207 | You may wish to check out a "CSS Framework" like Emastic |
a8f4e284 |
1208 | (L<http://code.google.com/p/emastic/>) as a way to quickly provide lots |
1209 | of high-quality CSS functionality. |
1390ef0e |
1210 | |
1211 | |
1212 | =head2 Test Run The Application |
1213 | |
a8f4e284 |
1214 | Hit "Reload" in your web browser and you should now see a formatted |
1215 | version of our basic book list. (Again, the development server should |
1216 | have automatically restarted when you made changes to |
1217 | C<lib/MyApp/View/HTML.pm>. If you are not using the "-r" option, you |
1218 | will need to hit C<Ctrl-C> and manually restart it. Also note that the |
1219 | development server does I<NOT> need to restart for changes to the TT and |
1220 | static files we created and edited in the C<root> directory -- those |
1221 | updates are handled on a per-request basis.) |
f058768a |
1222 | |
a8f4e284 |
1223 | Although our wrapper and stylesheet are obviously very simple, you |
1224 | should see how it allows us to control the overall look of an entire |
1225 | website from two central files. To add new pages to the site, just |
1226 | provide a template that fills in the C<content> section of our wrapper |
1227 | template -- the wrapper will provide the overall feel of the page. |
1390ef0e |
1228 | |
1229 | |
a46b474e |
1230 | =head2 Updating the Generated DBIx::Class Result Class Files |
3533daff |
1231 | |
a8f4e284 |
1232 | If you take a look at the Schema files automatically generated by |
1233 | L<DBIx::Class::Schema::Loader>, you will see that it has already defined |
1234 | C<has_many> and C<belongs_to> relationships on each side of our foreign |
1235 | keys. For example, take a look at C<lib/MyApp/Schema/Result/Book.pm> and |
1236 | notice the following code: |
f058768a |
1237 | |
1238 | =head1 RELATIONS |
c6b49844 |
1239 | |
f058768a |
1240 | =head2 book_authors |
c6b49844 |
1241 | |
f058768a |
1242 | Type: has_many |
c6b49844 |
1243 | |
f058768a |
1244 | Related object: L<MyApp::Schema::Result::BookAuthor> |
c6b49844 |
1245 | |
f058768a |
1246 | =cut |
c6b49844 |
1247 | |
f058768a |
1248 | __PACKAGE__->has_many( |
1249 | "book_authors", |
1250 | "MyApp::Schema::Result::BookAuthor", |
1251 | { "foreign.book_id" => "self.id" }, |
c988c8b0 |
1252 | { cascade_copy => 0, cascade_delete => 0 }, |
f058768a |
1253 | ); |
1254 | |
a8f4e284 |
1255 | Each C<Book> "has_many" C<book_authors>, where C<BookAuthor> is the |
1256 | many-to-many table that allows each Book to have multiple Authors, and |
c988c8b0 |
1257 | each Author to have multiple books. The arguments to C<has_many> are: |
f058768a |
1258 | |
1259 | =over 4 |
1260 | |
1261 | =item * |
1262 | |
a8f4e284 |
1263 | C<book_authors> - The name for this relationship. DBIC will create an |
1264 | accessor on the C<Books> DBIC Row object with this name. |
f058768a |
1265 | |
1266 | =item * |
1267 | |
a8f4e284 |
1268 | C<MyApp::Schema::Result::BookAuthor> - The name of the DBIC model class |
1269 | referenced by this C<has_many> relationship. |
f058768a |
1270 | |
1271 | =item * |
1272 | |
a8f4e284 |
1273 | C<foreign.book_id> - C<book_id> is the name of the foreign key column in |
1274 | the I<foreign> table that points back to this table. |
f058768a |
1275 | |
1276 | =item * |
1277 | |
a8f4e284 |
1278 | C<self.id> - C<id> is the name of the column in I<this> table that is |
1279 | referenced by the foreign key. |
f058768a |
1280 | |
1281 | =back |
1282 | |
a8f4e284 |
1283 | See L<DBIx::Class::Relationship/has_many> for additional information. |
1284 | Note that you might see a "hand coded" version of the C<has_many> |
1285 | relationship above expressed as: |
f058768a |
1286 | |
1287 | __PACKAGE__->has_many( |
1288 | "book_authors", |
1289 | "MyApp::Schema::Result::BookAuthor", |
1290 | "book_id", |
1291 | ); |
1292 | |
a8f4e284 |
1293 | Where the third argument is simply the name of the column in the foreign |
1294 | table. However, the hashref syntax used by |
1295 | L<DBIx::Class::Schema::Loader> is more flexible (for example, it can |
c988c8b0 |
1296 | handle "multi-column foreign keys"). |
f058768a |
1297 | |
a8f4e284 |
1298 | B<Note:> If you are using older versions of SQLite and related DBIC |
1299 | tools, you will need to manually define your C<has_many> and |
1300 | C<belongs_to> relationships. We recommend upgrading to the versions |
1301 | specified above. :-) |
f058768a |
1302 | |
a8f4e284 |
1303 | Have a look at C<lib/MyApp/Schema/Result/BookAuthor.pm> and notice that |
1304 | there is a C<belongs_to> relationship defined that acts as the "mirror |
1305 | image" to the C<has_many> relationship we just looked at above: |
f058768a |
1306 | |
1307 | =head1 RELATIONS |
c6b49844 |
1308 | |
f058768a |
1309 | =head2 book |
c6b49844 |
1310 | |
f058768a |
1311 | Type: belongs_to |
c6b49844 |
1312 | |
f058768a |
1313 | Related object: L<MyApp::Schema::Result::Book> |
c6b49844 |
1314 | |
f058768a |
1315 | =cut |
c6b49844 |
1316 | |
f058768a |
1317 | __PACKAGE__->belongs_to( |
1318 | "book", |
1319 | "MyApp::Schema::Result::Book", |
1320 | { id => "book_id" }, |
c988c8b0 |
1321 | { join_type => "LEFT", on_delete => "CASCADE", on_update => "CASCADE" }, |
f058768a |
1322 | ); |
1323 | |
a8f4e284 |
1324 | The arguments are similar, but see |
f058768a |
1325 | L<DBIx::Class::Relationship/belongs_to> for the details. |
f33d1dd7 |
1326 | |
a8f4e284 |
1327 | Although recent versions of SQLite and L<DBIx::Class::Schema::Loader> |
1328 | automatically handle the C<has_many> and C<belongs_to> relationships, |
7040a6cd |
1329 | C<many_to_many> relationship bridges (not technically a relationship) |
a8f4e284 |
1330 | currently need to be manually inserted. To add a C<many_to_many> |
1331 | relationship bridge, first edit C<lib/MyApp/Schema/Result/Book.pm> and |
1332 | add the following text below the C<# You can replace this text...> |
1333 | comment: |
3533daff |
1334 | |
3533daff |
1335 | # many_to_many(): |
1336 | # args: |
7040a6cd |
1337 | # 1) Name of relationship bridge, DBIC will create accessor with this name |
1390ef0e |
1338 | # 2) Name of has_many() relationship this many_to_many() is shortcut for |
1339 | # 3) Name of belongs_to() relationship in model class of has_many() above |
3533daff |
1340 | # You must already have the has_many() defined to use a many_to_many(). |
fce83e5f |
1341 | __PACKAGE__->many_to_many(authors => 'book_authors', 'author'); |
3533daff |
1342 | |
a8f4e284 |
1343 | B<Note:> Be careful to put this code I<above> the C<1;> at the end of |
1344 | the file. As with any Perl package, we need to end the last line with a |
1345 | statement that evaluates to C<true>. This is customarily done with |
3533daff |
1346 | C<1;> on a line by itself. |
1347 | |
7040a6cd |
1348 | The C<many_to_many> relationship bridge is optional, but it makes it |
a8f4e284 |
1349 | easier to map a book to its collection of authors. Without it, we would |
1350 | have to "walk" through the C<book_author> table as in |
1351 | C<$book-E<gt>book_author-E<gt>first-E<gt>author-E<gt>last_name> (we will |
1352 | see examples on how to use DBIx::Class objects in your code soon, but |
1353 | note that because C<$book-E<gt>book_author> can return multiple authors, |
1354 | we have to use C<first> to display a single author). C<many_to_many> |
1355 | allows us to use the shorter |
1356 | C<$book-E<gt>author-E<gt>first-E<gt>last_name>. Note that you cannot |
1357 | define a C<many_to_many> relationship bridge without also having the |
5a82cb36 |
1358 | C<has_many> relationship in place. |
3533daff |
1359 | |
a8f4e284 |
1360 | Then edit C<lib/MyApp/Schema/Result/Author.pm> and add the reverse |
1361 | C<many_to_many> relationship bridge for C<Author> as follows (again, be |
1362 | careful to put in above the C<1;> but below the C<# DO NOT MODIFY THIS |
1363 | OR ANYTHING ABOVE!> comment): |
3533daff |
1364 | |
3533daff |
1365 | # many_to_many(): |
1366 | # args: |
7040a6cd |
1367 | # 1) Name of relationship bridge, DBIC will create accessor with this name |
3533daff |
1368 | # 2) Name of has_many() relationship this many_to_many() is shortcut for |
1390ef0e |
1369 | # 3) Name of belongs_to() relationship in model class of has_many() above |
3533daff |
1370 | # You must already have the has_many() defined to use a many_to_many(). |
fce83e5f |
1371 | __PACKAGE__->many_to_many(books => 'book_authors', 'book'); |
3533daff |
1372 | |
f058768a |
1373 | |
1390ef0e |
1374 | =head2 Run The Application |
3533daff |
1375 | |
4d63a0d5 |
1376 | Run the Catalyst development server script with the C<DBIC_TRACE> option |
1377 | (it might still be enabled from earlier in the tutorial, but here is an |
f33d1dd7 |
1378 | alternate way to specify the trace option just in case): |
3533daff |
1379 | |
f058768a |
1380 | $ DBIC_TRACE=1 script/myapp_server.pl -r |
3533daff |
1381 | |
1390ef0e |
1382 | Make sure that the application loads correctly and that you see the |
a8f4e284 |
1383 | three dynamically created model class (one for each of the Result |
1384 | Classes we created). |
3533daff |
1385 | |
a8f4e284 |
1386 | Then hit the URL L<http://localhost:3000/books/list> with your browser |
f33d1dd7 |
1387 | and be sure that the book list still displays correctly. |
3533daff |
1388 | |
c988c8b0 |
1389 | B<Note:> You will not see the authors yet because the view isn't taking |
1390 | advantage of these relationships. Read on to the next section where we |
1391 | update the template to do that. |
3533daff |
1392 | |
1393 | |
1394 | =head1 UPDATING THE VIEW |
1395 | |
a8f4e284 |
1396 | Let's add a new column to our book list page that takes advantage of the |
1397 | relationship information we manually added to our schema files in the |
1398 | previous section. Edit C<root/src/books/list.tt2> and replace the |
1399 | "empty" table cell "<td></td>" with the following: |
3533daff |
1400 | |
acbd7bdd |
1401 | ... |
3533daff |
1402 | <td> |
fce83e5f |
1403 | [% # NOTE: See Chapter 4 for a better way to do this! -%] |
3533daff |
1404 | [% # First initialize a TT variable to hold a list. Then use a TT FOREACH -%] |
1405 | [% # loop in 'side effect notation' to load just the last names of the -%] |
6d97b973 |
1406 | [% # authors into the list. Note that the 'push' TT vmethod doesn't return -%] |
3533daff |
1407 | [% # a value, so nothing will be printed here. But, if you have something -%] |
6d97b973 |
1408 | [% # in TT that does return a value and you don't want it printed, you -%] |
1409 | [% # 1) assign it to a bogus value, or -%] |
1410 | [% # 2) use the CALL keyword to call it and discard the return value. -%] |
3533daff |
1411 | [% tt_authors = [ ]; |
1412 | tt_authors.push(author.last_name) FOREACH author = book.authors %] |
1413 | [% # Now use a TT 'virtual method' to display the author count in parens -%] |
1414 | [% # Note the use of the TT filter "| html" to escape dangerous characters -%] |
1415 | ([% tt_authors.size | html %]) |
1416 | [% # Use another TT vmethod to join & print the names & comma separators -%] |
1417 | [% tt_authors.join(', ') | html %] |
1418 | </td> |
acbd7bdd |
1419 | ... |
3533daff |
1420 | |
a8f4e284 |
1421 | B<IMPORTANT NOTE:> Again, you should keep as much "logic code" as |
1422 | possible out of your views. This kind of logic belongs in your model |
1423 | (the same goes for controllers -- keep them as "thin" as possible and |
1424 | push all of the "complicated code" out to your model objects). Avoid |
1425 | code like you see in the previous example -- we are only using it here |
1426 | to show some extra features in TT until we get to the more advanced |
1427 | model features we will see in Chapter 4 (see |
fce83e5f |
1428 | L<Catalyst::Manual::Tutorial::04_BasicCRUD/EXPLORING THE POWER OF DBIC>). |
1429 | |
a8f4e284 |
1430 | Then hit "Reload" in your browser (note that you don't need to reload |
1431 | the development server or use the C<-r> option when updating TT |
1432 | templates) and you should now see the number of authors each book has |
1433 | along with a comma-separated list of the authors' last names. (If you |
1434 | didn't leave the development server running from the previous step, you |
1435 | will obviously need to start it before you can refresh your browser |
1436 | window.) |
1390ef0e |
1437 | |
1438 | If you are still running the development server with C<DBIC_TRACE> |
1439 | enabled, you should also now see five more C<SELECT> statements in the |
1440 | debug output (one for each book as the authors are being retrieved by |
a46b474e |
1441 | DBIx::Class): |
3533daff |
1442 | |
fce83e5f |
1443 | SELECT me.id, me.title, me.rating FROM book me: |
3b1fa91b |
1444 | SELECT author.id, author.first_name, author.last_name FROM book_author me |
fce83e5f |
1445 | JOIN author author ON author.id = me.author_id WHERE ( me.book_id = ? ): '1' |
3b1fa91b |
1446 | SELECT author.id, author.first_name, author.last_name FROM book_author me |
fce83e5f |
1447 | JOIN author author ON author.id = me.author_id WHERE ( me.book_id = ? ): '2' |
3b1fa91b |
1448 | SELECT author.id, author.first_name, author.last_name FROM book_author me |
fce83e5f |
1449 | JOIN author author ON author.id = me.author_id WHERE ( me.book_id = ? ): '3' |
3b1fa91b |
1450 | SELECT author.id, author.first_name, author.last_name FROM book_author me |
fce83e5f |
1451 | JOIN author author ON author.id = me.author_id WHERE ( me.book_id = ? ): '4' |
3b1fa91b |
1452 | SELECT author.id, author.first_name, author.last_name FROM book_author me |
fce83e5f |
1453 | JOIN author author ON author.id = me.author_id WHERE ( me.book_id = ? ): '5' |
c2dfb562 |
1454 | |
a8f4e284 |
1455 | Also note in C<root/src/books/list.tt2> that we are using "| html", a |
1456 | type of TT filter, to escape characters such as E<lt> and E<gt> to < |
1457 | and > and avoid various types of dangerous hacks against your |
1458 | application. In a real application, you would probably want to put "| |
1459 | html" at the end of every field where a user has control over the |
1460 | information that can appear in that field (and can therefore inject |
1461 | markup or code if you don't "neutralize" those fields). In addition to |
1462 | "| html", Template Toolkit has a variety of other useful filters that |
c988c8b0 |
1463 | can found in the documentation for L<Template::Filters>. (While we are |
1464 | on the topic of security and escaping of dangerous values, one of the |
1465 | advantages of using tools like DBIC for database access or |
1466 | L<HTML::FormFu> for form management [see |
1467 | L<Chapter 9|Catalyst::Manual::Tutorial::09_AdvancedCRUD::09_FormFu> |
1468 | is that they automatically handle most escaping for you and therefore |
1469 | dramatically increase the security of your app.) |
3533daff |
1470 | |
1471 | |
1390ef0e |
1472 | =head1 RUNNING THE APPLICATION FROM THE COMMAND LINE |
1473 | |
a8f4e284 |
1474 | In some situations, it can be useful to run your application and display |
1475 | a page without using a browser. Catalyst lets you do this using the |
1476 | C<scripts/myapp_test.pl> script. Just supply the URL you wish to |
1477 | display and it will run that request through the normal controller |
1478 | dispatch logic and use the appropriate view to render the output |
1479 | (obviously, complex pages may dump a lot of text to your terminal |
01df1cc9 |
1480 | window). For example, if C<Ctrl+C> out of the development server |
1481 | and then type: |
1390ef0e |
1482 | |
1483 | $ script/myapp_test.pl "/books/list" |
1484 | |
1485 | You should get the same text as if you visited |
1486 | L<http://localhost:3000/books/list> with the normal development server |
c988c8b0 |
1487 | and asked your browser to view the page source. You can even pipe this |
1488 | HTML text output to a text-based browser using a command like: |
1489 | |
1490 | $ script/myapp_test.pl "/books/list" | lynx -stdin |
1491 | |
1492 | And you should see a fully rendered text-based view of your page. (If |
1493 | you are following along in Debian 6, type |
1494 | C<sudo aptitude -y install lynx> to install lynx.) If you do start |
1495 | lynx, you can use the "Q" key to quit. |
3533daff |
1496 | |
1390ef0e |
1497 | |
1498 | =head1 OPTIONAL INFORMATION |
1499 | |
4b4d3884 |
1500 | B<NOTE: The rest of this chapter of the tutorial is optional. You can |
3ab6187c |
1501 | skip to Chapter 4, L<Basic CRUD|Catalyst::Manual::Tutorial::04_BasicCRUD>, |
3533daff |
1502 | if you wish.> |
1503 | |
acbd7bdd |
1504 | |
8a472b34 |
1505 | =head2 Using 'RenderView' for the Default View |
1390ef0e |
1506 | |
1507 | Once your controller logic has processed the request from a user, it |
1508 | forwards processing to your view in order to generate the appropriate |
3533daff |
1509 | response output. Catalyst uses |
2217b252 |
1510 | L<Catalyst::Action::RenderView> by default |
a8f4e284 |
1511 | to automatically perform this operation. If you look in |
1512 | C<lib/MyApp/Controller/Root.pm>, you should see the empty definition for |
1513 | the C<sub end> method: |
3533daff |
1514 | |
1515 | sub end : ActionClass('RenderView') {} |
1516 | |
1390ef0e |
1517 | The following bullet points provide a quick overview of the |
3533daff |
1518 | C<RenderView> process: |
1519 | |
1520 | =over 4 |
1521 | |
1522 | =item * |
1523 | |
1524 | C<Root.pm> is designed to hold application-wide logic. |
1525 | |
1526 | =item * |
1527 | |
1390ef0e |
1528 | At the end of a given user request, Catalyst will call the most specific |
1529 | C<end> method that's appropriate. For example, if the controller for a |
1530 | request has an C<end> method defined, it will be called. However, if |
1531 | the controller does not define a controller-specific C<end> method, the |
3533daff |
1532 | "global" C<end> method in C<Root.pm> will be called. |
1533 | |
1534 | =item * |
1535 | |
1536 | Because the definition includes an C<ActionClass> attribute, the |
c988c8b0 |
1537 | L<Catalyst::Action::RenderView> logic will be executed B<after> any code |
1538 | inside the definition of C<sub end> is run. See |
1539 | L<Catalyst::Manual::Actions> for more information on C<ActionClass>. |
3533daff |
1540 | |
1541 | =item * |
1542 | |
1390ef0e |
1543 | Because C<sub end> is empty, this effectively just runs the default |
1544 | logic in C<RenderView>. However, you can easily extend the |
1545 | C<RenderView> logic by adding your own code inside the empty method body |
1546 | (C<{}>) created by the Catalyst Helpers when we first ran the |
1547 | C<catalyst.pl> to initialize our application. See |
2217b252 |
1548 | L<Catalyst::Action::RenderView> for more |
4d63a0d5 |
1549 | detailed information on how to extend C<RenderView> in C<sub end>. |
3533daff |
1550 | |
1551 | =back |
1552 | |
1553 | |
fce83e5f |
1554 | =head2 RenderView's "dump_info" Feature |
1555 | |
a8f4e284 |
1556 | One of the nice features of C<RenderView> is that it automatically |
1557 | allows you to add C<dump_info=1> to the end of any URL for your |
1558 | application and it will force the display of the "exception dump" screen |
1559 | to the client browser. You can try this out by pointing your browser to |
1560 | this URL: |
fce83e5f |
1561 | |
1562 | http://localhost:3000/books/list?dump_info=1 |
1563 | |
1564 | You should get a page with the following message at the top: |
1565 | |
1566 | Caught exception in MyApp::Controller::Root->end "Forced debug - |
1567 | Scrubbed output at /usr/share/perl5/Catalyst/Action/RenderView.pm line 46." |
1568 | |
a8f4e284 |
1569 | Along with a summary of your application's state at the end of the |
1570 | processing for that request. The "Stash" section should show a |
1571 | summarized version of the DBIC book model objects. If desired, you can |
1572 | adjust the summarization logic (called "scrubbing" logic) -- see |
2217b252 |
1573 | L<Catalyst::Action::RenderView> for |
fce83e5f |
1574 | details. |
1575 | |
a8f4e284 |
1576 | Note that you shouldn't need to worry about "normal clients" using this |
1577 | technique to "reverse engineer" your application -- C<RenderView> only |
1578 | supports the C<dump_info=1> feature when your application is running in |
1579 | C<-Debug> mode (something you won't do once you have your application |
1580 | deployed in production). |
fce83e5f |
1581 | |
1582 | |
3533daff |
1583 | =head2 Using The Default Template Name |
1584 | |
1390ef0e |
1585 | By default, C<Catalyst::View::TT> will look for a template that uses the |
1586 | same name as your controller action, allowing you to save the step of |
1587 | manually specifying the template name in each action. For example, this |
c988c8b0 |
1588 | would allow us to remove the |
1589 | C<$c-E<gt>stash-E<gt>{template} = 'books/list.tt2';> |
1590 | line of our C<list> action in the Books controller. |
a8f4e284 |
1591 | Open C<lib/MyApp/Controller/Books.pm> in your editor and comment out |
1592 | this line to match the following (only the |
1593 | C<$c-E<gt>stash-E<gt>{template}> line has changed): |
3533daff |
1594 | |
1595 | =head2 list |
1596 | |
1597 | Fetch all book objects and pass to books/list.tt2 in stash to be displayed |
1598 | |
1599 | =cut |
1600 | |
ddfbd850 |
1601 | sub list :Local { |
3533daff |
1602 | # Retrieve the usual Perl OO '$self' for this object. $c is the Catalyst |
1603 | # 'Context' that's used to 'glue together' the various components |
1604 | # that make up the application |
1605 | my ($self, $c) = @_; |
1606 | |
1607 | # Retrieve all of the book records as book model objects and store in the |
1608 | # stash where they can be accessed by the TT template |
0ed3df53 |
1609 | $c->stash(books => [$c->model('DB::Book')->all]); |
3533daff |
1610 | |
1611 | # Set the TT template to use. You will almost always want to do this |
1612 | # in your action methods (actions methods respond to user input in |
1613 | # your controllers). |
61cb69fd |
1614 | #$c->stash(template => 'books/list.tt2'); |
3533daff |
1615 | } |
1616 | |
3533daff |
1617 | |
6961c906 |
1618 | You should now be able to access the L<http://localhost:3000/books/list> |
1619 | URL as before. |
3533daff |
1620 | |
a8f4e284 |
1621 | B<NOTE:> Please note that if you use the default template technique, you |
1622 | will B<not> be able to use either the C<$c-E<gt>forward> or the |
1623 | C<$c-E<gt>detach> mechanisms (these are discussed in Chapter 2 and |
4b4d3884 |
1624 | Chapter 9 of the Tutorial). |
3533daff |
1625 | |
3b1fa91b |
1626 | B<IMPORTANT:> Make sure that you do NOT skip the following section |
1627 | before continuing to the next chapter 4 Basic CRUD. |
3533daff |
1628 | |
fce83e5f |
1629 | |
4d63a0d5 |
1630 | =head2 Return To A Manually Specified Template |
3533daff |
1631 | |
1632 | In order to be able to use C<$c-E<gt>forward> and C<$c-E<gt>detach> |
a8f4e284 |
1633 | later in the tutorial, you should remove the comment from the statement |
1634 | in C<sub list> in C<lib/MyApp/Controller/Books.pm>: |
3533daff |
1635 | |
0ed3df53 |
1636 | $c->stash(template => 'books/list.tt2'); |
3533daff |
1637 | |
a8f4e284 |
1638 | Then delete the C<TEMPLATE_EXTENSION> line in C<lib/MyApp/View/HTML.pm>. |
3533daff |
1639 | |
a8f4e284 |
1640 | Check the L<http://localhost:3000/books/list> URL in your browser. It |
1641 | should look the same manner as with earlier sections. |
3533daff |
1642 | |
1643 | |
1644 | =head1 AUTHOR |
1645 | |
1646 | Kennedy Clark, C<hkclark@gmail.com> |
1647 | |
53243324 |
1648 | Feel free to contact the author for any errors or suggestions, but the |
1649 | best way to report issues is via the CPAN RT Bug system at |
1650 | <https://rt.cpan.org/Public/Dist/Display.html?Name=Catalyst-Manual>. |
1651 | |
1652 | The most recent version of the Catalyst Tutorial can be found at |
59884771 |
1653 | L<http://dev.catalyst.perl.org/repos/Catalyst/Catalyst-Manual/5.80/trunk/lib/Catalyst/Manual/Tutorial/>. |
3533daff |
1654 | |
ec3ef4ad |
1655 | Copyright 2006-2010, Kennedy Clark, under the |
1656 | Creative Commons Attribution Share-Alike License Version 3.0 |
8482d557 |
1657 | (L<http://creativecommons.org/licenses/by-sa/3.0/us/>). |