Add section to discuss use of default template names.
[catagits/Catalyst-Runtime.git] / lib / Catalyst / Manual / Tutorial / CatalystBasics.pod
CommitLineData
4d583dd8 1=head1 NAME
2
64ccd8a8 3Catalyst::Manual::Tutorial::CatalystBasics - Catalyst Tutorial - Part 2: Catalyst Application Development Basics
4d583dd8 4
5
4d583dd8 6=head1 OVERVIEW
7
8This is B<Part 2 of 9> for the Catalyst tutorial.
9
64ccd8a8 10L<Tutorial Overview|Catalyst::Manual::Tutorial>
4d583dd8 11
12=over 4
13
14=item 1
15
16L<Introduction|Catalyst::Manual::Tutorial::Intro>
17
18=item 2
19
20B<Catalyst Basics>
21
22=item 3
23
653f4595 24L<Basic CRUD|Catalyst::Manual::Tutorial::BasicCRUD>
4d583dd8 25
26=item 4
27
28L<Authentication|Catalyst::Manual::Tutorial::Authentication>
29
30=item 5
31
32L<Authorization|Catalyst::Manual::Tutorial::Authorization>
33
34=item 6
35
36L<Debugging|Catalyst::Manual::Tutorial::Debugging>
37
38=item 7
39
40L<Testing|Catalyst::Manual::Tutorial::Testing>
41
42=item 8
43
653f4595 44L<Advanced CRUD|Catalyst::Manual::Tutorial::AdvancedCRUD>
4d583dd8 45
46=item 9
47
7d310f12 48L<Appendices|Catalyst::Manual::Tutorial::Appendices>
4d583dd8 49
50=back
51
208513f1 52
4d583dd8 53=head1 DESCRIPTION
54
64ccd8a8 55In this part of the tutorial, we will create a very basic Catalyst web
56application. Though simple in many respects, this section will already
57demonstrate a number of powerful capabilities such as:
4d583dd8 58
59=over 4
60
61=item * Helper Scripts
62
64ccd8a8 63Catalyst helper scripts that can be used to rapidly bootstrap the
64skeletal structure of an application.
4d583dd8 65
66=item * MVC
67
64ccd8a8 68Model/View/Controller (MVC) provides an architecture that facilitates a
69clean "separation of control" between the different portions of your
653f4595 70application. Given that many other documents cover this subject in
64ccd8a8 71detail, MVC will not be discussed in depth here (for an excellent
72introduction to MVC and general Catalyst concepts, please see
653f4595 73L<Catalyst::Manual::About>. In short:
4d583dd8 74
75=over 4
76
77=item * Model
78
653f4595 79The model usually represents a data store. In most applications, the
80model equates to the objects that are created from and saved to your SQL
81database.
4d583dd8 82
83=item * View
84
64ccd8a8 85The view takes model objects and renders them into something for the end
653f4595 86user to look at. Normally this involves a template-generation tool that
64ccd8a8 87creates HTML for the user's web browser, but it could easily be code
653f4595 88that generates other forms such as PDF documents, e-mails, or Excel
89spreadsheets.
4d583dd8 90
91=item * Controller
92
64ccd8a8 93As suggested by its name, the controller takes user requests and routes
94them to the necessary model and view.
4d583dd8 95
96=back
97
98=item * ORM
99
653f4595 100The use of Object-Relational Mapping (ORM) technology for database
101access. Specifically, ORM provides an automated and standardized means
102to persist and restore objects to/from a relational database.
4d583dd8 103
104=back
105
64ccd8a8 106B<TIP>: Note that all of the code for this part of the tutorial can be
107pulled from the Catalyst Subversion repository in one step with the
108following command:
4d583dd8 109
7d310f12 110 svn co http://dev.catalyst.perl.org/repos/Catalyst/tags/examples/Tutorial/MyApp/5.7/CatalystBasics MyApp
4d583dd8 111
112
4d583dd8 113=head1 CREATE A CATALYST PROJECT
114
64ccd8a8 115Catalyst provides a number of helper scripts that can be used to quickly
653f4595 116flesh out the basic structure of your application. All Catalyst projects
8112f931 117begin with the C<catalyst.pl> helper (see L<Catalyst::Helper|Catalyst::Helper>
118for more information on helpers). Also note that as of Catalyst 5.7000,
119you will not have the helper scripts unless you install both
120L<Catalyst::Runtime|Catalyst::Runtime> and L<Catalyst::Devel|Catalyst::Devel>.
4d583dd8 121
64ccd8a8 122In the case of this tutorial, use the Catalyst C<catalyst.pl> script to
123initialize the framework for an application called C<MyApp>:
4d583dd8 124
125 $ catalyst.pl MyApp
208513f1 126 created "MyApp"
127 created "MyApp/script"
128 created "MyApp/lib"
129 created "MyApp/root"
130 ...
131 created "MyApp/script/myapp_create.pl"
4d583dd8 132 $ cd MyApp
133
64ccd8a8 134The C<catalyst.pl> helper script will display the names of the
135directories and files it creates.
4d583dd8 136
653f4595 137Though it's too early for any significant celebration, we already have a
138functioning application. Run the following command to run this
139application with the built-in development web server:
4d583dd8 140
208513f1 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
8e956464 167 [info] MyApp powered by Catalyst 5.7000
208513f1 168 You can connect to your server at http://localhost.localdomain:3000
169
170Point your web browser to L<http://localhost:3000> (substituting a
171different hostname or IP address as appropriate) and you should be
172greeted by the Catalyst welcome screen. Information similar to the
173following should be appended to the logging output of the development
174server:
175
7d310f12 176 [info] *** Request 1 (0.043/s) [6003] [Fri Jul 7 13:32:53 2006] ***
208513f1 177 [debug] "GET" request for "/" from "127.0.0.1"
7d310f12 178 [info] Request took 0.067675s (14.777/s)
208513f1 179 .----------------------------------------------------------------+-----------.
180 | Action | Time |
181 +----------------------------------------------------------------+-----------+
7d310f12 182 | /default | 0.002844s |
183 | /end | 0.000207s |
208513f1 184 '----------------------------------------------------------------+-----------'
185
186Press Ctrl-C to break out of the development server.
4d583dd8 187
4d583dd8 188
4d583dd8 189=head1 CREATE A SQLITE DATABASE
190
64ccd8a8 191In this step, we make a text file with the required SQL commands to
192create a database table and load some sample data. Open C<myapp01.sql>
193in your editor and enter:
4d583dd8 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
64ccd8a8 239B<TIP>: See Appendix 1 for tips on removing the leading spaces when
c608fae5 240cutting and pasting example code from POD-based documents.
4d583dd8 241
242Then use the following command to build a C<myapp.db> SQLite database:
243
244 $ sqlite3 myapp.db < myapp01.sql
245
64ccd8a8 246If you need to create the database more than once, you probably want to
247issue the C<rm myapp.db> command to delete the database before you use
248the C<sqlite3 myapp.db < myapp01.sql> command.
4d583dd8 249
64ccd8a8 250Once the C<myapp.db> database file has been created and initialized, you
251can use the SQLite command line environment to do a quick dump of the
252database contents:
4d583dd8 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
266Or:
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
64ccd8a8 275As with most other SQL tools, if you are using the full "interactive"
276environment you need to terminate your SQL commands with a ";" (it's not
277required 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
279your OS command prompt.
4d583dd8 280
281
4d583dd8 282=head1 EDIT THE LIST OF CATALYST PLUGINS
283
64ccd8a8 284One of the greatest benefits of Catalyst is that it has such a large
285library of plugins available. Plugins are used to seamlessly integrate
286existing Perl modules into the overall Catalyst framework. In general,
287they do this by adding additional methods to the C<context> object
288(generally written as C<$c>) that Catalyst passes to every component
289throughout the framework.
4d583dd8 290
291By default, Catalyst enables three plugins/flags:
292
293=over 4
294
295=item *
296
297C<-Debug> Flag
298
64ccd8a8 299Enables the Catalyst debug output you saw when we started the
300C<script/myapp_server.pl> development server earlier. You can remove
301this plugin when you place your application into production.
4d583dd8 302
64ccd8a8 303As you may have noticed, C<-Debug> is not a plugin, but a I<flag>.
304Although most of the items specified on the C<use Catalyst> line of your
305application class will be plugins, Catalyst supports a limited number of
14e6feb0 306flag options (of these, C<-Debug> is the most common). See the
307documentation for C<Catalyst.pm> to get details on other flags
308(currently C<-Engine>, C<-Home>, and C<-Log>).
4d583dd8 309
64ccd8a8 310If you prefer, you can use the C<$c-E<gt>debug> method to enable debug
311messages.
4d583dd8 312
313=item *
314
315L<Catalyst::Plugin::ConfigLoader|Catalyst::Plugin::ConfigLoader>
316
653f4595 317C<ConfigLoader> provides an automatic way to load configurable
64ccd8a8 318parameters for your application from a central YAML file (versus having
319the values hard-coded inside your Perl modules). If you have not been
320exposed to YAML before, it is a human-readable data serialization format
321that can be used to read (and write) values to/from text files. We will
322see how to use this feature of Catalyst during the authentication and
323authorization sections (Part 4 and Part 5).
4d583dd8 324
4d583dd8 325=item *
326
14e6feb0 327L<Catalyst::Plugin::Static::Simple|Catalyst::Plugin::Static::Simple>
4d583dd8 328
64ccd8a8 329C<Static::Simple> provides an easy method of serving static content such
330as images and CSS files under the development server.
4d583dd8 331
332=back
333
64ccd8a8 334To modify the list of plugins, edit C<lib/MyApp.pm> (this file is
335generally referred to as your I<application class>) and delete the line
336with:
4d583dd8 337
338 use Catalyst qw/-Debug ConfigLoader Static::Simple/;
339
340Replace it with:
341
342 use Catalyst qw/
343 -Debug
344 ConfigLoader
345 Static::Simple
346
4d583dd8 347 StackTrace
4d583dd8 348 /;
349
c608fae5 350This tells Catalyst to start using one new plugin:
4d583dd8 351
352=over 4
353
354=item *
355
4d583dd8 356L<Catalyst::Plugin::StackTrace|Catalyst::Plugin::StackTrace>
357
64ccd8a8 358Adds a stack trace to the standard Catalyst "debug screen" (this is the
359screen Catalyst sends to your browser when an error occurs).
4d583dd8 360
c19d127e 361Note: L<StackTrace|Catalyst::Plugin::StackTrace> output appears in your
362browser, not in the console window from which you're running your
363application, which is where logging output usually goes.
4d583dd8 364
4d583dd8 365=back
366
64ccd8a8 367Note that when specifying plugins on the C<use Catalyst> line, you can
71dedf57 368omit C<Catalyst::Plugin::> from the name. Additionally, you can spread
64ccd8a8 369the plugin names across multiple lines as shown here, or place them all
370on one (or more) lines as with the default configuration.
4d583dd8 371
c608fae5 372B<TIP:> You may see examples that include the
373L<Catalyst::Plugin::DefaultEnd|Catalyst::Plugin::DefaultEnd>
8e956464 374plugins. As of Catalyst 5.7000, C<DefaultEnd> has been
c608fae5 375deprecated in favor of
376L<Catalyst::Action::RenderView|Catalyst::Action::RenderView>
377(as the name of the package suggests, C<RenderView> is not
378a plugin, but an action). The purpose of both is essentially the same:
208513f1 379forward processing to the view to be rendered. Applications generated
8e956464 380under 5.7000 should automatically use C<RenderView> and "just work"
208513f1 381for most applications. For more information on C<RenderView> and
382the various options for forwarding to your view logic, please refer
383to the "Using RenderView for the Default View" section under
384"CATALYST VIEWS" below.
c608fae5 385
386
4d583dd8 387=head1 DATABASE ACCESS WITH C<DBIx::Class>
388
64ccd8a8 389Catalyst can be used with virtually any form of persistent datastore
14e6feb0 390available via Perl. For example,
391L<Catalyst::Model::DBI|Catalyst::Model::DBI> can be used to
392easily access databases through the traditional Perl C<DBI> interface.
71dedf57 393However, most Catalyst applications use some form of ORM technology to
64ccd8a8 394automatically create and save model objects as they are used. Although
14e6feb0 395Tony Bowden's L<Class::DBI|Class::DBI> has been the traditional
396Perl ORM engine, Matt Trout's L<DBIx::Class|DBIx::Class> (abbreviated
397as "DBIC") has rapidly emerged as the Perl-based ORM technology of choice.
398Most new Catalyst applications rely on DBIC, as will this tutorial.
4d583dd8 399
14e6feb0 400Note: See L<Catalyst:: Model::CDBI> for more information on using
401Catalyst with L<Class::DBI|Class::DBI>.
4d583dd8 402
403=head2 Create a DBIC Schema File
404
64ccd8a8 405DBIx::Class uses a schema file to load other classes that represent the
406tables in your database (DBIC refers to these "table objects" as "result
71dedf57 407sources"; see L<DBIx::Class::ResultSource>). In this case, we want to
408load the model object for the C<books>, C<book_authors>, and C<authors>
409tables created in the previous step.
4d583dd8 410
411Open C<lib/MyAppDB.pm> in your editor and insert:
412
413 package MyAppDB;
414
415 =head1 NAME
416
71dedf57 417 MyAppDB - DBIC Schema Class
4d583dd8 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
64ccd8a8 438B<Note:> C<__PACKAGE__> is just a shorthand way of referencing the name
439of the package where it is used. Therefore, in C<MyAppDB.pm>,
14e6feb0 440C<__PACKAGE__> is equivalent to C<MyAppDB>.
4d583dd8 441
442
443=head2 Create the DBIC "Result Source" Files
444
64ccd8a8 445In this step, we create "table classes" (again, these are called a
71dedf57 446"result source" classes in DBIC) that act as model objects for the
64ccd8a8 447C<books>, C<book_authors>, and C<authors> tables in our database.
4d583dd8 448
449First, create a directory to hold the class:
450
451 $ mkdir lib/MyAppDB
452
453Then 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
64ccd8a8 504This defines both a C<has_many> and a C<many_to_many> relationship. The
505C<many_to_many> relationship is optional, but it makes it easier to map
506a book to its collection of authors. Without it, we would have to
507"walk" though the C<book_authors> table as in
508C<$book-E<gt>book_authors-E<gt>first-E<gt>author-E<gt>last_name> (we
509will see examples on how to use DBIC objects in your code soon, but note
510that because C<$book-E<gt>book_authors> can return multiple authors, we
71dedf57 511have to use C<first> to display a single author). C<many_to_many> allows
512us to use the shorter C<$book-E<gt>authors-E<gt>first-E<gt>last_name>.
513Note that you cannot define a C<many_to_many> relationship without also
514having the C<has_many> relationship in place.
4d583dd8 515
516Next, 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/);
208513f1 530
4d583dd8 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
568Finally, 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');
208513f1 593
4d583dd8 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.
208513f1 611
4d583dd8 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
64ccd8a8 622B<Note:> This sample application uses a plural form for the database
623tables (e.g., C<books> and C<authors>) and a singular form for the model
624objects (e.g., C<Book> and C<Author>); however, Catalyst places no
625restrictions on the naming conventions you wish to use.
4d583dd8 626
4d583dd8 627=head2 Use C<Catalyst::Model::DBIC::Schema> To Load The Model Class
628
14e6feb0 629When L<Catalyst::Model::DBIC::Schema|Catalyst::Model::DBIC::Schema> is
64ccd8a8 630in use, Catalyst essentially reads an existing copy of your database
631model and creates a new set of objects under C<MyApp::Model> for use
632inside of Catalyst.
4d583dd8 633
14e6feb0 634B<Note:> With
635L<Catalyst::Model::DBIC::Schema|Catalyst::Model::DBIC::Schema> you
636essentially end up with two sets of model classes (only one of which
637you write... the other set is created automatically in memory when
638your Catalyst application initializes). For this tutorial application,
639the important points to remember are: you write the I<result source>
640files in C<MyAppDB>, but I<within Catalyst> you use the I<automatically
641created model classes> in C<MyApp::Model>.
4d583dd8 642
14e6feb0 643Use the
644L<Catalyst::Helper::Model::DBIC::Schema|Catalyst::Helper::Model::DBIC::Schema>
645helper script to create the model class that loads up the model we
646created in the previous step:
4d583dd8 647
648 $ script/myapp_create.pl model MyAppDB DBIC::Schema MyAppDB dbi:SQLite:myapp.db '' '' '{ AutoCommit => 1 }'
208513f1 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
4d583dd8 654
64ccd8a8 655Where the first C<MyAppDB> is the name of the class to be created by the
656helper in C<lib/MyApp/Model> and the second C<MyAppDB> is the name of
657existing schema file we created (in C<lib/MyAppDB.pm>). You can see
658that the helper creates a model file under C<lib/MyApp/Model> (Catalyst
659has a separate directory under C<lib/MyApp> for each of the three parts
660of MVC: C<Model>, C<View>, and C<Controller> [although older Catalyst
661applications often use the directories C<M>, C<V>, and C<C>]).
4d583dd8 662
663
4d583dd8 664=head1 CREATE A CATALYST CONTROLLER
665
71dedf57 666Controllers are where you write methods that interact with user
667input--typically, controller methods respond to C<GET> and C<POST>
668messages from the user's web browser.
4d583dd8 669
71dedf57 670Use the Catalyst C<create> script to add a controller for book-related
671actions:
4d583dd8 672
673 $ script/myapp_create.pl controller Books
208513f1 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"
4d583dd8 678
64ccd8a8 679Then edit C<lib/MyApp/Controller/Books.pm> and add the following method
680to the controller:
4d583dd8 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
8112f931 699 # in your action methods (actions methods respond to user input in
700 # your controllers).
4d583dd8 701 $c->stash->{template} = 'books/list.tt2';
702 }
703
64ccd8a8 704B<Note:> Programmers experienced with object-oriented Perl should
705recognize C<$self> as a reference to the object where this method was
706called. On the other hand, C<$c> will be new to many Perl programmers
707who have not used Catalyst before (it's sometimes written as
708C<$context>). The Context object is automatically passed to all
709Catalyst components. It is used to pass information between components
710and provide access to Catalyst and plugin functionality.
4d583dd8 711
64ccd8a8 712B<TIP>: You may see the C<$c-E<gt>model('MyAppDB::Book')> used above
713written as C<$c-E<gt>model('MyAppDB')-E<gt>resultset('Book)>. The two
714are equivalent.
4d583dd8 715
64ccd8a8 716B<Note:> Catalyst actions are regular Perl methods, but they make use of
14e6feb0 717Nicholas Clark's C<attributes> module (that's the C<: Local> next to the
718C<sub list> in the code above) to provide additional information to the
719Catalyst dispatcher logic.
4d583dd8 720
208513f1 721
4d583dd8 722=head1 CATALYST VIEWS
723
71dedf57 724Views are where you render output, typically for display in the user's
14e6feb0 725web browser, but also possibly using other display output-generation
71dedf57 726systems. As with virtually every aspect of Catalyst, options abound
727when it comes to the specific view technology you adopt inside your
728application. However, most Catalyst applications use the Template
729Toolkit, known as TT (for more information on TT, see
208513f1 730L<http://www.template-toolkit.org>). Other popular view technologies
71dedf57 731include Mason (L<http://www.masonhq.com> and
14e6feb0 732L<http://www.masonbook.com>) and L<HTML::Template|HTML::Template>
64ccd8a8 733(L<http://html-template.sourceforge.net>).
4d583dd8 734
70493af7 735=head2 Create a Catalyst View Using C<TTSite>
4d583dd8 736
737When using TT for the Catalyst view, there are two main helper scripts:
738
739=over 4
740
741=item *
742
14e6feb0 743L<Catalyst::Helper::View::TT|Catalyst::Helper::View::TT>
4d583dd8 744
745=item *
746
14e6feb0 747L<Catalyst::Helper::View::TTSite|Catalyst::Helper::View::TTSite>
4d583dd8 748
749=back
750
64ccd8a8 751Both are similar, but C<TT> merely creates the C<lib/MyApp/View/TT.pm>
752file and leaves the creation of any hierarchical template organization
71dedf57 753entirely up to you. (It also creates a C<t/view_TT.t> file for testing;
754test cases will be discussed in Part 7). The C<TTSite> helper creates a
755modular and hierarchical view layout with separate Template Toolkit (TT)
756files for common header and footer information, configuration values, a
757CSS stylesheet, and more.
4d583dd8 758
64ccd8a8 759Enter the following command to enable the C<TTSite> style of view
71dedf57 760rendering for this tutorial:
4d583dd8 761
762 $ script/myapp_create.pl view TT TTSite
208513f1 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"
4d583dd8 769
64ccd8a8 770This puts a number of files in the C<root/lib> and C<root/src>
771directories that can be used to customize the look and feel of your
772application. Also take a look at C<lib/MyApp/View/TT.pm> for config
773values set by the C<TTSite> helper.
774
775B<TIP>: Note that TTSite does one thing that could confuse people who
208513f1 776are used to the normal C<TT> Catalyst view: it redefines the Catalyst
71dedf57 777context object in templates from its usual C<c> to C<Catalyst>. When
778looking at other Catalyst examples, remember that they almost always use
779C<c>. Note that Catalyst and TT I<do not complain> when you use the
780wrong name to access the context object...TT simply outputs blanks for
5c1f2a06 781that bogus logic (see next tip to change this behavior with TT C<DEBUG>
782options). Finally, be aware that this change in name I<only>
71dedf57 783applies to how the context object is accessed inside your TT templates;
64ccd8a8 784your controllers will continue to use C<$c> (or whatever name you use
71dedf57 785when fetching the reference from C<@_> inside your methods). (You can
64ccd8a8 786change back to the "default" behavior be removing the C<CATALYST_VAR>
787line from C<lib/MyApp/View/TT.pm>, but you will also have to edit
788C<root/lib/config/main> and C<root/lib/config/url>. If you do this, be
789careful not to have a collision between your own C<c> variable and the
790Catalyst C<c> variable.)
4d583dd8 791
5c1f2a06 792B<TIP>: When troubleshooting TT it can be helpful to enable variable
793C<DEBUG> options. You can do this in a Catalyst environment by adding
794a C<DEBUG> line to the C<__PACKAGE__->config> declaration in
8112f931 795C<lib/MyApp/View/TT.pm>:
5c1f2a06 796
797 __PACKAGE__->config({
798 CATALYST_VAR => 'Catalyst',
799 ...
800 DEBUG => 'undef',
801 ...
802 });
208513f1 803
5c1f2a06 804There are a variety of options you can use, such as 'undef', 'all',
805'service', 'context', 'parser', 'provider', and 'service'. See
806L<Template::Constants> for more information (remove the C<DEBUG_>
807portion of the name shown in the TT docs and convert to lower case
808for use inside Catalyst).
809
70493af7 810B<NOTE:> Please be sure to disable TT debug options before
811continuing the tutorial (especially the 'undef' option -- leaving
812this enabled will conflict with several of the conventions used
813by this tutorial and TTSite to leave some variables undefined
814on purpose).
815
5c1f2a06 816
208513f1 817=head2 Using C<RenderView> for the Default View
818
819Once your controller logic has processed the request from a user, it
820forwards processing to your view in order to generate the appropriate
8e956464 821response output. Catalyst v5.7000 ships with a new mechanism,
208513f1 822L<Catalyst::Action::RenderView|Catalyst::Action::RenderView>, that
823automatically performs this operation. If you look in
824C<lib/MyApp/Controller/Root.pm>, you should see the this empty
825definition for the C<sub end> method:
826
827 sub end : ActionClass('RenderView') {}
828
829The following bullet points provide a quick overview of the
830C<RenderView> process:
831
832=over 4
833
834=item *
835
836C<Root.pm> is designed to hold application-wide logic.
837
838=item *
839
840At the end of a given user request, Catalyst will call the most specific
841C<end> method that's appropriate. For example, if the controller for a
842request has an C<end> method defined, it will be called. However, if
843the controller does not define a controller-specific C<end> method, the
844"global" C<end> method in C<Root.pm> will be called.
c608fae5 845
208513f1 846=item *
847
848Because the definition includes an C<ActionClass> attribute, the
849L<Catalyst::Action::RenderView|Catalyst::Action::RenderView> logic
565d379b 850will be executed B<after> any code inside the definition of C<sub end>
208513f1 851is run. See L<Catalyst::Manual::Actions|Catalyst::Manual::Actions>
852for more information on C<ActionClass>.
853
854=item *
855
856Because C<sub end> is empty, this effectively just runs the default
857logic in C<RenderView>. However, you can easily extend the
858C<RenderView> logic by adding your own code inside the empty method body
859(C<{}>) created by the Catalyst Helpers when we first ran the
860C<catalyst.pl> to initialize our application. See
861L<Catalyst::Action::RenderView|Catalyst::Action::RenderView> for more
862detailed 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
869Although C<RenderView> strikes a nice balance between default
870behavior and easy extensibility, it is a new feature that won't
871appear in most existing Catalyst examples. This section provides
872some brief background on the evolution of default view rendering
873logic with an eye to how they can be migrated to C<RenderView>:
c608fae5 874
875=over 4
876
877=item *
878
879Private C<end> Action in Application Class
880
881Older Catalyst-related documents often suggest that you add a "private
882end action" to your application class (C<MyApp.pm>) or Root.pm
883(C<MyApp/Controller/Root.pm>). These examples should be easily
208513f1 884converted to L<RenderView|Catalyst::Action::RenderView> by simply adding
8112f931 885the attribute C<:ActionClass('RenderView')> to the C<sub end>
886definition. If end sub is defined in your application class
887(C<MyApp.pm>), you should also migrate it to
888C<MyApp/Controller/Root.pm>.
c608fae5 889
890=item *
891
892L<Catalyst::Plugin::DefaultEnd|Catalyst::Plugin::DefaultEnd>
893
208513f1 894C<DefaultEnd> represented the "next step" in passing processing from
895your controller to your view. It has the advantage of only requiring
896that C<DefaultEnd> be added to the list of plugins in C<lib/MyApp.pm>.
897It also allowed you to add "dump_info=1" (precede with "?" or "&"
898depending on where it is in the URL) to I<force> the debug screen at the
899end of the Catalyst request processing cycle. However, it was more
c9b77c06 900difficult to extend than the C<RenderView> mechanism, and is now
901deprecated.
c608fae5 902
903=item *
904
905L<Catalyst::Action::RenderView|Catalyst::Action::RenderView>
906
208513f1 907As discussed above, the current recommended approach to handling your
908view logic relies on
c608fae5 909L<Catalyst::Action::RenderView|Catalyst::Action::RenderView>. Although
208513f1 910similar in first appearance to the "private end action" approach, it
911utilizes Catalyst's "ActionClass" mechanism to provide both automatic
912default behavior (you don't have to include a plugin as with
913C<DefaultEnd>) and easy extensibility. As with C<DefaultEnd>, it allows
914you to add "dump_info=1" (precede with "?" or "&" depending on where it
915is in the URL) to I<force> the debug screen at the end of the Catalyst
916request processing cycle.
c608fae5 917
918=back
919
208513f1 920It is recommended that all Catalyst applications use or migrate to
921the C<RenderView> approach.
c608fae5 922
923
4d583dd8 924=head2 Globally Customize Every View
925
64ccd8a8 926When using TTSite, files in the subdirectories of C<root/lib> can be
927used to make changes that will appear in every view. For example, to
928display optional status and error messages in every view, edit
71dedf57 929C<root/lib/site/layout>, updating it to match the following (the two HTML
64ccd8a8 930C<span> elements are new):
4d583dd8 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
64ccd8a8 942If we set either message in the Catalyst stash (e.g.,
71dedf57 943C<$c-E<gt>stash-E<gt>{status_msg} = 'Request was successful!'>) it will
944be displayed whenever any view used by that request is rendered. The
945C<message> and C<error> CSS styles are automatically defined in
946C<root/src/ttsite.css> and can be customized to suit your needs.
4d583dd8 947
64ccd8a8 948B<Note:> The Catalyst stash only lasts for a single HTTP request. If
949you need to retain information across requests you can use
14e6feb0 950L<Catalyst::Plugin::Session|Catalyst::Plugin::Session> (we will use
951Catalyst sessions in the Authentication part of the tutorial).
4d583dd8 952
953
954=head2 Create a TT Template Page
955
64ccd8a8 956To add a new page of content to the TTSite view hierarchy, just create a
957new C<.tt2> file in C<root/src>. Only include HTML markup that goes
958inside the HTML <body> and </body> tags, TTSite will use the contents of
959C<root/lib/site> to add the top and bottom.
4d583dd8 960
961First create a directory for book-related TT templates:
962
963 $ mkdir root/src/books
964
965Then 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>
14e6feb0 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 -%]
c9b77c06 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. -%]
14e6feb0 990 [% tt_authors = [ ];
c9b77c06 991 tt_authors.push(author.last_name) FOREACH author = book.authors %]
14e6feb0 992 [% # Now use a TT 'virtual method' to display the author count in parens -%]
993 ([% tt_authors.size %])
c9b77c06 994 [% # Use another TT vmethod to join & print the names & comma separators -%]
14e6feb0 995 [% tt_authors.join(', ') %]
4d583dd8 996 </td>
997 </tr>
998 [% END -%]
999 </table>
1000
64ccd8a8 1001As indicated by the inline comments above, the C<META title> line uses
1002TT's META feature to provide a title to C<root/lib/site/header>.
1003Meanwhile, the outer C<FOREACH> loop iterates through each C<book> model
1004object and prints the C<title> and C<rating> fields. An inner
14e6feb0 1005C<FOREACH> loop prints the last name of each author in a comma-separated
1006list within a single table cell.
64ccd8a8 1007
71dedf57 1008If you are new to TT, the C<[%> and C<%]> tags are used to delimit TT
1009code. TT supports a wide variety of directives for "calling" other
64ccd8a8 1010files, looping, conditional logic, etc. In general, TT simplifies the
1011usual range of Perl operators down to the single dot (C<.>) operator.
1012This applies to operations as diverse as method calls, hash lookups, and
1013list index values (see
1014L<http://www.template-toolkit.org/docs/default/Manual/Variables.html>
1015for details and examples). In addition to the usual C<Template> module
1016Pod documentation, you can access the TT manual at
1017L<http://www.template-toolkit.org/docs/default/>.
1018
1019B<NOTE>: The C<TTSite> helper creates several TT files using an
1020extension of C<.tt2>. Most other Catalyst and TT examples use an
1021extension of C<.tt>. You can use either extension (or no extension at
1022all) with TTSite and TT, just be sure to use the appropriate extension
1023for 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
1025consistency with the files already created by the C<TTSite> helper.
4d583dd8 1026
1027
4d583dd8 1028=head1 RUN THE APPLICATION
1029
64ccd8a8 1030First, let's enable an environment variable option that causes
1031DBIx::Class to dump the SQL statements it's using to access the database
1032(this option can provide extremely helpful troubleshooting information):
4d583dd8 1033
1034 $ export DBIX_CLASS_STORAGE_DBI_DEBUG=1
1035
cc548726 1036This assumes you are using BASH as your shell -- adjust accordingly if
1037you are using a different shell (for example, under tcsh, use
1038C<setenv DBIX_CLASS_STORAGE_DBI_DEBUG 1>).
1039
64ccd8a8 1040B<NOTE>: You can also set this in your code using
1041C<$class-E<gt>storage-E<gt>debug(1);>. See
71dedf57 1042L<DBIx::Class::Manual::Troubleshooting> for details (including options
1043to log to file instead of displaying to the Catalyst development server
1044log).
4d583dd8 1045
1046Then run the Catalyst "demo server" script:
1047
1048 $ script/myapp_server.pl
1049
208513f1 1050Your development server log output should display something like:
4d583dd8 1051
1052 $ script/myapp_server.pl
208513f1 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 '----------------------------------------------------------------------------'
4d583dd8 1060
208513f1 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 '-----------------------------------------------------------------+----------'
4d583dd8 1076
208513f1 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 '----------------------+--------------------------------------+--------------'
4d583dd8 1086
208513f1 1087 [debug] Loaded Path actions:
1088 .-------------------------------------+--------------------------------------.
1089 | Path | Private |
1090 +-------------------------------------+--------------------------------------+
1091 | /books/list | /books/list |
1092 '-------------------------------------+--------------------------------------'
4d583dd8 1093
8e956464 1094 [info] MyApp powered by Catalyst 5.7000
208513f1 1095 You can connect to your server at http://localhost.localdomain:3000
4d583dd8 1096
1097Some things you should note in the output above:
1098
1099=over 4
1100
1101=item *
1102
64ccd8a8 1103Catalyst::Model::DBIC::Schema took our C<MyAppDB::Book> and made it
1104C<MyApp::Model::MyAppDB::Book> (and similar actions were performed on
1105C<MyAppDB::Author> and C<MyAppDB::BookAuthor>).
4d583dd8 1106
1107=item *
1108
64ccd8a8 1109The "list" action in our Books controller showed up with a path of
1110C</books/list>.
4d583dd8 1111
1112=back
1113
64ccd8a8 1114Point your browser to L<http://localhost:3000> and you should still get
1115the Catalyst welcome page.
4d583dd8 1116
64ccd8a8 1117Next, to view the book list, change the URL in your browser to
1118L<http://localhost:3000/books/list>. You should get a list of the five
1119books loaded by the C<myapp01.sql> script above, with TTSite providing
1120the formatting for the very simple output we generated in our template.
1121The count and space-separated list of author last names appear on the
1122end of each row.
4d583dd8 1123
64ccd8a8 1124Also notice in the output of the C<script/myapp_server.pl> that DBIC
1125used the following SQL to retrieve the data:
4d583dd8 1126
1127 SELECT me.id, me.title, me.rating FROM books me
1128
64ccd8a8 1129Along with a list of the following commands to retrieve the authors for
1130each book (the lines have been "word wrapped" here to improve
1131legibility):
4d583dd8 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
208513f1 1138You should see 5 such lines of debug output as DBIC fetches the author
1139information for each book.
4d583dd8 1140
1141
770fdaa9 1142=head1 USING THE DEFAULT TEMPLATE NAME
1143
1144By default, C<Catalyst::View::TT> will look for a template that uses the
1145same name as your controller action, allowing you to save the step of
1146manually specifying the template name in each action. For example, this
1147would allow us to remove (or comment out) the
1148C<$c-E<gt>stash-E<gt>{template} = 'books/list.tt2';> line of our
1149C<list> action in the Books controller. Open
1150C<lib/MyApp/Controller/Books.pm> in your editor and update it to
1151match 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
1173C<Catalyst::View::TT> defaults to looking for a template with no
1174extension. In our case, we need to override this to look for an
1175extension of C<.tt2>. Open C<lib/MyApp/View/TT.pm> and add the
1176C<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
1191You should now be able to restart the development server as per the
1192previous section and access the L<http://localhost:3000/books/list>
1193as before.
1194
1195Although this can be a valuable technique to establish a default
1196template for each of your actions, the remainder of the tutorial
1197will manually assign the template name to
1198C<$c-E<gt>stash-E<gt>{template}> in each action in order to make
1199the logic as conspicuous as possible.
1200
1201
4d583dd8 1202=head1 AUTHOR
1203
1204Kennedy Clark, C<hkclark@gmail.com>
1205
c608fae5 1206Please report any errors, issues or suggestions to the author. The
7d310f12 1207most recent version of the Catalyst Tutorial can be found at
c608fae5 1208L<http://dev.catalyst.perl.org/repos/Catalyst/trunk/Catalyst-Runtime/lib/Catalyst/Manual/Tutorial/>.
4d583dd8 1209
71dedf57 1210Copyright 2006, Kennedy Clark, under Creative Commons License
1211(L<http://creativecommons.org/licenses/by-nc-sa/2.5/>).
4d583dd8 1212