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