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