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