3 Catalyst::Manual::Tutorial::CatalystBasics - Catalyst Tutorial - Part 2: Catalyst Application Development Basics
9 This is B<Part 2 of 9> for the Catalyst tutorial.
11 L<Tutorial Overview|Catalyst::Manual::Tutorial>
17 L<Introduction|Catalyst::Manual::Tutorial::Intro>
25 L<Basic CRUD|Catalyst::Manual::Tutorial_BasicCRUD>
29 L<Authentication|Catalyst::Manual::Tutorial::Authentication>
33 L<Authorization|Catalyst::Manual::Tutorial::Authorization>
37 L<Debugging|Catalyst::Manual::Tutorial::Debugging>
41 L<Testing|Catalyst::Manual::Tutorial::Testing>
45 L<AdvancedCRUD|Catalyst::Manual::Tutorial::AdvancedCRUD>
49 L<Appendicies|Catalyst::Manual::Tutorial::Appendicies>
57 In this part of the tutorial, we will create a very basic Catalyst web
58 application. Though simple in many respects, this section will already
59 demonstrate a number of powerful capabilities such as:
63 =item * Helper Scripts
65 Catalyst helper scripts that can be used to rapidly bootstrap the
66 skeletal structure of an application.
70 Model/View/Controller (MVC) provides an architecture that facilitates a
71 clean "separation of control" between the different portions of your
72 application. Given that many other documents cover this subject in
73 detail, MVC will not be discussed in depth here (for an excellent
74 introduction to MVC and general Catalyst concepts, please see
75 L<Catalyst::Manual::About|Catalyst::Manual::About>. In short:
81 In most applications, the model equates to the objects that are created
82 from and saved to your SQL database.
86 The view takes model objects and renders them into something for the end
87 user to look at. Normally this involves a template-generation tool that
88 creates HTML for the user's web browser, but it could easily be code
89 that generates other forms such as PDF documents or Excel spreadsheets.
93 As suggested by its name, the controller takes user requests and routes
94 them to the necessary model and view.
100 The use Object-Relational Mapping (ORM) technology for database access
101 (specifically, ORM provides an automated means to persist and restore
102 objects to/from a relational database).
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
110 svn checkout http://dev.catalyst.perl.org/repos/Catalyst/trunk/examples/Tutorial@###
111 IMPORTANT: Does not work yet. Will be completed for final version.
115 =head1 CREATE A CATALYST PROJECT
117 Catalyst provides a number of helper scripts that can be used to quickly
118 flesh out the basic structure of your application. All Catalyst
119 projects begin with the C<catalyst.pl> helper.
121 In the case of this tutorial, use the Catalyst C<catalyst.pl> script to
122 initialize the framework for an application called C<MyApp>:
127 The C<catalyst.pl> helper script will display the names of the
128 directories and files it creates.
130 Though it's obviously too early for any significant celebration, we
131 already have a functioning application. Run the following command to
132 run this application with the built-in development web server:
134 $ script/myapp_server.pl
136 Point your web browser to L<http://localhost:3000> (substituting a
137 different hostname or IP address as appropriate) and you should be
138 greeted by the Catalyst welcome screen. Press Ctrl-C to break out of
139 the development server.
143 =head1 CREATE A SQLITE DATABASE
145 In this step, we make a text file with the required SQL commands to
146 create a database table and load some sample data. Open C<myapp01.sql>
147 in your editor and enter:
150 -- Create a very simple database to hold book and author information
153 id INTEGER PRIMARY KEY,
157 -- 'book_authors' is a many-to-many join table between books & authors
158 CREATE TABLE book_authors (
161 PRIMARY KEY (book_id, author_id)
163 CREATE TABLE authors (
164 id INTEGER PRIMARY KEY,
169 --- Load some sample data
171 INSERT INTO books VALUES (1, 'CCSP SNRS Exam Certification Guide', 5);
172 INSERT INTO books VALUES (2, 'TCP/IP Illustrated, Volume 1', 5);
173 INSERT INTO books VALUES (3, 'Internetworking with TCP/IP Vol.1', 4);
174 INSERT INTO books VALUES (4, 'Perl Cookbook', 5);
175 INSERT INTO books VALUES (5, 'Designing with Web Standards', 5);
176 INSERT INTO authors VALUES (1, 'Greg', 'Bastien');
177 INSERT INTO authors VALUES (2, 'Sara', 'Nasseh');
178 INSERT INTO authors VALUES (3, 'Christian', 'Degu');
179 INSERT INTO authors VALUES (4, 'Richard', 'Stevens');
180 INSERT INTO authors VALUES (5, 'Douglas', 'Comer');
181 INSERT INTO authors VALUES (6, 'Tom', 'Christiansen');
182 INSERT INTO authors VALUES (7, ' Nathan', 'Torkington');
183 INSERT INTO authors VALUES (8, 'Jeffrey', 'Zeldman');
184 INSERT INTO book_authors VALUES (1, 1);
185 INSERT INTO book_authors VALUES (1, 2);
186 INSERT INTO book_authors VALUES (1, 3);
187 INSERT INTO book_authors VALUES (2, 4);
188 INSERT INTO book_authors VALUES (3, 5);
189 INSERT INTO book_authors VALUES (4, 6);
190 INSERT INTO book_authors VALUES (4, 7);
191 INSERT INTO book_authors VALUES (5, 8);
193 B<TIP>: See Appendix 1 for tips on removing the leading spaces when
194 cutting and pasting example code from Pod documents.
196 Then use the following command to build a C<myapp.db> SQLite database:
198 $ sqlite3 myapp.db < myapp01.sql
200 If you need to create the database more than once, you probably want to
201 issue the C<rm myapp.db> command to delete the database before you use
202 the C<sqlite3 myapp.db < myapp01.sql> command.
204 Once the C<myapp.db> database file has been created and initialized, you
205 can use the SQLite command line environment to do a quick dump of the
210 Enter ".help" for instructions
211 sqlite> select * from books;
212 1|CCSP SNRS Exam Certification Guide|5
213 2|TCP/IP Illustrated, Volume 1|5
214 3|Internetworking with TCP/IP Vol.1|4
216 5|Designing with Web Standards|5
222 $ sqlite3 myapp.db "select * from books"
223 1|CCSP SNRS Exam Certification Guide|5
224 2|TCP/IP Illustrated, Volume 1|5
225 3|Internetworking with TCP/IP Vol.1|4
227 5|Designing with Web Standards|5
229 As with most other SQL tools, if you are using the full "interactive"
230 environment you need to terminate your SQL commands with a ";" (it's not
231 required if you do a single SQL statement on the command line). Use
232 ".q" to exit from SQLite from the SQLite interactive mode and return to
233 your OS command prompt.
237 =head1 EDIT THE LIST OF CATALYST PLUGINS
239 One of the greatest benefits of Catalyst is that it has such a large
240 library of plugins available. Plugins are used to seamlessly integrate
241 existing Perl modules into the overall Catalyst framework. In general,
242 they do this by adding additional methods to the C<context> object
243 (generally written as C<$c>) that Catalyst passes to every component
244 throughout the framework.
246 By default, Catalyst enables three plugins/flags:
254 Enables the Catalyst debug output you saw when we started the
255 C<script/myapp_server.pl> development server earlier. You can remove
256 this plugin when you place your application into production.
258 As you may have noticed, C<-Debug> is not a plugin, but a I<flag>.
259 Although most of the items specified on the C<use Catalyst> line of your
260 application class will be plugins, Catalyst supports a limited number of
261 flag options (of these, C<-Debug> is the most common).
263 If you prefer, you can use the C<$c-E<gt>debug> method to enable debug
268 L<Catalyst::Plugin::ConfigLoader|Catalyst::Plugin::ConfigLoader>
270 C<ConfigLoader> provides an automatic way to load your configurable
271 parameters for your application from a central YAML file (versus having
272 the values hard-coded inside your Perl modules). If you have not been
273 exposed to YAML before, it is a human-readable data serialization format
274 that can be used to read (and write) values to/from text files. We will
275 see how to use this feature of Catalyst during the authentication and
276 authorization sections (Part 4 and Part 5).
281 L<Catalyst::Plugin::Static::Simple|Catalyst::Plugin::Static::Simple>
283 C<Static::Simple> provides an easy method of serving static content such
284 as images and CSS files under the development server.
288 To modify the list of plugins, edit C<lib/MyApp.pm> (this file is
289 generally referred to as your I<application class>) and delete the line
292 use Catalyst qw/-Debug ConfigLoader Static::Simple/;
306 This tells Catalyst to start using three new plugins:
312 L<Catalyst::Plugin::Dumper|Catalyst::Plugin::Dumper>
314 Allows you to easily use L<Data::Dumper|Data::Dumper> to dump variables
315 to the logs, for example:
317 $c->log->dumper($myvar);
319 When running your application under the development server, the logs
320 will be printed to your screen along with the other debug information
321 generated by the C<-Debug> flag.
325 L<Catalyst::Plugin::StackTrace|Catalyst::Plugin::StackTrace>
327 Adds a stack trace to the standard Catalyst "debug screen" (this is the
328 screen Catalyst sends to your browser when an error occurs).
330 Note: L<Dumper|Catalyst::Plugin::Dumper> output appears on the
331 console/telnet/SSH window where you issue the C<script/myapp_server.pl>
332 command. L<StackTrace|Catalyst::Plugin::StackTrace> output appears in
337 L<Catalyst::Plugin::DefaultEnd|Catalyst::Plugin::DefaultEnd>
339 Automatically provides a Catalyst "end action" that invokes your view at
340 the end of each request. Also allows you to add "dump_info=1" (precede
341 with "?" or "&" depending on where it is in the URL) to I<force> the
342 debug screen at the end of the Catalyst request processing cycle.
344 TIP: Many Catalyst-related documents predate
345 L<DefaultEnd|Catalyst::Plugin::DefaultEnd> and suggest that you add an
346 C<end> action to your application class (C<MyApp.pm>) or Root.pm
347 (C<MyApp/Controller/Root.pm>). In most of these cases, you can convert
348 to L<DefaultEnd|Catalyst::Plugin::DefaultEnd> by deleting the C<end>
349 action and using the plugin instead.
353 Note that when specifying plugins on the C<use Catalyst> line, you can
354 omit C<Catalyst::Plugin> from the name. Additionally, you can spread
355 the plugin names across multiple lines as shown here, or place them all
356 on one (or more) lines as with the default configuration.
360 =head1 DATABASE ACCESS WITH C<DBIx::Class>
362 Catalyst can be used with virtually any form of persistent datastore
363 available via Perl. For example,
364 L<Catalyst::Model::DBI|Catalyst::Model::DBI> can be used to easily
365 access databases through the traditional Perl DBI interface. However,
366 most Catalyst applications use some form of ORM technology to
367 automatically create and save model objects as they are used. Although
368 Tony Bowden's L<Class::DBI|Class::DBI> has been the traditional Perl ORM
369 engine, Matt Trout's L<DBIx::Class|DBIx::Class> (abbreviated as "DBIC")
370 has rapidly emerged as the Perl-based ORM technology of choice. Most
371 new Catalyst applications rely on DBIC, as will this tutorial.
373 Note: See L<Catalyst::Model::CDBI| Catalyst:: Model::CDBI > for more
374 information on using Catalyst with L<Class::DBI|Class::DBI>. Catalyst
375 can also be used with "plain old DBI"; see L<Catalyst::Model::DBI|
376 Catalyst::Model::DBI>.
379 =head2 Create a DBIC Schema File
381 DBIx::Class uses a schema file to load other classes that represent the
382 tables in your database (DBIC refers to these "table objects" as "result
383 sources," see L<DBIx::Class::ResultSource|DBIx::Class::ResultSource>).
384 In this case, we want to load the model object for the C<books>,
385 C<book_authors>, and C<authors> tables created in the previous step.
387 Open C<lib/MyAppDB.pm> in your editor and insert:
393 MyAppDB -- DBIC Schema Class
397 # Our schema needs to inherit from 'DBIx::Class::Schema'
398 use base qw/DBIx::Class::Schema/;
400 # Need to load the DB Model classes here.
401 # You can use this syntax if you want:
402 # __PACKAGE__->load_classes(qw/Book BookAuthor Author/);
403 # Also, if you simply want to load all of the classes in a directory
404 # of the same name as your schema class (as we do here) you can use:
405 # __PACKAGE__->load_classes(qw//);
406 # But the variation below is more flexible in that it can be used to
407 # load from multiple namespaces.
408 __PACKAGE__->load_classes({
409 MyAppDB => [qw/Book BookAuthor Author/]
414 B<Note:> C<__PACKAGE__> is just a shorthand way of referencing the name
415 of the package where it is used. Therefore, in C<MyAppDB.pm>,
416 C<__PACKAGE> is equivalent to C<MyAppDB>
419 =head2 Create the DBIC "Result Source" Files
421 In this step, we create "table classes" (again, these are called a
422 "result source" classes in DBIC) that acts as model objects for the
423 C<books>, C<book_authors>, and C<authors> tables in our database.
425 First, create a directory to hold the class:
429 Then open C<lib/MyAppDB/Book.pm> in your editor and enter:
431 package MyAppDB::Book;
433 use base qw/DBIx::Class/;
435 # Load required DBIC stuff
436 __PACKAGE__->load_components(qw/PK::Auto Core/);
438 __PACKAGE__->table('books');
439 # Set columns in table
440 __PACKAGE__->add_columns(qw/id title rating/);
441 # Set the primary key for the table
442 __PACKAGE__->set_primary_key(qw/id/);
450 # 1) Name of relationship, DBIC will create accessor with this name
451 # 2) Name of the model class referenced by this relationship
452 # 3) Column name in *foreign* table
453 __PACKAGE__->has_many(book_authors => 'MyAppDB::BookAuthor', 'book_id');
457 # 1) Name of relationship, DBIC will create accessor with this name
458 # 2) Name of has_many() relationship this many_to_many() is shortcut for
459 # 3) Name of belongs_to() relationship in model class of has_many() above
460 # You must already have the has_many() defined to use a many_to_many().
461 __PACKAGE__->many_to_many(authors => 'book_authors', 'author');
466 MyAppDB::Book - A model object representing a book.
470 This is an object that represents a row in the 'books' table of your application
471 database. It uses DBIx::Class (aka, DBIC) to do ORM.
473 For Catalyst, this is designed to be used through MyApp::Model::MyAppDB.
474 Offline utilities may wish to use this class directly.
480 This defines both a C<has_many> and a C<many_to_many> relationship. The
481 C<many_to_many> relationship is optional, but it makes it easier to map
482 a book to its collection of authors. Without it, we would have to
483 "walk" though the C<book_authors> table as in
484 C<$book-E<gt>book_authors-E<gt>first-E<gt>author-E<gt>last_name> (we
485 will see examples on how to use DBIC objects in your code soon, but note
486 that because C<$book-E<gt>book_authors> can return multiple authors, we
487 have to use C<first> to display a single author). C<many_to_many>
488 allows us to use the shorter
489 C<$book-E<gt>authors-E<gt>first-E<gt>last_name>. Note that you cannot
490 define a C<many_to_many> relationship without also having the
491 C<has_many> relationship in place.
493 Next, open C<lib/MyAppDB/Author.pm> in your editor and enter:
495 package MyAppDB::Author;
497 use base qw/DBIx::Class/;
499 # Load required DBIC stuff
500 __PACKAGE__->load_components(qw/PK::Auto Core/);
502 __PACKAGE__->table('authors');
503 # Set columns in table
504 __PACKAGE__->add_columns(qw/id first_name last_name/);
505 # Set the primary key for the table
506 __PACKAGE__->set_primary_key(qw/id/);
514 # 1) Name of relationship, DBIC will create accessor with this name
515 # 2) Name of the model class referenced by this relationship
516 # 3) Column name in *foreign* table
517 __PACKAGE__->has_many(book_author => 'MyAppDB::BookAuthor', 'author_id');
521 # 1) Name of relationship, DBIC will create accessor with this name
522 # 2) Name of has_many() relationship this many_to_many() is shortcut for
523 # 3) Name of belongs_to() relationship in model class of has_many() above
524 # You must already have the has_many() defined to use a many_to_many().
525 __PACKAGE__->many_to_many(books => 'book_author', 'book');
530 MyAppDB::Author - A model object representing an author of a book (if a book has
531 multiple authors, each will be represented be separate Author object).
535 This is an object that represents a row in the 'authors' table of your application
536 database. It uses DBIx::Class (aka, DBIC) to do ORM.
538 For Catalyst, this is designed to be used through MyApp::Model::MyAppDB.
539 Offline utilities may wish to use this class directly.
545 Finally, open C<lib/MyAppDB/BookAuthor.pm> in your editor and enter:
547 package MyAppDB::BookAuthor;
549 use base qw/DBIx::Class/;
551 # Load required DBIC stuff
552 __PACKAGE__->load_components(qw/PK::Auto Core/);
554 __PACKAGE__->table('book_authors');
555 # Set columns in table
556 __PACKAGE__->add_columns(qw/book_id author_id/);
557 # Set the primary key for the table
558 __PACKAGE__->set_primary_key(qw/book_id author_id/);
566 # 1) Name of relationship, DBIC will create accessor with this name
567 # 2) Name of the model class referenced by this relationship
568 # 3) Column name in *this* table
569 __PACKAGE__->belongs_to(book => 'MyAppDB::Book', 'book_id');
573 # 1) Name of relationship, DBIC will create accessor with this name
574 # 2) Name of the model class referenced by this relationship
575 # 3) Column name in *this* table
576 __PACKAGE__->belongs_to(author => 'MyAppDB::Author', 'author_id');
581 MyAppDB::BookAuthor - A model object representing the JOIN between an author and
586 This is an object that represents a row in the 'book_authors' table of your
587 application database. It uses DBIx::Class (aka, DBIC) to do ORM.
589 You probably won't need to use this class directly -- it will be automatically
590 used by DBIC where joins are needed.
592 For Catalyst, this is designed to be used through MyApp::Model::MyAppDB.
593 Offline utilities may wish to use this class directly.
599 B<Note:> This sample application uses a plural form for the database
600 tables (e.g., C<books> and C<authors>) and a singular form for the model
601 objects (e.g., C<Book> and C<Author>); however, Catalyst places no
602 restrictions on the naming conventions you wish to use.
605 =head2 Use C<Catalyst::Model::DBIC::Schema> To Load The Model Class
607 When L<Catalyst::Model::DBIC::Schema|Catalyst::Model::DBIC::Schema> is
608 in use, Catalyst essentially reads an existing copy of your database
609 model and creates a new set of objects under C<MyApp::Model> for use
613 L<Catalyst::Model::DBIC::Schema|Catalyst::Model::DBIC::Schema> you
614 essentially end up with two sets of model classes (only one of which you
615 write... the other set is created automatically in memory when your
616 Catalyst application initializes). For this tutorial application, the
617 important points to remember are: you write the I<result source> files
618 in C<MyAppDB>, but I<within Catalyst> you use the I<automatically
619 created model classes> in C<MyApp::Model>.
621 Use the L<Catalyst::Helper::Model::DBIC::Schema|
622 Catalyst::Helper::Model::DBIC::Schema > helper script to create the
623 model class that loads up the model we created in the previous step:
625 $ script/myapp_create.pl model MyAppDB DBIC::Schema MyAppDB dbi:SQLite:myapp.db '' '' '{ AutoCommit => 1 }'
627 Where the first C<MyAppDB> is the name of the class to be created by the
628 helper in C<lib/MyApp/Model> and the second C<MyAppDB> is the name of
629 existing schema file we created (in C<lib/MyAppDB.pm>). You can see
630 that the helper creates a model file under C<lib/MyApp/Model> (Catalyst
631 has a separate directory under C<lib/MyApp> for each of the three parts
632 of MVC: C<Model>, C<View>, and C<Controller> [although older Catalyst
633 applications often use the directories C<M>, C<V>, and C<C>]).
637 =head1 CREATE A CATALYST CONTROLLER
639 Controllers are where you write methods that respond to C<GET> and C<POST> messages from the user's web browser.
641 Use the Catalyst C<create> script to add a controller for book-related actions:
643 $ script/myapp_create.pl controller Books
645 Then edit C<lib/MyApp/Controller/Books.pm> and add the following method
650 Fetch all book objects and pass to books/list.tt2 in stash to be displayed
655 # Retrieve the usual perl OO '$self' for this object. $c is the Catalyst
656 # 'Context' that's used to 'glue together' the various components
657 # that make up the application
660 # Retrieve all of the book records as book model objects and store in the
661 # stash where they can be accessed by the TT template
662 $c->stash->{books} = [$c->model('MyAppDB::Book')->all];
664 # Set the TT template to use. You will almost always want to do this
665 # in your action methods.
666 $c->stash->{template} = 'books/list.tt2';
669 B<Note:> Programmers experienced with object-oriented Perl should
670 recognize C<$self> as a reference to the object where this method was
671 called. On the other hand, C<$c> will be new to many Perl programmers
672 who have not used Catalyst before (it's sometimes written as
673 C<$context>). The Context object is automatically passed to all
674 Catalyst components. It is used to pass information between components
675 and provide access to Catalyst and plugin functionality.
677 B<TIP>: You may see the C<$c-E<gt>model('MyAppDB::Book')> used above
678 written as C<$c-E<gt>model('MyAppDB')-E<gt>resultset('Book)>. The two
681 B<Note:> Catalyst actions are regular Perl methods, but they make use of
682 Nicholas Clark's C<attributes> module to provide additional information
683 to the Catalyst dispatcher logic.
686 =head1 CATALYST VIEWS
688 Views are where you render output for display in the user's web browser
689 (or possibly using other display technology). As with virtually every
690 aspect of Catalyst, options abound when it comes to the specific view
691 technology you adopt inside your application. However, most Catalyst
692 applications use the Template Toolkit, known as TT (for more information
693 on TT, see L<http://www.template-toolkit.org>). Other popular View
694 technologies include Mason (L<http://www.masonhq.com> and
695 L<http://www.masonbook.com>) and L<HTML::Template|HTML::Template>
696 (L<http://html-template.sourceforge.net>).
699 =head2 Create a Catalyst View Using C<TTSITE>
701 When using TT for the Catalyst view, there are two main helper scripts:
707 L<Catalyst::Helper::View::TT|Catalyst::Helper::View::TT>
711 L<Catalyst::Helper::View::TTSite|Catalyst::Helper::View::TTSite>
715 Both are similar, but C<TT> merely creates the C<lib/MyApp/View/TT.pm>
716 file and leaves the creation of any hierarchical template organization
717 entirely up to you (it also creates a C<t/view_TT.t> file for testing;
718 test cases will be discussed in Part 7). Conversely, the C<TTSite>
719 helper creates a modular and hierarchical view layout with separate
720 Template Toolkit (TT) files for common header and footer information,
721 configuration values, a CSS stylesheet, etc.
723 Enter the following command to enable the C<TTSite> style of view
724 rendering for the tutorial:
726 $ script/myapp_create.pl view TT TTSite
728 This puts a number of files in the C<root/lib> and C<root/src>
729 directories that can be used to customize the look and feel of your
730 application. Also take a look at C<lib/MyApp/View/TT.pm> for config
731 values set by the C<TTSite> helper.
733 B<TIP>: Note that TTSite does one thing that could confuse people who
734 are used to the normal C<TT> Catalyst View: it redefines the Catalyst
735 context object in templates from its usual C<c> to C<Catalyst>. Also
736 keep this in mind when looking at other Catalyst examples (they almost
737 always use C<c>). Note that Catalyst and TT I<do not complain> when you
738 use the wrong name to access the context... it simply outputs blanks for
739 that bogus logic. Finally, be aware that this change in name I<only>
740 applies to how the context object is accessed inside your TT templates,
741 your controllers will continue to use C<$c> (or whatever name you use
742 when fetching the reference from C<@_> inside your methods). (You can
743 change back to the "default" behavior be removing the C<CATALYST_VAR>
744 line from C<lib/MyApp/View/TT.pm>, but you will also have to edit
745 C<root/lib/config/main> and C<root/lib/config/url>. If you do this, be
746 careful not to have a collision between your own C<c> variable and the
747 Catalyst C<c> variable.)
751 =head2 Globally Customize Every View
753 When using TTSite, files in the subdirectories of C<root/lib> can be
754 used to make changes that will appear in every view. For example, to
755 display optional status and error messages in every view, edit
756 C<root/lib/site/layout> update it to match the following (the two HTML
757 C<span> elements are new):
759 <div id="header">[% PROCESS site/header %]</div>
762 <span class="message">[% status_msg %]</span>
763 <span class="error">[% error_msg %]</span>
767 <div id="footer">[% PROCESS site/footer %]</div>
769 If we set either message in the Catalyst stash (e.g.,
770 C<$c-E<gt>stash-E<gt>{status_msg} = 'Hello world'>) it will be displayed
771 whenever any view used by that request is rendered. The C<message> and
772 C<error> CSS styles are automatically defined in C<root/src/ttsite.css>
773 and can be customized to suit your needs.
775 B<Note:> The Catalyst stash only lasts for a single HTTP request. If
776 you need to retain information across requests you can use
777 L<Catalyst::Plugin::Session|Catalyst::Plugin::Session> (we will use
778 Catalyst sessions in the Authentication part).
781 =head2 Create a TT Template Page
783 To add a new page of content to the TTSite view hierarchy, just create a
784 new C<.tt2> file in C<root/src>. Only include HTML markup that goes
785 inside the HTML <body> and </body> tags, TTSite will use the contents of
786 C<root/lib/site> to add the top and bottom.
788 First create a directory for book-related TT templates:
790 $ mkdir root/src/books
792 Then open C<root/src/books/list.tt2> in your editor and enter:
794 [% # This is a TT comment. The '-' at the end "chomps" the newline. You won't -%]
795 [% # see this "chomping" in your browser because HTML ignores blank lines, but -%]
796 [% # it WILL eliminate a blank line if you view the HTML source. It's purely -%]
797 [%- # optional, but both the beginning and the ending TT tags support chomping. -%]
799 [% # Provide a title to root/lib/site/header -%]
800 [% META title = 'Book List' -%]
803 <tr><th>Title</th><th>Rating</th><th>Author(s)</th></tr>
804 [% # Display each book in a table row %]
805 [% FOREACH book IN books -%]
807 <td>[% book.title %]</td>
808 <td>[% book.rating %]</td>
810 [% # Print author count in parens. 'book.authors' uses the 'many_to_many' -%]
811 [% # relationship to retrieve all of the authors of a book. 'size' is a -%]
812 [% # TT VMethod to get the number of elements in a list. -%]
813 ([% book.authors.size %])
814 [% # Use an alternate form of a FOREACH loop to display authors. -%]
815 [% # _ below is the TT string concatenation operator. -%]
816 [% author.last_name _' ' FOREACH author = book.authors %]
817 [% # Note: if many_to_many relationship not used in Authors.pm, you could -%]
818 [% # have used the following to 'walk' through the 'join table objects' -%]
819 [% # bk_author.author.last_name _' ' FOREACH bk_author = book.book_authors %]
825 As indicated by the inline comments above, the C<META title> line uses
826 TT's META feature to provide a title to C<root/lib/site/header>.
827 Meanwhile, the outer C<FOREACH> loop iterates through each C<book> model
828 object and prints the C<title> and C<rating> fields. An inner
829 C<FOREACH> loop prints the last name of each author in a single table
830 cell (a simple space is used between the names; in reality you would
831 probably want to modify the code to use a comma as a separator).
833 If you are new to TT, the [% and %] tags are used to delimit "variable
834 text". TT supports a wide variety of directives for "calling" other
835 files, looping, conditional logic, etc. In general, TT simplifies the
836 usual range of Perl operators down to the single dot (C<.>) operator.
837 This applies to operations as diverse as method calls, hash lookups, and
838 list index values (see
839 L<http://www.template-toolkit.org/docs/default/Manual/Variables.html>
840 for details and examples). In addition to the usual C<Template> module
841 Pod documentation, you can access the TT manual at
842 L<http://www.template-toolkit.org/docs/default/>.
844 B<NOTE>: The C<TTSite> helper creates several TT files using an
845 extension of C<.tt2>. Most other Catalyst and TT examples use an
846 extension of C<.tt>. You can use either extension (or no extension at
847 all) with TTSite and TT, just be sure to use the appropriate extension
848 for both the file itself I<and> the C<$c-E<gt>stash-E<gt>{template} =
849 ...> line in your controller. This document will use C<.tt2> for
850 consistency with the files already created by the C<TTSite> helper.
854 =head1 RUN THE APPLICATION
856 First, let's enable an environment variable option that causes
857 DBIx::Class to dump the SQL statements it's using to access the database
858 (this option can provide extremely helpful troubleshooting information):
860 $ export DBIX_CLASS_STORAGE_DBI_DEBUG=1
862 B<NOTE>: You can also set this in your code using
863 C<$class-E<gt>storage-E<gt>debug(1);>. See
864 L<DBIx::Class::Manual::Troubleshooting|DBIx::Class::Manual::Troubleshooting>
865 for details (including options to log to file vs. the Catalyst
866 development server log.
868 Then run the Catalyst "demo server" script:
870 $ script/myapp_server.pl
872 You should get something like this:
874 $ script/myapp_server.pl
875 [Tue May 16 12:51:33 2006] [catalyst] [debug] Debug messages enabled
876 [Tue May 16 12:51:33 2006] [catalyst] [debug] Loaded plugins:
877 .------------------------------------------------------------------------------.
878 | Catalyst::Plugin::ConfigLoader 0.07 |
879 | Catalyst::Plugin::Static::Simple 0.14 |
880 | Catalyst::Plugin::Dumper 0.000002 |
881 | Catalyst::Plugin::StackTrace 0.04 |
882 | Catalyst::Plugin::DefaultEnd 0.06 |
883 '------------------------------------------------------------------------------'
885 [Tue May 16 12:51:33 2006] [catalyst] [debug] Loaded dispatcher "Catalyst::Dispatcher"
886 [Tue May 16 12:51:33 2006] [catalyst] [debug] Loaded engine "Catalyst::Engine::HTTP"
887 [Tue May 16 12:51:33 2006] [catalyst] [debug] Found home "/home/me/MyApp"
888 [Tue May 16 12:51:37 2006] [catalyst] [debug] Loaded components:
889 .-------------------------------------------------------------------+----------.
891 +-------------------------------------------------------------------+----------+
892 | MyApp::Controller::Books | instance |
893 | MyApp::Controller::Root | instance |
894 | MyApp::Model::MyAppDB | instance |
895 | MyApp::Model::MyAppDB::Author | class |
896 | MyApp::Model::MyAppDB::Book | class |
897 | MyApp::Model::MyAppDB::BookAuthor | class |
898 | MyApp::View::TT | instance |
899 '-------------------------------------------------------------------+----------'
901 [Tue May 16 12:51:37 2006] [catalyst] [debug] Loaded Private actions:
902 .----------------------+----------------------------------------+--------------.
903 | Private | Class | Method |
904 +----------------------+----------------------------------------+--------------+
905 | /default | MyApp::Controller::Root | default |
906 | /end | MyApp | end |
907 | /books/list | MyApp::Controller::Books | list |
908 '----------------------+----------------------------------------+--------------'
910 [Tue May 16 12:51:37 2006] [catalyst] [debug] Loaded Path actions:
911 .--------------------------------------+---------------------------------------.
913 +--------------------------------------+---------------------------------------+
914 | /books/list | /books/list |
915 '--------------------------------------+---------------------------------------'
917 [Tue May 16 12:51:37 2006] [catalyst] [info] MyApp powered by Catalyst 5.6902
918 You can connect to your server at http://localhost:3000
920 Some things you should note in the output above:
926 Catalyst::Model::DBIC::Schema took our C<MyAppDB::Book> and made it
927 C<MyApp::Model::MyAppDB::Book> (and similar actions were performed on
928 C<MyAppDB::Author> and C<MyAppDB::BookAuthor>).
932 The "list" action in our Books controller showed up with a path of
938 Point your browser to L<http://localhost:3000> and you should still get
939 the Catalyst welcome page.
941 Next, to view the book list, change the URL in your browser to
942 L<http://localhost:3000/books/list>. You should get a list of the five
943 books loaded by the C<myapp01.sql> script above, with TTSite providing
944 the formatting for the very simple output we generated in our template.
945 The count and space-separated list of author last names appear on the
948 Also notice in the output of the C<script/myapp_server.pl> that DBIC
949 used the following SQL to retrieve the data:
951 SELECT me.id, me.title, me.rating FROM books me
953 Along with a list of the following commands to retrieve the authors for
954 each book (the lines have been "word wrapped" here to improve
957 SELECT author.id, author.first_name, author.last_name
959 JOIN authors author ON ( author.id = me.author_id )
960 WHERE ( me.book_id = ? ): `1'
962 You should see 10 such lines of debug output, two for each of the five
963 author_id values (it pulls the data once for the count logic and another
964 time to actually display the list).
969 Kennedy Clark, C<hkclark@gmail.com>
971 Please report any errors, issues or suggestions to the author.
973 Copyright 2006, Kennedy Clark, under Creative Commons License (L<http://creativecommons.org/licenses/by-nc-sa/2.5/>).