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