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