Tut docs work
[catagits/Catalyst-Runtime.git] / lib / Catalyst / Manual / Tutorial / CatalystBasics.pod
1 =head1 NAME
2
3 Catalyst::Manual::Tutorial::CatalystBasics - Catalyst Tutorial - Part 2: Catalyst Application Development Basics
4
5
6 =head1 OVERVIEW
7
8 This is B<Part 2 of 9> 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 B<Catalyst Basics>
21
22 =item 3
23
24 L<Basic CRUD|Catalyst::Manual::Tutorial::BasicCRUD>
25
26 =item 4
27
28 L<Authentication|Catalyst::Manual::Tutorial::Authentication>
29
30 =item 5
31
32 L<Authorization|Catalyst::Manual::Tutorial::Authorization>
33
34 =item 6
35
36 L<Debugging|Catalyst::Manual::Tutorial::Debugging>
37
38 =item 7
39
40 L<Testing|Catalyst::Manual::Tutorial::Testing>
41
42 =item 8
43
44 L<Advanced CRUD|Catalyst::Manual::Tutorial::AdvancedCRUD>
45
46 =item 9
47
48 L<Appendices|Catalyst::Manual::Tutorial::Appendicies>
49
50 =back
51
52 =head1 DESCRIPTION
53
54 In this part of the tutorial, we will create a very basic Catalyst web
55 application.  Though simple in many respects, this section will already
56 demonstrate a number of powerful capabilities such as:
57
58 =over 4
59
60 =item * Helper Scripts
61
62 Catalyst helper scripts that can be used to rapidly bootstrap the
63 skeletal structure of an application.
64
65 =item * MVC
66
67 Model/View/Controller (MVC) provides an architecture that facilitates a
68 clean "separation of control" between the different portions of your
69 application. Given that many other documents cover this subject in
70 detail, MVC will not be discussed in depth here (for an excellent
71 introduction to MVC and general Catalyst concepts, please see
72 L<Catalyst::Manual::About>. In short:
73
74 =over 4
75
76 =item * Model
77
78 The model usually represents a data store. In most applications, the
79 model equates to the objects that are created from and saved to your SQL
80 database.
81
82 =item * View
83
84 The view takes model objects and renders them into something for the end
85 user to look at. Normally this involves a template-generation tool that
86 creates HTML for the user's web browser, but it could easily be code
87 that generates other forms such as PDF documents, e-mails, or Excel
88 spreadsheets.
89
90 =item * Controller
91
92 As suggested by its name, the controller takes user requests and routes
93 them to the necessary model and view.
94
95 =back
96
97 =item * ORM
98
99 The use of Object-Relational Mapping (ORM) technology for database
100 access. Specifically, ORM provides an automated and standardized means
101 to persist and restore objects to/from a relational database.
102
103 =back
104
105 B<TIP>: Note that all of the code for this part of the tutorial can be
106 pulled from the Catalyst Subversion repository in one step with the
107 following command:
108
109     svn checkout http://dev.catalyst.perl.org/repos/Catalyst/trunk/examples/Tutorial@###
110     IMPORTANT: Does not work yet.  Will be completed for final version.
111
112
113 =head1 CREATE A CATALYST PROJECT
114
115 Catalyst provides a number of helper scripts that can be used to quickly
116 flesh out the basic structure of your application. All Catalyst projects
117 begin with the C<catalyst.pl> helper.
118
119 In the case of this tutorial, use the Catalyst C<catalyst.pl> script to
120 initialize the framework for an application called C<MyApp>:
121
122     $ catalyst.pl MyApp
123     $ cd MyApp
124
125 The C<catalyst.pl> helper script will display the names of the
126 directories and files it creates.
127
128 Though it's too early for any significant celebration, we already have a
129 functioning application. Run the following command to run this
130 application with the built-in development web server:
131
132         $ script/myapp_server.pl
133
134 Point your web browser to L<http://localhost:3000> (substituting a
135 different hostname or IP address as appropriate) and you should be
136 greeted by the Catalyst welcome screen.  Press Ctrl-C to break out of
137 the development server.
138
139 =head1 CREATE A SQLITE DATABASE
140
141 In this step, we make a text file with the required SQL commands to
142 create a database table and load some sample data.  Open C<myapp01.sql>
143 in your editor and enter:
144
145     --
146     -- Create a very simple database to hold book and author information
147     --
148     CREATE TABLE books (
149             id          INTEGER PRIMARY KEY,
150             title       TEXT ,
151             rating      INTEGER
152     );
153     -- 'book_authors' is a many-to-many join table between books & authors
154     CREATE TABLE book_authors (
155             book_id     INTEGER,
156             author_id   INTEGER,
157             PRIMARY KEY (book_id, author_id)
158     );
159     CREATE TABLE authors (
160             id          INTEGER PRIMARY KEY,
161             first_name  TEXT,
162             last_name   TEXT
163     );
164     ---
165     --- Load some sample data
166     ---
167     INSERT INTO books VALUES (1, 'CCSP SNRS Exam Certification Guide', 5);
168     INSERT INTO books VALUES (2, 'TCP/IP Illustrated, Volume 1', 5);
169     INSERT INTO books VALUES (3, 'Internetworking with TCP/IP Vol.1', 4);
170     INSERT INTO books VALUES (4, 'Perl Cookbook', 5);
171     INSERT INTO books VALUES (5, 'Designing with Web Standards', 5);
172     INSERT INTO authors VALUES (1, 'Greg', 'Bastien');
173     INSERT INTO authors VALUES (2, 'Sara', 'Nasseh');
174     INSERT INTO authors VALUES (3, 'Christian', 'Degu');
175     INSERT INTO authors VALUES (4, 'Richard', 'Stevens');
176     INSERT INTO authors VALUES (5, 'Douglas', 'Comer');
177     INSERT INTO authors VALUES (6, 'Tom', 'Christiansen');
178     INSERT INTO authors VALUES (7, ' Nathan', 'Torkington');
179     INSERT INTO authors VALUES (8, 'Jeffrey', 'Zeldman');
180     INSERT INTO book_authors VALUES (1, 1);
181     INSERT INTO book_authors VALUES (1, 2);
182     INSERT INTO book_authors VALUES (1, 3);
183     INSERT INTO book_authors VALUES (2, 4);
184     INSERT INTO book_authors VALUES (3, 5);
185     INSERT INTO book_authors VALUES (4, 6);
186     INSERT INTO book_authors VALUES (4, 7);
187     INSERT INTO book_authors VALUES (5, 8);
188
189 B<TIP>: See Appendix 1 for tips on removing the leading spaces when
190 cutting and pasting example code from POD documents.
191
192 Then use the following command to build a C<myapp.db> SQLite database:
193
194     $ sqlite3 myapp.db < myapp01.sql
195
196 If you need to create the database more than once, you probably want to
197 issue the C<rm myapp.db> command to delete the database before you use
198 the C<sqlite3 myapp.db < myapp01.sql> command.
199
200 Once the C<myapp.db> database file has been created and initialized, you
201 can use the SQLite command line environment to do a quick dump of the
202 database contents:
203
204     $ sqlite3 myapp.db
205     SQLite version 3.2.2
206     Enter ".help" for instructions
207     sqlite> select * from books;
208     1|CCSP SNRS Exam Certification Guide|5
209     2|TCP/IP Illustrated, Volume 1|5
210     3|Internetworking with TCP/IP Vol.1|4
211     4|Perl Cookbook|5
212     5|Designing with Web Standards|5
213     sqlite> .q
214     $
215
216 Or:
217
218     $ sqlite3 myapp.db "select * from books"
219     1|CCSP SNRS Exam Certification Guide|5
220     2|TCP/IP Illustrated, Volume 1|5
221     3|Internetworking with TCP/IP Vol.1|4
222     4|Perl Cookbook|5
223     5|Designing with Web Standards|5
224
225 As with most other SQL tools, if you are using the full "interactive"
226 environment you need to terminate your SQL commands with a ";" (it's not
227 required if you do a single SQL statement on the command line).  Use
228 ".q" to exit from SQLite from the SQLite interactive mode and return to
229 your OS command prompt.
230
231
232 =head1 EDIT THE LIST OF CATALYST PLUGINS
233
234 One of the greatest benefits of Catalyst is that it has such a large
235 library of plugins available.  Plugins are used to seamlessly integrate
236 existing Perl modules into the overall Catalyst framework.  In general,
237 they do this by adding additional methods to the C<context> object
238 (generally written as C<$c>) that Catalyst passes to every component
239 throughout the framework.
240
241 By default, Catalyst enables three plugins/flags:
242
243 =over 4
244
245 =item * 
246
247 C<-Debug> Flag
248
249 Enables the Catalyst debug output you saw when we started the
250 C<script/myapp_server.pl> development server earlier.  You can remove
251 this plugin when you place your application into production.
252
253 As you may have noticed, C<-Debug> is not a plugin, but a I<flag>.
254 Although most of the items specified on the C<use Catalyst> line of your
255 application class will be plugins, Catalyst supports a limited number of
256 flag options (of these, C<-Debug> is the most common).
257
258 If you prefer, you can use the C<$c-E<gt>debug> method to enable debug
259 messages.
260
261 =item *
262
263 L<Catalyst::Plugin::ConfigLoader|Catalyst::Plugin::ConfigLoader>
264
265 C<ConfigLoader> provides an automatic way to load configurable
266 parameters for your application from a central YAML file (versus having
267 the values hard-coded inside your Perl modules).  If you have not been
268 exposed to YAML before, it is a human-readable data serialization format
269 that can be used to read (and write) values to/from text files.  We will
270 see how to use this feature of Catalyst during the authentication and
271 authorization sections (Part 4 and Part 5).
272
273 =item *
274
275 L<Catalyst::Plugin::Static::Simple>
276
277 C<Static::Simple> provides an easy method of serving static content such
278 as images and CSS files under the development server.
279
280 =back
281
282 To modify the list of plugins, edit C<lib/MyApp.pm> (this file is
283 generally referred to as your I<application class>) and delete the line
284 with:
285
286     use Catalyst qw/-Debug ConfigLoader Static::Simple/;
287
288 Replace it with:
289
290     use Catalyst qw/
291             -Debug
292             ConfigLoader
293             Static::Simple
294             
295             StackTrace
296             DefaultEnd
297             /;
298
299 This tells Catalyst to start using three new plugins:
300
301 =over 4
302
303 =item * 
304
305 L<Catalyst::Plugin::StackTrace|Catalyst::Plugin::StackTrace>
306
307 Adds a stack trace to the standard Catalyst "debug screen" (this is the
308 screen Catalyst sends to your browser when an error occurs).
309
310 Note: L<StackTrace|Catalyst::Plugin::StackTrace> output appears in your
311 browser, not in the console window from which you're running your
312 application, which is where logging output usually goes.
313
314 =item * 
315
316 L<Catalyst::Plugin::DefaultEnd|Catalyst::Plugin::DefaultEnd>
317
318 Automatically provides a Catalyst "end action" that invokes your view at
319 the end of each request.  Also allows you to add "dump_info=1" (precede
320 with "?" or "&" depending on where it is in the URL) to I<force> the
321 debug screen at the end of the Catalyst request processing cycle.
322
323 B<TIP>: Many Catalyst-related documents predate
324 L<DefaultEnd|Catalyst::Plugin::DefaultEnd> and suggest that you add an
325 C<end> action to your application class (C<MyApp.pm>) or Root.pm
326 (C<MyApp/Controller/Root.pm>).  In most of these cases, you can convert
327 to L<DefaultEnd|Catalyst::Plugin::DefaultEnd> by deleting the C<end>
328 action and using the plugin instead. There are certainly cases when
329 you'd want to write your own custom C<end> action, but for most
330 circumstances, DefaultEnd will be exactly what you want.
331
332 =back
333
334 Note that when specifying plugins on the C<use Catalyst> line, you can
335 omit C<Catalyst::Plugin::> from the name.  Additionally, you can spread
336 the plugin names across multiple lines as shown here, or place them all
337 on one (or more) lines as with the default configuration.
338
339 =head1 DATABASE ACCESS WITH C<DBIx::Class>
340
341 Catalyst can be used with virtually any form of persistent datastore
342 available via Perl.  For example, L<Catalyst::Model::DBI> can be used to
343 easily access databases through the traditional Perl L<DBI> interface.
344 However, most Catalyst applications use some form of ORM technology to
345 automatically create and save model objects as they are used.  Although
346 Tony Bowden's L<Class::DBI> has been the traditional Perl ORM engine,
347 Matt Trout's L<DBIx::Class> (abbreviated as "DBIC") has rapidly emerged
348 as the Perl-based ORM technology of choice.  Most new Catalyst
349 applications rely on DBIC, as will this tutorial.
350
351 Note: See L<Catalyst:: Model::CDBI > for more information on using
352 Catalyst with L<Class::DBI>.
353
354 =head2 Create a DBIC Schema File
355
356 DBIx::Class uses a schema file to load other classes that represent the
357 tables in your database (DBIC refers to these "table objects" as "result
358 sources"; see L<DBIx::Class::ResultSource>).  In this case, we want to
359 load the model object for the C<books>, C<book_authors>, and C<authors>
360 tables created in the previous step.
361
362 Open C<lib/MyAppDB.pm> in your editor and insert:
363
364     package MyAppDB;
365     
366     =head1 NAME 
367     
368     MyAppDB - DBIC Schema Class
369     
370     =cut
371     
372     # Our schema needs to inherit from 'DBIx::Class::Schema'
373     use base qw/DBIx::Class::Schema/;
374     
375     # Need to load the DB Model classes here.
376     # You can use this syntax if you want:
377     #    __PACKAGE__->load_classes(qw/Book BookAuthor Author/);
378     # Also, if you simply want to load all of the classes in a directory
379     # of the same name as your schema class (as we do here) you can use:
380     #    __PACKAGE__->load_classes(qw//);
381     # But the variation below is more flexible in that it can be used to 
382     # load from multiple namespaces.
383     __PACKAGE__->load_classes({
384         MyAppDB => [qw/Book BookAuthor Author/]
385     });
386     
387     1;
388
389 B<Note:> C<__PACKAGE__> is just a shorthand way of referencing the name
390 of the package where it is used.  Therefore, in C<MyAppDB.pm>,
391 C<__PACKAGE__> is equivalent to C<MyAppDB>
392
393
394 =head2 Create the DBIC "Result Source" Files
395
396 In this step, we create "table classes" (again, these are called a
397 "result source" classes in DBIC) that act as model objects for the
398 C<books>, C<book_authors>, and C<authors> tables in our database.
399
400 First, create a directory to hold the class:
401
402     $ mkdir lib/MyAppDB
403
404 Then open C<lib/MyAppDB/Book.pm> in your editor and enter:
405
406     package MyAppDB::Book;
407     
408     use base qw/DBIx::Class/;  
409     
410     # Load required DBIC stuff
411     __PACKAGE__->load_components(qw/PK::Auto Core/);
412     # Set the table name
413     __PACKAGE__->table('books');
414     # Set columns in table
415     __PACKAGE__->add_columns(qw/id title rating/);
416     # Set the primary key for the table
417     __PACKAGE__->set_primary_key(qw/id/);
418     
419     #
420     # Set relationships:
421     #
422     
423     # has_many():
424     #   args:
425     #     1) Name of relationship, DBIC will create accessor with this name
426     #     2) Name of the model class referenced by this relationship
427     #     3) Column name in *foreign* table
428     __PACKAGE__->has_many(book_authors => 'MyAppDB::BookAuthor', 'book_id');
429     
430     # many_to_many():
431     #   args:
432     #     1) Name of relationship, DBIC will create accessor with this name
433     #     2) Name of has_many() relationship this many_to_many() is shortcut for
434     #     3) Name of belongs_to() relationship in model class of has_many() above 
435     #   You must already have the has_many() defined to use a many_to_many().
436     __PACKAGE__->many_to_many(authors => 'book_authors', 'author');
437     
438     
439     =head1 NAME
440     
441     MyAppDB::Book - A model object representing a book.
442     
443     =head1 DESCRIPTION
444     
445     This is an object that represents a row in the 'books' table of your application
446     database.  It uses DBIx::Class (aka, DBIC) to do ORM.
447     
448     For Catalyst, this is designed to be used through MyApp::Model::MyAppDB.
449     Offline utilities may wish to use this class directly.
450     
451     =cut
452     
453     1;
454
455 This defines both a C<has_many> and a C<many_to_many> relationship.  The
456 C<many_to_many> relationship is optional, but it makes it easier to map
457 a book to its collection of authors.  Without it, we would have to
458 "walk" though the C<book_authors> table as in
459 C<$book-E<gt>book_authors-E<gt>first-E<gt>author-E<gt>last_name> (we
460 will see examples on how to use DBIC objects in your code soon, but note
461 that because C<$book-E<gt>book_authors> can return multiple authors, we
462 have to use C<first> to display a single author). C<many_to_many> allows
463 us to use the shorter C<$book-E<gt>authors-E<gt>first-E<gt>last_name>.
464 Note that you cannot define a C<many_to_many> relationship without also
465 having the C<has_many> relationship in place.
466
467 Next, open C<lib/MyAppDB/Author.pm> in your editor and enter:
468
469     package MyAppDB::Author;
470     
471     use base qw/DBIx::Class/;
472     
473     # Load required DBIC stuff
474     __PACKAGE__->load_components(qw/PK::Auto Core/);
475     # Set the table name
476     __PACKAGE__->table('authors');
477     # Set columns in table
478     __PACKAGE__->add_columns(qw/id first_name last_name/);
479     # Set the primary key for the table
480     __PACKAGE__->set_primary_key(qw/id/);
481
482     #
483     # Set relationships:
484     #
485     
486     # has_many():
487     #   args:
488     #     1) Name of relationship, DBIC will create accessor with this name
489     #     2) Name of the model class referenced by this relationship
490     #     3) Column name in *foreign* table
491     __PACKAGE__->has_many(book_author => 'MyAppDB::BookAuthor', 'author_id');
492     
493     # many_to_many():
494     #   args:
495     #     1) Name of relationship, DBIC will create accessor with this name
496     #     2) Name of has_many() relationship this many_to_many() is shortcut for
497     #     3) Name of belongs_to() relationship in model class of has_many() above 
498     #   You must already have the has_many() defined to use a many_to_many().
499     __PACKAGE__->many_to_many(books => 'book_author', 'book');
500     
501     
502     =head1 NAME
503     
504     MyAppDB::Author - A model object representing an author of a book (if a book has 
505     multiple authors, each will be represented be separate Author object).
506     
507     =head1 DESCRIPTION
508     
509     This is an object that represents a row in the 'authors' table of your application
510     database.  It uses DBIx::Class (aka, DBIC) to do ORM.
511     
512     For Catalyst, this is designed to be used through MyApp::Model::MyAppDB.
513     Offline utilities may wish to use this class directly.
514     
515     =cut
516     
517     1;
518
519 Finally, open C<lib/MyAppDB/BookAuthor.pm> in your editor and enter:
520
521     package MyAppDB::BookAuthor;
522     
523     use base qw/DBIx::Class/;
524     
525     # Load required DBIC stuff
526     __PACKAGE__->load_components(qw/PK::Auto Core/);
527     # Set the table name
528     __PACKAGE__->table('book_authors');
529     # Set columns in table
530     __PACKAGE__->add_columns(qw/book_id author_id/);
531     # Set the primary key for the table
532     __PACKAGE__->set_primary_key(qw/book_id author_id/);
533     
534     #
535     # Set relationships:
536     #
537     
538     # belongs_to():
539     #   args:
540     #     1) Name of relationship, DBIC will create accessor with this name
541     #     2) Name of the model class referenced by this relationship
542     #     3) Column name in *this* table
543     __PACKAGE__->belongs_to(book => 'MyAppDB::Book', 'book_id');
544
545     # belongs_to():
546     #   args:
547     #     1) Name of relationship, DBIC will create accessor with this name
548     #     2) Name of the model class referenced by this relationship
549     #     3) Column name in *this* table
550     __PACKAGE__->belongs_to(author => 'MyAppDB::Author', 'author_id');
551     
552     
553     =head1 NAME
554     
555     MyAppDB::BookAuthor - A model object representing the JOIN between an author and 
556     a book.
557     
558     =head1 DESCRIPTION
559     
560     This is an object that represents a row in the 'book_authors' table of your 
561     application database.  It uses DBIx::Class (aka, DBIC) to do ORM.
562
563     You probably won't need to use this class directly -- it will be automatically
564     used by DBIC where joins are needed.
565     
566     For Catalyst, this is designed to be used through MyApp::Model::MyAppDB.
567     Offline utilities may wish to use this class directly.
568     
569     =cut
570     
571     1;
572
573 B<Note:> This sample application uses a plural form for the database
574 tables (e.g., C<books> and C<authors>) and a singular form for the model
575 objects (e.g., C<Book> and C<Author>); however, Catalyst places no
576 restrictions on the naming conventions you wish to use.
577
578 =head2 Use C<Catalyst::Model::DBIC::Schema> To Load The Model Class
579
580 When L<Catalyst::Model::DBIC::Schema> is
581 in use, Catalyst essentially reads an existing copy of your database
582 model and creates a new set of objects under C<MyApp::Model> for use
583 inside of Catalyst.
584
585 B<Note:> With L<Catalyst::Model::DBIC::Schema> you essentially end up
586 with two sets of model classes (only one of which you write... the other
587 set is created automatically in memory when your Catalyst application
588 initializes).  For this tutorial application, the important points to
589 remember are: you write the I<result source> files in C<MyAppDB>, but
590 I<within Catalyst> you use the I<automatically created model classes> in
591 C<MyApp::Model>.
592
593 Use the L<Catalyst::Helper::Model::DBIC::Schema > helper script to
594 create the model class that loads up the model we created in the
595 previous step:
596
597     $ script/myapp_create.pl model MyAppDB DBIC::Schema MyAppDB dbi:SQLite:myapp.db '' '' '{ AutoCommit => 1 }'
598
599 Where the first C<MyAppDB> is the name of the class to be created by the
600 helper in C<lib/MyApp/Model> and the second C<MyAppDB> is the name of
601 existing schema file we created (in C<lib/MyAppDB.pm>).  You can see
602 that the helper creates a model file under C<lib/MyApp/Model> (Catalyst
603 has a separate directory under C<lib/MyApp> for each of the three parts
604 of MVC: C<Model>, C<View>, and C<Controller> [although older Catalyst
605 applications often use the directories C<M>, C<V>, and C<C>]).
606
607
608 =head1 CREATE A CATALYST CONTROLLER
609
610 Controllers are where you write methods that interact with user
611 input--typically, controller methods respond to C<GET> and C<POST>
612 messages from the user's web browser.
613
614 Use the Catalyst C<create> script to add a controller for book-related
615 actions:
616
617     $ script/myapp_create.pl controller Books
618
619 Then edit C<lib/MyApp/Controller/Books.pm> and add the following method
620 to the controller:
621
622     =head2 list
623     
624     Fetch all book objects and pass to books/list.tt2 in stash to be displayed
625     
626     =cut
627      
628     sub list : Local {
629         # Retrieve the usual perl OO '$self' for this object. $c is the Catalyst
630         # 'Context' that's used to 'glue together' the various components
631         # that make up the application
632         my ($self, $c) = @_;
633     
634         # Retrieve all of the book records as book model objects and store in the
635         # stash where they can be accessed by the TT template
636         $c->stash->{books} = [$c->model('MyAppDB::Book')->all];
637         
638         # Set the TT template to use.  You will almost always want to do this
639         # in your action methods.
640         $c->stash->{template} = 'books/list.tt2';
641     }
642
643 B<Note:> Programmers experienced with object-oriented Perl should
644 recognize C<$self> as a reference to the object where this method was
645 called.  On the other hand, C<$c> will be new to many Perl programmers
646 who have not used Catalyst before (it's sometimes written as
647 C<$context>).  The Context object is automatically passed to all
648 Catalyst components.  It is used to pass information between components
649 and provide access to Catalyst and plugin functionality.
650
651 B<TIP>: You may see the C<$c-E<gt>model('MyAppDB::Book')> used above
652 written as C<$c-E<gt>model('MyAppDB')-E<gt>resultset('Book)>.  The two
653 are equivalent.
654
655 B<Note:> Catalyst actions are regular Perl methods, but they make use of
656 Nicholas Clark's C<attributes> module to provide additional information
657 to the Catalyst dispatcher logic.
658
659 =head1 CATALYST VIEWS
660
661 Views are where you render output, typically for display in the user's
662 web browser, but also possibly using other display our output-generation
663 systems.  As with virtually every aspect of Catalyst, options abound
664 when it comes to the specific view technology you adopt inside your
665 application.  However, most Catalyst applications use the Template
666 Toolkit, known as TT (for more information on TT, see
667 L<http://www.template-toolkit.org>). Other popular View technologies
668 include Mason (L<http://www.masonhq.com> and
669 L<http://www.masonbook.com>) and L<HTML::Template>
670 (L<http://html-template.sourceforge.net>).
671
672 =head2 Create a Catalyst View Using C<TTSITE>
673
674 When using TT for the Catalyst view, there are two main helper scripts:
675
676 =over 4
677
678 =item *
679
680 L<Catalyst::Helper::View::TT>
681
682 =item *
683
684 L<Catalyst::Helper::View::TTSite>
685
686 =back
687
688 Both are similar, but C<TT> merely creates the C<lib/MyApp/View/TT.pm>
689 file and leaves the creation of any hierarchical template organization
690 entirely up to you. (It also creates a C<t/view_TT.t> file for testing;
691 test cases will be discussed in Part 7). The C<TTSite> helper creates a
692 modular and hierarchical view layout with separate Template Toolkit (TT)
693 files for common header and footer information, configuration values, a
694 CSS stylesheet, and more.
695
696 Enter the following command to enable the C<TTSite> style of view
697 rendering for this tutorial:
698
699     $ script/myapp_create.pl view TT TTSite
700
701 This puts a number of files in the C<root/lib> and C<root/src>
702 directories that can be used to customize the look and feel of your
703 application.  Also take a look at C<lib/MyApp/View/TT.pm> for config
704 values set by the C<TTSite> helper.
705
706 B<TIP>: Note that TTSite does one thing that could confuse people who
707 are used to the normal C<TT> Catalyst View: it redefines the Catalyst
708 context object in templates from its usual C<c> to C<Catalyst>. When
709 looking at other Catalyst examples, remember that they almost always use
710 C<c>.  Note that Catalyst and TT I<do not complain> when you use the
711 wrong name to access the context object...TT simply outputs blanks for
712 that bogus logic.  Finally, be aware that this change in name I<only>
713 applies to how the context object is accessed inside your TT templates;
714 your controllers will continue to use C<$c> (or whatever name you use
715 when fetching the reference from C<@_> inside your methods). (You can
716 change back to the "default" behavior be removing the C<CATALYST_VAR>
717 line from C<lib/MyApp/View/TT.pm>, but you will also have to edit
718 C<root/lib/config/main> and C<root/lib/config/url>.  If you do this, be
719 careful not to have a collision between your own C<c> variable and the
720 Catalyst C<c> variable.)
721
722 =head2 Globally Customize Every View
723
724 When using TTSite, files in the subdirectories of C<root/lib> can be
725 used to make changes that will appear in every view.  For example, to
726 display optional status and error messages in every view, edit
727 C<root/lib/site/layout>, updating it to match the following (the two HTML
728 C<span> elements are new):
729
730     <div id="header">[% PROCESS site/header %]</div>
731     
732     <div id="content">
733     <span class="message">[% status_msg %]</span>
734     <span class="error">[% error_msg %]</span>
735     [% content %]
736     </div>
737     
738     <div id="footer">[% PROCESS site/footer %]</div>
739
740 If we set either message in the Catalyst stash (e.g.,
741 C<$c-E<gt>stash-E<gt>{status_msg} = 'Request was successful!'>) it will
742 be displayed whenever any view used by that request is rendered.  The
743 C<message> and C<error> CSS styles are automatically defined in
744 C<root/src/ttsite.css> and can be customized to suit your needs.
745
746 B<Note:> The Catalyst stash only lasts for a single HTTP request.  If
747 you need to retain information across requests you can use
748 L<Catalyst::Plugin::Session> (we will use
749 Catalyst sessions in the Authentication part).
750
751
752 =head2 Create a TT Template Page
753
754 To add a new page of content to the TTSite view hierarchy, just create a
755 new C<.tt2> file in C<root/src>.  Only include HTML markup that goes
756 inside the HTML <body> and </body> tags, TTSite will use the contents of
757 C<root/lib/site> to add the top and bottom.
758
759 First create a directory for book-related TT templates:
760
761     $ mkdir root/src/books
762
763 Then open C<root/src/books/list.tt2> in your editor and enter:
764
765     [% # This is a TT comment.  The '-' at the end "chomps" the newline.  You won't -%]
766     [% # see this "chomping" in your browser because HTML ignores blank lines, but  -%]
767     [% # it WILL eliminate a blank line if you view the HTML source.  It's purely   -%]
768     [%- # optional, but both the beginning and the ending TT tags support chomping. -%]
769     
770     [% # Provide a title to root/lib/site/header -%]
771     [% META title = 'Book List' -%]
772     
773     <table>
774     <tr><th>Title</th><th>Rating</th><th>Author(s)</th></tr>
775     [% # Display each book in a table row %]
776     [% FOREACH book IN books -%]
777       <tr>
778         <td>[% book.title %]</td>
779         <td>[% book.rating %]</td>
780         <td>
781           [% # Print author count in parens. 'book.authors' uses the 'many_to_many' -%]
782           [% # relationship to retrieve all of the authors of a book. 'size' is a   -%]
783           [% # TT VMethod to get the number of elements in a list.                  -%]
784           ([% book.authors.size %])
785           [% # Use an alternate form of a FOREACH loop to display authors.          -%]
786           [% # _ below is the TT string concatenation operator.                     -%]
787           [% author.last_name _' ' FOREACH author = book.authors %]
788           [% # Note: if many_to_many relationship not used in Authors.pm, you could -%]
789           [% # have used the following to 'walk' through the 'join table objects'   -%]
790           [% # bk_author.author.last_name _' ' FOREACH bk_author = book.book_authors %]
791         </td>
792       </tr>
793     [% END -%]
794     </table>
795
796 As indicated by the inline comments above, the C<META title> line uses
797 TT's META feature to provide a title to C<root/lib/site/header>.
798 Meanwhile, the outer C<FOREACH> loop iterates through each C<book> model
799 object and prints the C<title> and C<rating> fields.  An inner
800 C<FOREACH> loop prints the last name of each author in a single table
801 cell (a simple space is used between the names; in reality you would
802 probably want to modify the code to use a comma as a separator).
803
804 If you are new to TT, the C<[%> and C<%]> tags are used to delimit TT
805 code.  TT supports a wide variety of directives for "calling" other
806 files, looping, conditional logic, etc.  In general, TT simplifies the
807 usual range of Perl operators down to the single dot (C<.>) operator.
808 This applies to operations as diverse as method calls, hash lookups, and
809 list index values (see
810 L<http://www.template-toolkit.org/docs/default/Manual/Variables.html>
811 for details and examples).  In addition to the usual C<Template> module
812 Pod documentation, you can access the TT manual at
813 L<http://www.template-toolkit.org/docs/default/>.
814
815 B<NOTE>: The C<TTSite> helper creates several TT files using an
816 extension of C<.tt2>. Most other Catalyst and TT examples use an
817 extension of C<.tt>.  You can use either extension (or no extension at
818 all) with TTSite and TT, just be sure to use the appropriate extension
819 for both the file itself I<and> the C<$c-E<gt>stash-E<gt>{template} =
820 ...> line in your controller.  This document will use C<.tt2> for
821 consistency with the files already created by the C<TTSite> helper.
822
823
824 =head1 RUN THE APPLICATION
825
826 First, let's enable an environment variable option that causes
827 DBIx::Class to dump the SQL statements it's using to access the database
828 (this option can provide extremely helpful troubleshooting information):
829
830     $ export DBIX_CLASS_STORAGE_DBI_DEBUG=1
831
832 B<NOTE>: You can also set this in your code using
833 C<$class-E<gt>storage-E<gt>debug(1);>.  See
834 L<DBIx::Class::Manual::Troubleshooting> for details (including options
835 to log to file instead of displaying to the Catalyst development server
836 log).
837
838 Then run the Catalyst "demo server" script:    
839
840     $ script/myapp_server.pl
841
842 You should get something like this:
843
844     $ script/myapp_server.pl
845     [Tue May 16 12:51:33 2006] [catalyst] [debug] Debug messages enabled
846     [Tue May 16 12:51:33 2006] [catalyst] [debug] Loaded plugins:
847     .------------------------------------------------------------------------------.
848     | Catalyst::Plugin::ConfigLoader 0.07                                          |
849     | Catalyst::Plugin::Static::Simple 0.14                                        |
850     | Catalyst::Plugin::StackTrace 0.04                                            |
851     | Catalyst::Plugin::DefaultEnd 0.06                                            |
852     '------------------------------------------------------------------------------'
853     
854     [Tue May 16 12:51:33 2006] [catalyst] [debug] Loaded dispatcher "Catalyst::Dispatcher"
855     [Tue May 16 12:51:33 2006] [catalyst] [debug] Loaded engine "Catalyst::Engine::HTTP"
856     [Tue May 16 12:51:33 2006] [catalyst] [debug] Found home "/home/me/MyApp"
857     [Tue May 16 12:51:37 2006] [catalyst] [debug] Loaded components:
858     .-------------------------------------------------------------------+----------.
859     | Class                                                             | Type     |
860     +-------------------------------------------------------------------+----------+
861     | MyApp::Controller::Books                                          | instance |
862     | MyApp::Controller::Root                                           | instance |
863     | MyApp::Model::MyAppDB                                             | instance |
864     | MyApp::Model::MyAppDB::Author                                     | class    |
865     | MyApp::Model::MyAppDB::Book                                       | class    |
866     | MyApp::Model::MyAppDB::BookAuthor                                 | class    |
867     | MyApp::View::TT                                                   | instance |
868     '-------------------------------------------------------------------+----------'
869     
870     [Tue May 16 12:51:37 2006] [catalyst] [debug] Loaded Private actions:
871     .----------------------+----------------------------------------+--------------.
872     | Private              | Class                                  | Method       |
873     +----------------------+----------------------------------------+--------------+
874     | /default             | MyApp::Controller::Root                | default      |
875     | /end                 | MyApp                                  | end          |
876     | /books/list          | MyApp::Controller::Books               | list         |
877     '----------------------+----------------------------------------+--------------'
878     
879     [Tue May 16 12:51:37 2006] [catalyst] [debug] Loaded Path actions:
880     .--------------------------------------+---------------------------------------.
881     | Path                                 | Private                               |
882     +--------------------------------------+---------------------------------------+
883     | /books/list                          | /books/list                           |
884     '--------------------------------------+---------------------------------------'
885     
886     [Tue May 16 12:51:37 2006] [catalyst] [info] MyApp powered by Catalyst 5.6902
887     You can connect to your server at http://localhost:3000
888
889 Some things you should note in the output above:
890
891 =over 4
892
893 =item * 
894
895 Catalyst::Model::DBIC::Schema took our C<MyAppDB::Book> and made it
896 C<MyApp::Model::MyAppDB::Book> (and similar actions were performed on
897 C<MyAppDB::Author> and C<MyAppDB::BookAuthor>).
898
899 =item * 
900
901 The "list" action in our Books controller showed up with a path of
902 C</books/list>.
903
904 =back
905
906 Point your browser to L<http://localhost:3000> and you should still get
907 the Catalyst welcome page.
908
909 Next, to view the book list, change the URL in your browser to
910 L<http://localhost:3000/books/list>. You should get a list of the five
911 books loaded by the C<myapp01.sql> script above, with TTSite providing
912 the formatting for the very simple output we generated in our template.
913 The count and space-separated list of author last names appear on the
914 end of each row.
915
916 Also notice in the output of the C<script/myapp_server.pl> that DBIC
917 used the following SQL to retrieve the data:
918
919     SELECT me.id, me.title, me.rating FROM books me
920
921 Along with a list of the following commands to retrieve the authors for
922 each book (the lines have been "word wrapped" here to improve
923 legibility):
924
925     SELECT author.id, author.first_name, author.last_name 
926         FROM book_authors me  
927         JOIN authors author ON ( author.id = me.author_id ) 
928         WHERE ( me.book_id = ? ): `1'
929
930 You should see 10 such lines of debug output, two for each of the five
931 author_id values (it pulls the data once for the count logic and another
932 time to actually display the list).
933
934
935 =head1 AUTHOR
936
937 Kennedy Clark, C<hkclark@gmail.com>
938
939 Please report any errors, issues or suggestions to the author.
940
941 Copyright 2006, Kennedy Clark, under Creative Commons License
942 (L<http://creativecommons.org/licenses/by-nc-sa/2.5/>).
943
944 Version: .94
945