Fix erroneous "Part #" cross references between parts of the tutorial.
[catagits/Catalyst-Manual.git] / lib / Catalyst / Manual / Tutorial / MoreCatalystBasics.pod
1 =head1 NAME
2
3 Catalyst::Manual::Tutorial::MoreCatalystBasics - Catalyst Tutorial - Part 3: More Catalyst Application Development Basics
4
5
6 =head1 OVERVIEW
7
8 This is B<Part 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::Intro>
17
18 =item 2
19
20 L<Catalyst Basics|Catalyst::Manual::Tutorial::CatalystBasics>
21
22 =item 3
23
24 B<More Catalyst Basics>
25
26 =item 4
27
28 L<Basic CRUD|Catalyst::Manual::Tutorial::BasicCRUD>
29
30 =item 5
31
32 L<Authentication|Catalyst::Manual::Tutorial::Authentication>
33
34 =item 6
35
36 L<Authorization|Catalyst::Manual::Tutorial::Authorization>
37
38 =item 7
39
40 L<Debugging|Catalyst::Manual::Tutorial::Debugging>
41
42 =item 8
43
44 L<Testing|Catalyst::Manual::Tutorial::Testing>
45
46 =item 9
47
48 L<Advanced CRUD|Catalyst::Manual::Tutorial::AdvancedCRUD>
49
50 =item 10
51
52 L<Appendices|Catalyst::Manual::Tutorial::Appendices>
53
54 =back
55
56
57 =head1 DESCRIPTION
58
59 This part of the tutorial builds on the work done in Part 2 to explore 
60 some features that are more typical of "real world" web applications. 
61 From this part of the tutorial onward, we will be building a simple 
62 book database application.  Although the application will be too 
63 limited to be of use to anyone, it should provide a basic environment 
64 where we can explore a variety of features used in virtually all web 
65 applications.
66
67 You can checkout the source code for this example from the catalyst
68 subversion repository as per the instructions in
69 L<Catalyst::Manual::Tutorial::Intro>
70
71
72 =head1 CREATE A NEW APPLICATION
73
74 The remainder of the tutorial will build an application call C<MyApp>. 
75 Use the Catalyst C<catalyst.pl> script to initialize the framework for 
76 an application called C<MyApp> (make sure you aren't still inside the 
77 directory of the C<Hello> application from the previous part of the 
78 tutorial):
79
80     $ catalyst.pl MyApp
81     created "MyApp"
82     created "MyApp/script"
83     created "MyApp/lib"
84     created "MyApp/root"
85     ...
86     created "MyApp/script/myapp_create.pl"
87     $ cd MyApp
88
89 This creates a similar skeletal structure to what we saw in Part 2 of 
90 the tutorial, except with C<MyApp> or C<myapp> substituted for 
91 C<Hello> and C<hello>.
92
93
94 =head1 EDIT THE LIST OF CATALYST PLUGINS
95
96 One of the greatest benefits of Catalyst is that it has such a large
97 library of plugins available.  Plugins are used to seamlessly integrate
98 existing Perl modules into the overall Catalyst framework.  In general,
99 they do this by adding additional methods to the C<context> object
100 (generally written as C<$c>) that Catalyst passes to every component
101 throughout the framework.
102
103 By default, Catalyst enables three plugins/flags:
104
105 =over 4
106
107 =item * 
108
109 C<-Debug> Flag
110
111 Enables the Catalyst debug output you saw when we started the
112 C<script/myapp_server.pl> development server earlier.  You can remove
113 this plugin when you place your application into production.
114
115 As you may have noticed, C<-Debug> is not a plugin, but a I<flag>.
116 Although most of the items specified on the C<use Catalyst> line of your
117 application class will be plugins, Catalyst supports a limited number of
118 flag options (of these, C<-Debug> is the most common).  See the
119 documentation for C<Catalyst.pm> to get details on other flags 
120 (currently C<-Engine>, C<-Home>, and C<-Log>).
121
122 If you prefer, you can use the C<$c-E<gt>debug> method to enable debug
123 messages.
124
125 B<TIP>: Depending on your needs, it can be helpful to permanently
126 remove C<-Debug> from C<lib/MyApp.pm> and then use the C<-d> option
127 to C<script/myapp_server.pl> to re-enable it just for the development
128 server.  We will not be using that approach in the tutorial, but feel 
129 free to make use of it in your own projects.
130
131 =item *
132
133 L<Catalyst::Plugin::ConfigLoader|Catalyst::Plugin::ConfigLoader>
134
135 C<ConfigLoader> provides an automatic way to load configurable
136 parameters for your application from a central
137 L<Config::General|Config::General> file (versus having the values
138 hard-coded inside your Perl modules).  Config::General uses syntax
139 very similar to Apache configuration files.  We will see how to use
140 this feature of Catalyst during the authentication and authorization
141 sections (Part 5 and Part 6).
142
143 B<IMPORTANT NOTE:> If you are following along in Ubuntu 8.04 or
144 otherwise using a version of L<Catalyst::Devel|Catalyst::Devel> prior
145 to version 1.06, you need to be aware that Catalyst changed from a
146 default format of YAML to the more straightforward C<Config::General>
147 format.  Because Catalyst has long supported both formats, this
148 tutorial will simply use a configuration file called C<myapp.conf>
149 instead of C<myapp.yml> and Catatlyst will automcatically use the new
150 format.  Just be aware that earlier versions of Catalyst will still
151 create the C<myapp.yml> file and that you will need to B<remove
152 C<myapp.yml>> and create a new C<myapp.conf> file by hand, but
153 otherwise this transition is very painless.  The default contents of
154 C<myapp.conf> should only consist of one line: C<name MyApp>.  Also be
155 aware that you can continue to use any format supported by
156 L<Catalyst::Plugin::ConfigLoader|Catalyst::Plugin::ConfigLoader> and
157 L<Config::Any|Config::Any>, including YAML -- Catalyst will
158 automatically look for any of the supported configuration file
159 formats.
160
161 B<TIP>: This script can be useful for converting between configuration 
162 formats:
163
164     perl -Ilib -e 'use MyApp; use Config::General; 
165         Config::General->new->save_file("myapp.conf", MyApp->config);'
166
167 B<NOTE:> The default C<myapp.conf> should look like:
168
169     name   MyApp
170
171 =item *
172
173 L<Catalyst::Plugin::Static::Simple|Catalyst::Plugin::Static::Simple>
174
175 C<Static::Simple> provides an easy method of serving static content such
176 as images and CSS files under the development server.
177
178 =back
179
180 To modify the list of plugins, edit C<lib/MyApp.pm> (this file is
181 generally referred to as your I<application class>) and delete the line
182 with:
183
184     use Catalyst qw/-Debug ConfigLoader Static::Simple/;
185
186 Replace it with:
187
188     use Catalyst qw/
189             -Debug
190             ConfigLoader
191             Static::Simple
192             
193             StackTrace
194             /;
195
196 This tells Catalyst to start using one new plugin:
197
198 =over 4
199
200 =item * 
201
202 L<Catalyst::Plugin::StackTrace|Catalyst::Plugin::StackTrace>
203
204 Adds a stack trace to the standard Catalyst "debug screen" (this is the
205 screen Catalyst sends to your browser when an error occurs).
206
207 Note: L<StackTrace|Catalyst::Plugin::StackTrace> output appears in your
208 browser, not in the console window from which you're running your
209 application, which is where logging output usually goes.
210
211 B<Note:> You will want to disable 
212 L<StackTrace|Catalyst::Plugin::StackTrace> before you put your 
213 application into production, but it can be helpful during development.
214
215 =back
216
217 Note that when specifying plugins on the C<use Catalyst> line, you can
218 omit C<Catalyst::Plugin::> from the name.  Additionally, you can spread
219 the plugin names across multiple lines as shown here, or place them all
220 on one (or more) lines as with the default configuration.
221
222
223 =head1 CREATE A CATALYST CONTROLLER
224
225 As discussed earlier, controllers are where you write methods that 
226 interact with user input.  Typically, controller methods respond to 
227 C<GET> and C<POST> messages from the user's web browser.
228
229 Use the Catalyst C<create> script to add a controller for book-related
230 actions:
231
232     $ script/myapp_create.pl controller Books
233      exists "/home/me/MyApp/script/../lib/MyApp/Controller"
234      exists "/home/me/MyApp/script/../t"
235     created "/home/me/MyApp/script/../lib/MyApp/Controller/Books.pm"
236     created "/home/me/MyApp/script/../t/controller_Books.t"
237
238 Then edit C<lib/MyApp/Controller/Books.pm> and add the following method
239 to the controller:
240
241     =head2 list
242     
243     Fetch all book objects and pass to books/list.tt2 in stash to be displayed
244     
245     =cut
246      
247     sub list : Local {
248         # Retrieve the usual Perl OO '$self' for this object. $c is the Catalyst
249         # 'Context' that's used to 'glue together' the various components
250         # that make up the application
251         my ($self, $c) = @_;
252     
253         # Retrieve all of the book records as book model objects and store in the
254         # stash where they can be accessed by the TT template
255         $c->stash->{books} = [$c->model('DB::Books')->all];
256         
257         # Set the TT template to use.  You will almost always want to do this
258         # in your action methods (action methods respond to user input in
259         # your controllers).
260         $c->stash->{template} = 'books/list.tt2';
261     }
262
263 B<Note:> This won't actually work yet since you haven't set up your 
264 model yet.  We will be covering the model soon.
265
266 B<Note:> Programmers experienced with object-oriented Perl should 
267 recognize C<$self> as a reference to the object where this method was 
268 called.  On the other hand, C<$c> will be new to many Perl programmers 
269 who have not used Catalyst before (it's sometimes written as 
270 C<$context>).  The Context object is automatically passed to all 
271 Catalyst components.  It is used to pass information between 
272 components and provide access to Catalyst and plugin functionality.
273
274 B<TIP>: You may see the C<$c-E<gt>model('DB::Book')> used above
275 written as C<$c-E<gt>model('DB')-E<gt>resultset('Book)>.  The two
276 are equivalent.
277
278 B<Note:> Catalyst actions are regular Perl methods, but they make use 
279 of Nicholas Clark's C<attributes> module (that's the C<: Local> next 
280 to the C<sub list> in the code above) to provide additional 
281 information to the Catalyst dispatcher logic.  Many newer Catalyst 
282 applications are switching to the use of "Literal" C<:Path> actions 
283 and C<Args> attribute in lieu of C<: Local> and C<: Private>.  For 
284 example, C<sub any_method :Path :Args(0)> can be used instead of 
285 C<sub index :Private> (because no path was supplied to C<Path> it 
286 matches the "empty" URL in the namespace of that module... the same 
287 thing C<sub index> would do) or C<sub list :Path('list') :Args(0)> 
288 could be used instead of the C<sub list : Local> above (the C<list> 
289 argument to C<Path> would make it match on the URL C<list> under 
290 C<books>, the namespace of the current module).  See "Action Types" in 
291 L<Catalyst::Manual::Intro|Catalyst::Manual::Intro> as well as Part 5 
292 of this tutorial (Authentication) for additional information.  Another 
293 popular but more advanced feature is C<Chained> actions that allow a 
294 single URL to "chain together" multiple action method calls, each with 
295 an appropriate number of arguments (see
296 L<Catalyst::DispatchType::Chained|Catalyst::DispatchType::Chained>
297 for details).
298
299
300 =head1 CATALYST VIEWS
301
302 As mentioned in Part 2 of the tutorial, views are where you render 
303 output, typically for display in the user's web browser, but also 
304 possibly using other display output- generation systems.  As with 
305 virtually every aspect of Catalyst, options abound when it comes to 
306 the specific view technology you adopt inside your application. 
307 However, most Catalyst applications use the Template Toolkit, known as 
308 TT (for more information on TT, see 
309 L<http://www.template-toolkit.org>). Other popular view technologies 
310 include Mason (L<http://www.masonhq.com> and 
311 L<http://www.masonbook.com>) and L<HTML::Template> 
312 (L<http://html- template.sourceforge.net>).
313
314 =head2 Create a Catalyst View Using C<TTSite>
315
316 When using TT for the Catalyst view, there are two main helper scripts:
317
318 =over 4
319
320 =item *
321
322 L<Catalyst::Helper::View::TT|Catalyst::Helper::View::TT>
323
324 =item *
325
326 L<Catalyst::Helper::View::TTSite|Catalyst::Helper::View::TTSite>
327
328 =back
329
330 Both are similar, but C<TT> merely creates the C<lib/MyApp/View/TT.pm>
331 file and leaves the creation of any hierarchical template organization
332 entirely up to you. (It also creates a C<t/view_TT.t> file for testing;
333 test cases will be discussed in Part 8). The C<TTSite> helper creates a
334 modular and hierarchical view layout with separate Template Toolkit (TT)
335 files for common header and footer information, configuration values, a
336 CSS stylesheet, and more.
337
338 While TTSite is useful to bootstrap a project, we recommend that
339 unless you know what you're doing or want to pretty much use the
340 supplied templates as is, that you use the plain Template Toolkit view
341 when starting a project from scratch.  This is because TTSite can be
342 tricky to customize.  Additionally TT contains constructs that you
343 need to learn yourself if you're going to be a serious user of TT.
344 Our experience suggests that you're better off learning these from
345 scratch.  We use TTSite here precisely because it is useful for
346 bootstrap/prototype purposes.
347
348 Enter the following command to enable the C<TTSite> style of view
349 rendering for this tutorial:
350
351     $ script/myapp_create.pl view TT TTSite
352      exists "/home/me/MyApp/script/../lib/MyApp/View"
353      exists "/home/me/MyApp/script/../t"
354     created "/home/me/MyApp/script/../lib/MyApp/View/TT.pm"
355     created "/home/me/MyApp/script/../root/lib"
356     ...
357     created "/home/me/MyApp/script/../root/src/ttsite.css"
358
359 This puts a number of files in the C<root/lib> and C<root/src>
360 directories that can be used to customize the look and feel of your
361 application.  Also take a look at C<lib/MyApp/View/TT.pm> for config
362 values set by the C<TTSite> helper.
363
364 B<TIP>: Note that TTSite does one thing that could confuse people who
365 are used to the normal C<TT> Catalyst view: it redefines the Catalyst
366 context object in templates from its usual C<c> to C<Catalyst>. When
367 looking at other Catalyst examples, remember that they almost always use
368 C<c>.  Note that Catalyst and TT I<do not complain> when you use the
369 wrong name to access the context object...TT simply outputs blanks for
370 that bogus logic (see next tip to change this behavior with TT C<DEBUG>
371 options).  Finally, be aware that this change in name I<only>
372 applies to how the context object is accessed inside your TT templates;
373 your controllers will continue to use C<$c> (or whatever name you use
374 when fetching the reference from C<@_> inside your methods). (You can
375 change back to the "default" behavior be removing the C<CATALYST_VAR>
376 line from C<lib/MyApp/View/TT.pm>, but you will also have to edit
377 C<root/lib/config/main> and C<root/lib/config/url>.  If you do this, be
378 careful not to have a collision between your own C<c> variable and the
379 Catalyst C<c> variable.)
380
381 B<TIP>: When troubleshooting TT it can be helpful to enable variable
382 C<DEBUG> options.  You can do this in a Catalyst environment by adding
383 a C<DEBUG> line to the C<__PACKAGE__->config> declaration in 
384 C<lib/MyApp/View/TT.pm>:
385
386     __PACKAGE__->config({
387         CATALYST_VAR => 'Catalyst',
388         ...
389         DEBUG        => 'undef',
390         ...
391     });
392
393 B<Note:> C<__PACKAGE__> is just a shorthand way of referencing the name
394 of the package where it is used.  Therefore, in C<TT.pm>,
395 C<__PACKAGE__> is equivalent to C<TT>.
396
397 There are a variety of options you can use, such as 'undef', 'all', 
398 'service', 'context', 'parser', 'provider', and 'service'.  See
399 L<Template::Constants> for more information (remove the C<DEBUG_>
400 portion of the name shown in the TT docs and convert to lower case
401 for use inside Catalyst).
402
403 B<NOTE:> B<Please be sure to disable TT debug options before 
404 continuing the tutorial> (especially the 'undef' option -- leaving
405 this enabled will conflict with several of the conventions used
406 by this tutorial and TTSite to leave some variables undefined
407 on purpose).
408
409
410 =head2 Globally Customize Every View
411
412 When using TTSite, files in the subdirectories of C<root/lib> can be
413 used to make changes that will appear in every view.  For example, to
414 display optional status and error messages in every view, edit
415 C<root/lib/site/layout>, updating it to match the following (the two HTML
416 C<span> elements are new):
417
418     <div id="header">[% PROCESS site/header %]</div>
419     
420     <div id="content">
421     <span class="message">[% status_msg %]</span>
422     <span class="error">[% error_msg %]</span>
423     [% content %]
424     </div>
425     
426     <div id="footer">[% PROCESS site/footer %]</div>
427
428 If we set either message in the Catalyst stash (e.g.,
429 C<$c-E<gt>stash-E<gt>{status_msg} = 'Request was successful!'>) it will
430 be displayed whenever any view used by that request is rendered.  The
431 C<message> and C<error> CSS styles are automatically defined in
432 C<root/src/ttsite.css> and can be customized to suit your needs.
433
434 B<Note:> The Catalyst stash only lasts for a single HTTP request.  If
435 you need to retain information across requests you can use
436 L<Catalyst::Plugin::Session|Catalyst::Plugin::Session> (we will use
437 Catalyst sessions in the Authentication part of the tutorial).
438
439
440 =head2 Create a TT Template Page
441
442 To add a new page of content to the TTSite view hierarchy, just create a
443 new C<.tt2> file in C<root/src>.  Only include HTML markup that goes
444 inside the HTML <body> and </body> tags, TTSite will use the contents of
445 C<root/lib/site> to add the top and bottom.
446
447 First create a directory for book-related TT templates:
448
449     $ mkdir root/src/books
450
451 Then create C<root/src/books/list.tt2> in your editor and enter:
452
453     [% # This is a TT comment.  The '-' at the end "chomps" the newline.  You won't -%]
454     [% # see this "chomping" in your browser because HTML ignores blank lines, but  -%]
455     [% # it WILL eliminate a blank line if you view the HTML source.  It's purely   -%]
456     [%- # optional, but both the beginning and the ending TT tags support chomping. -%]
457     
458     [% # Provide a title to root/lib/site/header -%]
459     [% META title = 'Book List' -%]
460     
461     <table>
462     <tr><th>Title</th><th>Rating</th><th>Author(s)</th></tr>
463     [% # Display each book in a table row %]
464     [% FOREACH book IN books -%]
465       <tr>
466         <td>[% book.title %]</td>
467         <td>[% book.rating %]</td>
468       </tr>
469     [% END -%]
470     </table>
471
472 As indicated by the inline comments above, the C<META title> line uses
473 TT's META feature to provide a title to C<root/lib/site/header>.
474 Meanwhile, the outer C<FOREACH> loop iterates through each C<book> model
475 object and prints the C<title> and C<rating> fields.  An inner
476 C<FOREACH> loop prints the last name of each author in a comma-separated
477 list within a single table cell.
478
479 If you are new to TT, the C<[%> and C<%]> tags are used to delimit TT
480 code.  TT supports a wide variety of directives for "calling" other
481 files, looping, conditional logic, etc.  In general, TT simplifies the
482 usual range of Perl operators down to the single dot (C<.>) operator.
483 This applies to operations as diverse as method calls, hash lookups, and
484 list index values (see
485 L<http://www.template-toolkit.org/docs/default/Manual/Variables.html>
486 for details and examples).  In addition to the usual C<Template> module
487 Pod documentation, you can access the TT manual at
488 L<http://www.template-toolkit.org/docs/default/>.
489
490 B<NOTE:> The C<TTSite> helper creates several TT files using an
491 extension of C<.tt2>. Most other Catalyst and TT examples use an
492 extension of C<.tt>.  You can use either extension (or no extension at
493 all) with TTSite and TT, just be sure to use the appropriate extension
494 for both the file itself I<and> the C<$c-E<gt>stash-E<gt>{template} =
495 ...> line in your controller.  This document will use C<.tt2> for
496 consistency with the files already created by the C<TTSite> helper.
497
498
499 =head1 CREATE A SQLITE DATABASE
500
501 In this step, we make a text file with the required SQL commands to
502 create a database table and load some sample data.  Open C<myapp01.sql>
503 in your editor and enter:
504
505     --
506     -- Create a very simple database to hold book and author information
507     --
508     CREATE TABLE books (
509             id          INTEGER PRIMARY KEY,
510             title       TEXT ,
511             rating      INTEGER
512     );
513     -- 'book_authors' is a many-to-many join table between books & authors
514     CREATE TABLE book_authors (
515             book_id     INTEGER,
516             author_id   INTEGER,
517             PRIMARY KEY (book_id, author_id)
518     );
519     CREATE TABLE authors (
520             id          INTEGER PRIMARY KEY,
521             first_name  TEXT,
522             last_name   TEXT
523     );
524     ---
525     --- Load some sample data
526     ---
527     INSERT INTO books VALUES (1, 'CCSP SNRS Exam Certification Guide', 5);
528     INSERT INTO books VALUES (2, 'TCP/IP Illustrated, Volume 1', 5);
529     INSERT INTO books VALUES (3, 'Internetworking with TCP/IP Vol.1', 4);
530     INSERT INTO books VALUES (4, 'Perl Cookbook', 5);
531     INSERT INTO books VALUES (5, 'Designing with Web Standards', 5);
532     INSERT INTO authors VALUES (1, 'Greg', 'Bastien');
533     INSERT INTO authors VALUES (2, 'Sara', 'Nasseh');
534     INSERT INTO authors VALUES (3, 'Christian', 'Degu');
535     INSERT INTO authors VALUES (4, 'Richard', 'Stevens');
536     INSERT INTO authors VALUES (5, 'Douglas', 'Comer');
537     INSERT INTO authors VALUES (6, 'Tom', 'Christiansen');
538     INSERT INTO authors VALUES (7, 'Nathan', 'Torkington');
539     INSERT INTO authors VALUES (8, 'Jeffrey', 'Zeldman');
540     INSERT INTO book_authors VALUES (1, 1);
541     INSERT INTO book_authors VALUES (1, 2);
542     INSERT INTO book_authors VALUES (1, 3);
543     INSERT INTO book_authors VALUES (2, 4);
544     INSERT INTO book_authors VALUES (3, 5);
545     INSERT INTO book_authors VALUES (4, 6);
546     INSERT INTO book_authors VALUES (4, 7);
547     INSERT INTO book_authors VALUES (5, 8);
548
549 B<TIP>: See Appendix 1 for tips on removing the leading spaces when
550 cutting and pasting example code from POD-based documents.
551
552 Then use the following command to build a C<myapp.db> SQLite database:
553
554     $ sqlite3 myapp.db < myapp01.sql
555
556 If you need to create the database more than once, you probably want to
557 issue the C<rm myapp.db> command to delete the database before you use
558 the C<sqlite3 myapp.db < myapp01.sql> command.
559
560 Once the C<myapp.db> database file has been created and initialized, you
561 can use the SQLite command line environment to do a quick dump of the
562 database contents:
563
564     $ sqlite3 myapp.db
565     SQLite version 3.4.2
566     Enter ".help" for instructions
567     sqlite> select * from books;
568     1|CCSP SNRS Exam Certification Guide|5
569     2|TCP/IP Illustrated, Volume 1|5
570     3|Internetworking with TCP/IP Vol.1|4
571     4|Perl Cookbook|5
572     5|Designing with Web Standards|5
573     sqlite> .q
574     $
575
576 Or:
577
578     $ sqlite3 myapp.db "select * from books"
579     1|CCSP SNRS Exam Certification Guide|5
580     2|TCP/IP Illustrated, Volume 1|5
581     3|Internetworking with TCP/IP Vol.1|4
582     4|Perl Cookbook|5
583     5|Designing with Web Standards|5
584
585 As with most other SQL tools, if you are using the full "interactive"
586 environment you need to terminate your SQL commands with a ";" (it's not
587 required if you do a single SQL statement on the command line).  Use
588 ".q" to exit from SQLite from the SQLite interactive mode and return to
589 your OS command prompt.
590
591
592 =head1 DATABASE ACCESS WITH C<DBIx::Class>
593
594 Catalyst can be used with virtually any form of persistent datastore
595 available via Perl.  For example, 
596 L<Catalyst::Model::DBI|Catalyst::Model::DBI> can be used to
597 easily access databases through the traditional Perl C<DBI> interface.
598 However, most Catalyst applications use some form of ORM technology to
599 automatically create and save model objects as they are used.  Although
600 Tony Bowden's L<Class::DBI|Class::DBI> has been a popular choice 
601 in the past, Matt Trout's L<DBIx::Class|DBIx::Class> (abbreviated 
602 as "DBIC") has rapidly emerged as the Perl-based ORM technology of choice.  
603 Most new Catalyst applications rely on DBIC, as will this tutorial.
604
605 =head2 Create a dynamic DBIC Model
606
607 Use the C<create=dynamic> model helper option to build a model that 
608 dynamically reads your database structure every time the application
609 starts:
610
611     $ script/myapp_create.pl model DB DBIC::Schema MyApp::Schema create=dynamic dbi:SQLite:myapp.db
612      exists "/home/kclark/dev/MyApp/script/../lib/MyApp/Model"
613      exists "/home/kclark/dev/MyApp/script/../t"
614      exists "/home/kclark/dev/MyApp/script/../lib/MyApp"
615     created "/home/kclark/dev/MyApp/script/../lib/MyApp/Schema.pm"
616     created "/home/kclark/dev/MyApp/script/../lib/MyApp/Model/DB.pm"
617     created "/home/kclark/dev/MyApp/script/../t/model_DB.t"
618
619
620 C<DB> is the name of the model class to be created by the helper in 
621 C<lib/MyApp/Model> (Catalyst has a separate directory under C<lib/MyApp> 
622 for each of the three parts of MVC: C<Model>, C<View>, and C<Controller>).  
623 C<DBIC::Schema> is the type of the model to create. 
624 C<MyApp::Schema> is the name of the DBIC schema file written to 
625 C<lib/MyApp/Schema.pm>.  Because we specified C<create=dynamic> 
626 to the helper, it use L<DBIx::Class::Schema::Loader> to dynamically load 
627 the schema information from the database every time the application 
628 starts.  And finally, C<dbi:SQLite:myapp.db> is the standard DBI connect 
629 string for use with SQLite.
630
631 B<NOTE:> Although the C<create=dynamic> option to the DBIC helper
632 makes for a nifty demonstration, is only really suitable for very
633 small applications. After this demonstration, you should almost always
634 use the C<create=static> option that we switch to below.
635
636
637 =head1 RUN THE APPLICATION
638
639 First, let's enable an environment variable option that causes
640 DBIx::Class to dump the SQL statements it's using to access the database
641 (this option can provide extremely helpful troubleshooting information):
642
643     $ export DBIC_TRACE=1
644
645 This assumes you are using BASH as your shell -- adjust accordingly if
646 you are using a different shell (for example, under tcsh, use
647 C<setenv DBIC_TRACE 1>).
648
649 B<NOTE:> You can also set this in your code using
650 C<$class-E<gt>storage-E<gt>debug(1);>.  See
651 L<DBIx::Class::Manual::Troubleshooting> for details (including options
652 to log to file instead of displaying to the Catalyst development server
653 log).
654
655 Then run the Catalyst "demo server" script:    
656
657     $ script/myapp_server.pl
658
659 Your development server log output should display something like:
660
661     $script/myapp_server.pl
662     [debug] Debug messages enabled
663     [debug] Loaded plugins:
664     .----------------------------------------------------------------------------.
665     | Catalyst::Plugin::ConfigLoader  0.17                                       |
666     | Catalyst::Plugin::StackTrace  0.06                                         |
667     | Catalyst::Plugin::Static::Simple  0.20                                     |
668     '----------------------------------------------------------------------------'
669     
670     [debug] Loaded dispatcher "Catalyst::Dispatcher"
671     [debug] Loaded engine "Catalyst::Engine::HTTP"
672     [debug] Found home "/home/me/MyApp"
673     [debug] Loaded Config "/home/me/MyApp/myapp.conf"
674     [debug] Loaded components:
675     .-----------------------------------------------------------------+----------.
676     | Class                                                           | Type     |
677     +-----------------------------------------------------------------+----------+
678     | MyApp::Controller::Books                                        | instance |
679     | MyApp::Controller::Root                                         | instance |
680     | MyApp::Model::DB                                                | instance |
681     | MyApp::Model::DB::Authors                                       | class    |
682     | MyApp::Model::DB::BookAuthors                                   | class    |
683     | MyApp::Model::DB::Books                                         | class    |
684     | MyApp::View::TT                                                 | instance |
685     '-----------------------------------------------------------------+----------'
686     
687     [debug] Loaded Private actions:
688     .----------------------+--------------------------------------+--------------.
689     | Private              | Class                                | Method       |
690     +----------------------+--------------------------------------+--------------+
691     | /default             | MyApp::Controller::Root              | default      |
692     | /end                 | MyApp::Controller::Root              | end          |
693     | /books/index         | MyApp::Controller::Books             | index        |
694     | /books/list          | MyApp::Controller::Books             | list         |
695     '----------------------+--------------------------------------+--------------'
696     
697     [debug] Loaded Path actions:
698     .-------------------------------------+--------------------------------------.
699     | Path                                | Private                              |
700     +-------------------------------------+--------------------------------------+
701     | /books/list                         | /books/list                          |
702     '-------------------------------------+--------------------------------------'
703     
704     [info] MyApp powered by Catalyst 5.7011
705     You can connect to your server at http://localhost:3000
706
707 B<NOTE:> Be sure you run the C<script/myapp_server.pl> command from 
708 the 'base' directory of your application, not inside the C<script> 
709 directory itself or it will not be able to locate the C<myapp.db> 
710 database file.  You can use a fully qualified or a relative path to 
711 locate the database file, but we did not specify that when we ran the 
712 model helper earlier.
713
714 Some things you should note in the output above:
715
716 =over 4
717
718 =item * 
719
720 Catalyst::Model::DBIC::Schema dynamically created three model classes, 
721 one to represent each of the three tables in our database 
722 (C<MyApp::Model::DB::Authors>, C<MyApp::Model::DB::BookAuthors>,
723 and C<MyApp::Model::DB::Books>).
724
725 =item * 
726
727 The "list" action in our Books controller showed up with a path of
728 C</books/list>.
729
730 =back
731
732 Point your browser to L<http://localhost:3000> and you should still get
733 the Catalyst welcome page.
734
735 Next, to view the book list, change the URL in your browser to
736 L<http://localhost:3000/books/list>. You should get a list of the five
737 books loaded by the C<myapp01.sql> script above, with TTSite providing
738 the formatting for the very simple output we generated in our template.
739 The rating for each book should appear on each row.
740
741 Also notice in the output of the C<script/myapp_server.pl> that DBIC
742 used the following SQL to retrieve the data:
743
744     SELECT me.id, me.title, me.rating FROM books me
745
746 because we enabled DBIC_TRACE.
747
748 You now the beginnings of a simple but workable web application. 
749 Continue on to future sections and we will develop the application
750 more fully.
751
752
753 =head1 A STATIC DATABASE MODEL WITH C<DBIx::Class>
754
755 =head2 Create Static DBIC Schema Files
756
757 Unlike the previous section where we had DBIC automatically discover the 
758 structure of the database every time the application started, here we 
759 will use static schema files for more control.  This is typical of most 
760 "real world" applications.
761
762 One option would be to create a separate schema file for each table in
763 the database, however, lets use the same L<DBIx::Class::Schema::Loader>
764 used earlier with C<create=dynamic> to build the static files for us.
765 First, lets remove the schema file created earlier:
766
767     $ rm lib/MyApp/Schema.pm 
768
769 Now regenerate the schema using the C<create=static> option:
770
771     $ script/myapp_create.pl model DB DBIC::Schema MyApp::Schema create=static dbi:SQLite:myapp.db
772      exists "/home/kclark/dev/MyApp/script/../lib/MyApp/Model"
773      exists "/home/kclark/dev/MyApp/script/../t"
774     Dumping manual schema for MyApp::Schema to directory /home/kclark/dev/MyApp/script/../lib ...
775     Schema dump completed.
776      exists "/home/kclark/dev/MyApp/script/../lib/MyApp/Model/DB.pm"
777
778 We could have also deleted C<lib/MyApp/Model/DB.pm>, but it would 
779 have regenerated the same file (note the C<exists> in the output above).
780 If you take a look at C<lib/MyApp/Model/DB.pm>, it simply contains
781 a reference to the actual schema file in C<lib/MyApp/Schema.pm>
782 along with the database connect string.
783
784 If you look in the C<lib/MyApp/Schema> directory, you will find that 
785 C<DB.pm> is no longer using L<DBIx::Class::Schema::Loader> as its 
786 base class (L<DBIx::Class::Schema::Loader> is only being used by the 
787 helper to load the schema once and then create the static files for us) 
788 and that it only contains a call to the C<load_classes> method.  You 
789 will also find that C<lib/MyApp/Schema> contains a C<Schema> 
790 subdirectory, with one file inside this directory for each of the tables 
791 in our simple database (C<Authors.pm>, C<BookAuthors.pm>, and 
792 C<Books.pm>).  These three files were created based on the information
793 found by L<DBIx::Class::Schema::Loader> as the helper ran.
794
795 The idea with all of the files created under C<lib/MyApp/Schema> by the 
796 C<create=static> option is to only edit the files below the C<# DO NOT 
797 MODIFY THIS OR ANYTHING ABOVE!> warning.  If you place all of your 
798 changes below that point in the file, you can regenerate the 
799 auto-generated information at the top of each file should your database 
800 structure get updated.
801
802 Also note the "flow" of the model information across the various files 
803 and directories.  Catalyst will initially load the model from 
804 C<lib/MyApp/Model/DB.pm>.  This file contains a reference to
805 C<lib/MyApp/Schema.pm>, so that file is loaded next.  Finally,
806 the call to C<load_classes> in that file will load each of the 
807 table-specific "results source" files from the C<lib/MyApp/Schema>
808 subdirectory.  These three table-specific DBIC schema files will then be 
809 used to create three table-specific Catalyst models every time the 
810 application starts (you can see these three model files listed in
811 the debug output generated when you launch the application).
812
813
814 =head2 Updating the Generated DBIC Schema Files
815
816
817 Let's manually add some relationship information to the auto-generated
818 schema files.  First edit C<lib/MyApp/Schema/Books.pm> and
819 add the following text below the C<# You can replace this text...> 
820 comment:
821
822     #
823     # Set relationships:
824     #   
825     
826     # has_many():
827     #   args:
828     #     1) Name of relationship, DBIC will create accessor with this name
829     #     2) Name of the model class referenced by this relationship
830     #     3) Column name in *foreign* table
831     __PACKAGE__->has_many(book_authors => 'MyApp::Schema::BookAuthors', 'book_id');
832     
833     # many_to_many():
834     #   args:
835     #     1) Name of relationship, DBIC will create accessor with this name
836     #     2) Name of has_many() relationship this many_to_many() is shortcut for 
837     #     3) Name of belongs_to() relationship in model class of has_many() above 
838     #   You must already have the has_many() defined to use a many_to_many().
839     __PACKAGE__->many_to_many(authors => 'book_authors', 'author');
840
841
842 B<Note:> Be careful to put this code I<above> the C<1;> at the end of the
843 file.  As with any Perl package, we need to end the last line with
844 a statement that evaluates to C<true>.  This is customarily done with
845 C<1;> on a line by itself.
846
847 This code defines both a C<has_many> and a C<many_to_many> relationship. 
848 The C<many_to_many> relationship is optional, but it makes it easier to 
849 map a book to its collection of authors.  Without it, we would have to 
850 "walk" though the C<book_authors> table as in C<$book-E<gt>book_authors-
851 E<gt>first-E<gt>author-E<gt>last_name> (we will see examples on how to 
852 use DBIC objects in your code soon, but note that because C<$book-
853 E<gt>book_authors> can return multiple authors, we have to use C<first> 
854 to display a single author). C<many_to_many> allows us to use the 
855 shorter C<$book-E<gt>authors-E<gt>first-E<gt>last_name>. Note that you 
856 cannot define a C<many_to_many> relationship without also having the 
857 C<has_many> relationship in place.
858
859 Then edit C<lib/MyApp/Schema/Authors.pm> and add relationship
860 information as follows (again, be careful to put in above the C<1;> but
861 below the C<# DO NOT MODIFY THIS OR ANYTHING ABOVE!> comment):
862
863     #
864     # Set relationships:
865     #
866     
867     # has_many():
868     #   args:
869     #     1) Name of relationship, DBIC will create accessor with this name
870     #     2) Name of the model class referenced by this relationship
871     #     3) Column name in *foreign* table
872     __PACKAGE__->has_many(book_author => 'MyApp::Schema::BookAuthors', 'author_id');
873     
874     # many_to_many():
875     #   args:
876     #     1) Name of relationship, DBIC will create accessor with this name
877     #     2) Name of has_many() relationship this many_to_many() is shortcut for
878     #     3) Name of belongs_to() relationship in model class of has_many() above 
879     #   You must already have the has_many() defined to use a many_to_many().
880     __PACKAGE__->many_to_many(books => 'book_author', 'book');
881
882 Finally, do the same for the "join table," 
883 C<lib/MyApp/Schema/BookAuthors.pm>:
884
885     #
886     # Set relationships:
887     #
888     
889     # belongs_to():
890     #   args:
891     #     1) Name of relationship, DBIC will create accessor with this name
892     #     2) Name of the model class referenced by this relationship
893     #     3) Column name in *this* table
894     __PACKAGE__->belongs_to(book => 'MyApp::Schema::Books', 'book_id');
895     
896     # belongs_to():
897     #   args:
898     #     1) Name of relationship, DBIC will create accessor with this name
899     #     2) Name of the model class referenced by this relationship
900     #     3) Column name in *this* table
901     __PACKAGE__->belongs_to(author => 'MyApp::Schema::Authors', 'author_id');
902
903
904 =head1 RUN THE APPLICATION
905
906 Run the Catalyst "demo server" script with the C<DBIC_TRACE> option
907 (it might still be enabled from earlier in the tutorial, but here
908 is an alternate way to specify the option just in case):
909
910     $ DBIC_TRACE=1 script/myapp_server.pl
911
912 Make sure that the application loads correctly and that you see the 
913 three dynamically created model class (one for each of the 
914 table-specific schema classes we created).
915
916 Then hit the URL L<http://localhost:3000/books/list> and be sure that
917 the book list is displayed.
918
919
920 =head1 RUNNING THE APPLICATION FROM THE COMMAND LINE
921
922 In some situations, it can be useful to run your application and 
923 display a page without using a browser.  Catalyst lets you do this 
924 using the C<scripts/myapp_test.pl> script.  Just supply the URL you 
925 wish to display and it will run that request through the normal 
926 controller dispatch logic and use the appropriate view to render the 
927 output (obviously, complex pages may dump a lot of text to your 
928 terminal window).  For example, if you type:
929
930     $ script/myapp_test.pl "/books/list"
931
932 You should get the same text as if you visited 
933 L<http://localhost:3000/books/list> with the normal development server 
934 and asked your browser to view the page source.
935
936
937 =head1 UPDATING THE VIEW
938
939 Let's add a new column to our book list page that takes advantage of
940 the relationship information we manually added to our schema files
941 in the previous section.  Edit C<root/src/books/list.tt2> add add the
942 following code below the existing table cell that contains
943 C<book.rating> (IOW, add a new table cell below the existing two 
944 C<td> cells):
945
946     <td>
947       [% # First initialize a TT variable to hold a list.  Then use a TT FOREACH -%]
948       [% # loop in 'side effect notation' to load just the last names of the     -%]
949       [% # authors into the list.  Note that the 'push' TT vmethod does not      -%]
950       [% # a value, so nothing will be printed here.  But, if you have something -%]
951       [% # in TT that does return a method and you don't want it printed, you    -%]
952       [% # can: 1) assign it to a bogus value, or 2) use the CALL keyword to     -%]
953       [% # call it and discard the return value.                                 -%]
954       [% tt_authors = [ ];
955          tt_authors.push(author.last_name) FOREACH author = book.authors %]
956       [% # Now use a TT 'virtual method' to display the author count in parens   -%]
957       [% # Note the use of the TT filter "| html" to escape dangerous characters -%]
958       ([% tt_authors.size | html %])
959       [% # Use another TT vmethod to join & print the names & comma separators   -%]
960       [% tt_authors.join(', ') | html %]
961     </td>
962
963 Then hit C<Ctrl+R> in your browser (not that you don't need to reload 
964 the development server or use the C<-r> option when updating TT 
965 templates) and you should now the the number of authors each book and 
966 a comma-separated list of the author's last names.  
967
968 If you are still running the development server with C<DBIC_TRACE> 
969 enabled, you should also now see five more C<SELECT> statements in the 
970 debug output (one for each book as the authors are being retrieved by 
971 DBIC).
972
973 Also note that we are using "| html", a type of TT filter, to escape 
974 characters such as E<lt> and E<gt> to &lt; and &gt; and avoid various
975 types of dangerous hacks against your application.  In a real 
976 application, you would probably want to put "| html" at the end of 
977 every field where a user has control over the information that can 
978 appear in that field (and can therefore inject markup or code if you
979 don't "neutralize" those fields).  In addition to "| html", Template
980 Toolkit has a variety of other useful filters that can found in the
981 documentation for L<Template::Filters|Template::Filters>.
982
983
984 =head2 Using C<RenderView> for the Default View
985
986 B<NOTE: The rest of this part of the tutorial is optional.  You can 
987 skip to Part 4, L<Basic CRUD|Catalyst::Manual::Tutorial::BasicCRUD>, 
988 if you wish.>
989
990 Once your controller logic has processed the request from a user, it 
991 forwards processing to your view in order to generate the appropriate 
992 response output.  Catalyst uses
993 L<Catalyst::Action::RenderView|Catalyst::Action::RenderView> by 
994 default to automatically performs this operation.  If you look in 
995 C<lib/MyApp/Controller/Root.pm>, you should see the empty 
996 definition for the C<sub end> method:
997
998     sub end : ActionClass('RenderView') {}
999
1000 The following bullet points provide a quick overview of the 
1001 C<RenderView> process:
1002
1003 =over 4
1004
1005 =item *
1006
1007 C<Root.pm> is designed to hold application-wide logic.
1008
1009 =item *
1010
1011 At the end of a given user request, Catalyst will call the most specific 
1012 C<end> method that's appropriate.  For example, if the controller for a 
1013 request has an C<end> method defined, it will be called.  However, if 
1014 the controller does not define a controller-specific C<end> method, the 
1015 "global" C<end> method in C<Root.pm> will be called.
1016
1017 =item *
1018
1019 Because the definition includes an C<ActionClass> attribute, the
1020 L<Catalyst::Action::RenderView|Catalyst::Action::RenderView> logic
1021 will be executed B<after> any code inside the definition of C<sub end>
1022 is run.  See L<Catalyst::Manual::Actions|Catalyst::Manual::Actions>
1023 for more information on C<ActionClass>.
1024
1025 =item *
1026
1027 Because C<sub end> is empty, this effectively just runs the default 
1028 logic in C<RenderView>.  However, you can easily extend the 
1029 C<RenderView> logic by adding your own code inside the empty method body 
1030 (C<{}>) created by the Catalyst Helpers when we first ran the 
1031 C<catalyst.pl> to initialize our application.  See 
1032 L<Catalyst::Action::RenderView|Catalyst::Action::RenderView> for more 
1033 detailed information on how to extended C<RenderView> in C<sub end>.
1034
1035 =back
1036
1037
1038 =head2 Using The Default Template Name
1039
1040 By default, C<Catalyst::View::TT> will look for a template that uses the 
1041 same name as your controller action, allowing you to save the step of 
1042 manually specifying the template name in each action.  For example, this 
1043 would allow us to remove the 
1044 C<$c-E<gt>stash-E<gt>{template} = 'books/list.tt2';> line of our 
1045 C<list> action in the Books controller.  Open 
1046 C<lib/MyApp/Controller/Books.pm> in your editor and comment out this line
1047 to match the following (only the C<$c-E<gt>stash-E<gt>{template}> line
1048 has changed):
1049
1050     =head2 list
1051     
1052     Fetch all book objects and pass to books/list.tt2 in stash to be displayed
1053     
1054     =cut
1055     
1056     sub list : Local {
1057         # Retrieve the usual Perl OO '$self' for this object. $c is the Catalyst
1058         # 'Context' that's used to 'glue together' the various components
1059         # that make up the application
1060         my ($self, $c) = @_;
1061     
1062         # Retrieve all of the book records as book model objects and store in the
1063         # stash where they can be accessed by the TT template
1064         $c->stash->{books} = [$c->model('DB::Books')->all];
1065     
1066         # Set the TT template to use.  You will almost always want to do this
1067         # in your action methods (actions methods respond to user input in
1068         # your controllers).
1069         #$c->stash->{template} = 'books/list.tt2';
1070     }
1071
1072 C<Catalyst::View::TT> defaults to looking for a template with no 
1073 extension.  In our case, we need to override this to look for an 
1074 extension of C<.tt2>.  Open C<lib/MyApp/View/TT.pm> and add the 
1075 C<TEMPLATE_EXTENSION> definition as follows:
1076
1077     __PACKAGE__->config({
1078         CATALYST_VAR => 'Catalyst',
1079         INCLUDE_PATH => [
1080             MyApp->path_to( 'root', 'src' ),
1081             MyApp->path_to( 'root', 'lib' )
1082         ],
1083         PRE_PROCESS  => 'config/main',
1084         WRAPPER      => 'site/wrapper',
1085         ERROR        => 'error.tt2',
1086         TIMER        => 0,
1087         TEMPLATE_EXTENSION => '.tt2',
1088     });
1089
1090 You should now be able to restart the development server as per the 
1091 previous section and access the L<http://localhost:3000/books/list>
1092 as before.
1093
1094 B<NOTE:> Please note that if you use the default template technique,
1095 you will B<not> be able to use either the C<$c-E<gt>forward> or
1096 the C<$c-E<gt>detach> mechanisms (these are discussed in Part 2 and 
1097 Part 9 of the Tutorial).
1098
1099
1100 =head2 Return To A Manually-Specified Template
1101
1102 In order to be able to use C<$c-E<gt>forward> and C<$c-E<gt>detach>
1103 later in the tutorial, you should remove the comment from the
1104 statement in C<sub list> in C<lib/MyApp/Controller/Books.pm>:
1105
1106     $c->stash->{template} = 'books/list.tt2';
1107
1108 Then delete the C<TEMPLATE_EXTENSION> line in  
1109 C<lib/MyApp/View/TT.pm>.
1110
1111 You should then be able to restart the development server and 
1112 access L<http://localhost:3000/books/list> in the same manner as
1113 with earlier sections.
1114
1115
1116 =head1 AUTHOR
1117
1118 Kennedy Clark, C<hkclark@gmail.com>
1119
1120 Please report any errors, issues or suggestions to the author.  The
1121 most recent version of the Catalyst Tutorial can be found at
1122 L<http://dev.catalyst.perl.org/repos/Catalyst/trunk/Catalyst-Manual/lib/Catalyst/Manual/Tutorial/>.
1123
1124 Copyright 2006-2008, Kennedy Clark, under Creative Commons License
1125 (L<http://creativecommons.org/licenses/by-nc-sa/2.5/>).
1126