3 Catalyst::Manual::Tutorial::CatalystBasics - Catalyst Tutorial - Part 2: Catalyst Application Development Basics
8 This is B<Part 2 of 9> for the Catalyst tutorial.
10 L<Tutorial Overview|Catalyst::Manual::Tutorial>
16 L<Introduction|Catalyst::Manual::Tutorial::Intro>
24 L<Basic CRUD|Catalyst::Manual::Tutorial::BasicCRUD>
28 L<Authentication|Catalyst::Manual::Tutorial::Authentication>
32 L<Authorization|Catalyst::Manual::Tutorial::Authorization>
36 L<Debugging|Catalyst::Manual::Tutorial::Debugging>
40 L<Testing|Catalyst::Manual::Tutorial::Testing>
44 L<Advanced CRUD|Catalyst::Manual::Tutorial::AdvancedCRUD>
48 L<Appendices|Catalyst::Manual::Tutorial::Appendices>
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:
61 =item * Helper Scripts
63 Catalyst helper scripts that can be used to rapidly bootstrap the
64 skeletal structure of an application.
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:
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
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
93 As suggested by its name, the controller takes user requests and routes
94 them to the necessary model and view.
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.
106 You can checkout the source code for this example from the catalyst
107 subversion repository as per the instructions in
108 L<Catalyst::Manual::Tutorial::Intro>
110 =head1 CREATE A CATALYST PROJECT
112 Catalyst provides a number of helper scripts that can be used to quickly
113 flesh out the basic structure of your application. All Catalyst projects
114 begin with the C<catalyst.pl> helper (see L<Catalyst::Helper|Catalyst::Helper>
115 for more information on helpers). Also note that as of Catalyst 5.7000,
116 you will not have the helper scripts unless you install both
117 L<Catalyst::Runtime|Catalyst::Runtime> and L<Catalyst::Devel|Catalyst::Devel>.
119 In the case of this tutorial, use the Catalyst C<catalyst.pl> script to
120 initialize the framework for an application called C<MyApp>:
124 created "MyApp/script"
128 created "MyApp/script/myapp_create.pl"
131 The C<catalyst.pl> helper script will display the names of the
132 directories and files it creates.
134 Though it's too early for any significant celebration, we already have a
135 functioning application. Run the following command to run this
136 application with the built-in development web server:
138 $ script/myapp_server.pl
139 [debug] Debug messages enabled
140 [debug] Loaded plugins:
141 .----------------------------------------------------------------------------.
142 | Catalyst::Plugin::ConfigLoader 0.06 |
143 | Catalyst::Plugin::Static::Simple 0.14 |
144 '----------------------------------------------------------------------------'
146 [debug] Loaded dispatcher "Catalyst::Dispatcher"
147 [debug] Loaded engine "Catalyst::Engine::HTTP"
148 [debug] Found home "/root/dev/MyApp"
149 [debug] Loaded components:
150 .-----------------------------------------------------------------+----------.
152 +-----------------------------------------------------------------+----------+
153 | MyApp::Controller::Root | instance |
154 '-----------------------------------------------------------------+----------'
156 [debug] Loaded Private actions:
157 .----------------------+--------------------------------------+--------------.
158 | Private | Class | Method |
159 +----------------------+--------------------------------------+--------------+
160 | /default | MyApp::Controller::Root | default |
161 | /end | MyApp::Controller::Root | end |
162 '----------------------+--------------------------------------+--------------'
164 [info] MyApp powered by Catalyst 5.7000
165 You can connect to your server at http://localhost.localdomain:3000
167 B<NOTE>: Be sure you run the C<script/myapp_server.pl> command from the
168 'base' directory of your application, not inside the C<script> directory
169 itself. It doesn't make a difference at this point, but it will as soon
170 as we get the database going in the next section.
172 Point your web browser to L<http://localhost:3000> (substituting a
173 different hostname or IP address as appropriate) and you should be
174 greeted by the Catalyst welcome screen. Information similar to the
175 following should be appended to the logging output of the development
178 [info] *** Request 1 (0.043/s) [6003] [Fri Jul 7 13:32:53 2006] ***
179 [debug] "GET" request for "/" from "127.0.0.1"
180 [info] Request took 0.067675s (14.777/s)
181 .----------------------------------------------------------------+-----------.
183 +----------------------------------------------------------------+-----------+
184 | /default | 0.002844s |
186 '----------------------------------------------------------------+-----------'
188 Press Ctrl-C to break out of the development server.
191 =head1 CREATE A SQLITE DATABASE
193 In this step, we make a text file with the required SQL commands to
194 create a database table and load some sample data. Open C<myapp01.sql>
195 in your editor and enter:
198 -- Create a very simple database to hold book and author information
201 id INTEGER PRIMARY KEY,
205 -- 'book_authors' is a many-to-many join table between books & authors
206 CREATE TABLE book_authors (
209 PRIMARY KEY (book_id, author_id)
211 CREATE TABLE authors (
212 id INTEGER PRIMARY KEY,
217 --- Load some sample data
219 INSERT INTO books VALUES (1, 'CCSP SNRS Exam Certification Guide', 5);
220 INSERT INTO books VALUES (2, 'TCP/IP Illustrated, Volume 1', 5);
221 INSERT INTO books VALUES (3, 'Internetworking with TCP/IP Vol.1', 4);
222 INSERT INTO books VALUES (4, 'Perl Cookbook', 5);
223 INSERT INTO books VALUES (5, 'Designing with Web Standards', 5);
224 INSERT INTO authors VALUES (1, 'Greg', 'Bastien');
225 INSERT INTO authors VALUES (2, 'Sara', 'Nasseh');
226 INSERT INTO authors VALUES (3, 'Christian', 'Degu');
227 INSERT INTO authors VALUES (4, 'Richard', 'Stevens');
228 INSERT INTO authors VALUES (5, 'Douglas', 'Comer');
229 INSERT INTO authors VALUES (6, 'Tom', 'Christiansen');
230 INSERT INTO authors VALUES (7, ' Nathan', 'Torkington');
231 INSERT INTO authors VALUES (8, 'Jeffrey', 'Zeldman');
232 INSERT INTO book_authors VALUES (1, 1);
233 INSERT INTO book_authors VALUES (1, 2);
234 INSERT INTO book_authors VALUES (1, 3);
235 INSERT INTO book_authors VALUES (2, 4);
236 INSERT INTO book_authors VALUES (3, 5);
237 INSERT INTO book_authors VALUES (4, 6);
238 INSERT INTO book_authors VALUES (4, 7);
239 INSERT INTO book_authors VALUES (5, 8);
241 B<TIP>: See Appendix 1 for tips on removing the leading spaces when
242 cutting and pasting example code from POD-based documents.
244 Then use the following command to build a C<myapp.db> SQLite database:
246 $ sqlite3 myapp.db < myapp01.sql
248 If you need to create the database more than once, you probably want to
249 issue the C<rm myapp.db> command to delete the database before you use
250 the C<sqlite3 myapp.db < myapp01.sql> command.
252 Once the C<myapp.db> database file has been created and initialized, you
253 can use the SQLite command line environment to do a quick dump of the
258 Enter ".help" for instructions
259 sqlite> select * from books;
260 1|CCSP SNRS Exam Certification Guide|5
261 2|TCP/IP Illustrated, Volume 1|5
262 3|Internetworking with TCP/IP Vol.1|4
264 5|Designing with Web Standards|5
270 $ sqlite3 myapp.db "select * from books"
271 1|CCSP SNRS Exam Certification Guide|5
272 2|TCP/IP Illustrated, Volume 1|5
273 3|Internetworking with TCP/IP Vol.1|4
275 5|Designing with Web Standards|5
277 As with most other SQL tools, if you are using the full "interactive"
278 environment you need to terminate your SQL commands with a ";" (it's not
279 required if you do a single SQL statement on the command line). Use
280 ".q" to exit from SQLite from the SQLite interactive mode and return to
281 your OS command prompt.
284 =head1 EDIT THE LIST OF CATALYST PLUGINS
286 One of the greatest benefits of Catalyst is that it has such a large
287 library of plugins available. Plugins are used to seamlessly integrate
288 existing Perl modules into the overall Catalyst framework. In general,
289 they do this by adding additional methods to the C<context> object
290 (generally written as C<$c>) that Catalyst passes to every component
291 throughout the framework.
293 By default, Catalyst enables three plugins/flags:
301 Enables the Catalyst debug output you saw when we started the
302 C<script/myapp_server.pl> development server earlier. You can remove
303 this plugin when you place your application into production.
305 As you may have noticed, C<-Debug> is not a plugin, but a I<flag>.
306 Although most of the items specified on the C<use Catalyst> line of your
307 application class will be plugins, Catalyst supports a limited number of
308 flag options (of these, C<-Debug> is the most common). See the
309 documentation for C<Catalyst.pm> to get details on other flags
310 (currently C<-Engine>, C<-Home>, and C<-Log>).
312 If you prefer, you can use the C<$c-E<gt>debug> method to enable debug
317 L<Catalyst::Plugin::ConfigLoader|Catalyst::Plugin::ConfigLoader>
319 C<ConfigLoader> provides an automatic way to load configurable
320 parameters for your application from a central YAML file (versus having
321 the values hard-coded inside your Perl modules). If you have not been
322 exposed to YAML before, it is a human-readable data serialization format
323 that can be used to read (and write) values to/from text files. We will
324 see how to use this feature of Catalyst during the authentication and
325 authorization sections (Part 4 and Part 5).
329 L<Catalyst::Plugin::Static::Simple|Catalyst::Plugin::Static::Simple>
331 C<Static::Simple> provides an easy method of serving static content such
332 as images and CSS files under the development server.
336 To modify the list of plugins, edit C<lib/MyApp.pm> (this file is
337 generally referred to as your I<application class>) and delete the line
340 use Catalyst qw/-Debug ConfigLoader Static::Simple/;
352 This tells Catalyst to start using one new plugin:
358 L<Catalyst::Plugin::StackTrace|Catalyst::Plugin::StackTrace>
360 Adds a stack trace to the standard Catalyst "debug screen" (this is the
361 screen Catalyst sends to your browser when an error occurs).
363 Note: L<StackTrace|Catalyst::Plugin::StackTrace> output appears in your
364 browser, not in the console window from which you're running your
365 application, which is where logging output usually goes.
369 Note that when specifying plugins on the C<use Catalyst> line, you can
370 omit C<Catalyst::Plugin::> from the name. Additionally, you can spread
371 the plugin names across multiple lines as shown here, or place them all
372 on one (or more) lines as with the default configuration.
374 B<TIP:> You may see examples that include the
375 L<Catalyst::Plugin::DefaultEnd|Catalyst::Plugin::DefaultEnd>
376 plugins. As of Catalyst 5.7000, C<DefaultEnd> has been
377 deprecated in favor of
378 L<Catalyst::Action::RenderView|Catalyst::Action::RenderView>
379 (as the name of the package suggests, C<RenderView> is not
380 a plugin, but an action). The purpose of both is essentially the same:
381 forward processing to the view to be rendered. Applications generated
382 under 5.7000 should automatically use C<RenderView> and "just work"
383 for most applications. For more information on C<RenderView> and
384 the various options for forwarding to your view logic, please refer
385 to the "Using RenderView for the Default View" section under
386 "CATALYST VIEWS" below.
389 =head1 DATABASE ACCESS WITH C<DBIx::Class>
391 Catalyst can be used with virtually any form of persistent datastore
392 available via Perl. For example,
393 L<Catalyst::Model::DBI|Catalyst::Model::DBI> can be used to
394 easily access databases through the traditional Perl C<DBI> interface.
395 However, most Catalyst applications use some form of ORM technology to
396 automatically create and save model objects as they are used. Although
397 Tony Bowden's L<Class::DBI|Class::DBI> has been the traditional
398 Perl ORM engine, Matt Trout's L<DBIx::Class|DBIx::Class> (abbreviated
399 as "DBIC") has rapidly emerged as the Perl-based ORM technology of choice.
400 Most new Catalyst applications rely on DBIC, as will this tutorial.
402 Note: See L<Catalyst::Model::CDBI> for more information on using
403 Catalyst with L<Class::DBI|Class::DBI>.
405 =head2 Create a DBIC Schema File
407 DBIx::Class uses a schema file to load other classes that represent the
408 tables in your database (DBIC refers to these "table objects" as "result
409 sources"; see L<DBIx::Class::ResultSource>). In this case, we want to
410 load the model object for the C<books>, C<book_authors>, and C<authors>
411 tables created in the previous step.
413 Open C<lib/MyAppDB.pm> in your editor and insert:
419 MyAppDB - DBIC Schema Class
423 # Our schema needs to inherit from 'DBIx::Class::Schema'
424 use base qw/DBIx::Class::Schema/;
426 # Need to load the DB Model classes here.
427 # You can use this syntax if you want:
428 # __PACKAGE__->load_classes(qw/Book BookAuthor Author/);
429 # Also, if you simply want to load all of the classes in a directory
430 # of the same name as your schema class (as we do here) you can use:
431 # __PACKAGE__->load_classes(qw//);
432 # But the variation below is more flexible in that it can be used to
433 # load from multiple namespaces.
434 __PACKAGE__->load_classes({
435 MyAppDB => [qw/Book BookAuthor Author/]
440 B<Note:> C<__PACKAGE__> is just a shorthand way of referencing the name
441 of the package where it is used. Therefore, in C<MyAppDB.pm>,
442 C<__PACKAGE__> is equivalent to C<MyAppDB>.
445 =head2 Create the DBIC "Result Source" Files
447 In this step, we create "table classes" (again, these are called a
448 "result source" classes in DBIC) that act as model objects for the
449 C<books>, C<book_authors>, and C<authors> tables in our database.
451 First, create a directory to hold the class:
455 Then open C<lib/MyAppDB/Book.pm> in your editor and enter:
457 package MyAppDB::Book;
459 use base qw/DBIx::Class/;
461 # Load required DBIC stuff
462 __PACKAGE__->load_components(qw/PK::Auto Core/);
464 __PACKAGE__->table('books');
465 # Set columns in table
466 __PACKAGE__->add_columns(qw/id title rating/);
467 # Set the primary key for the table
468 __PACKAGE__->set_primary_key(qw/id/);
476 # 1) Name of relationship, DBIC will create accessor with this name
477 # 2) Name of the model class referenced by this relationship
478 # 3) Column name in *foreign* table
479 __PACKAGE__->has_many(book_authors => 'MyAppDB::BookAuthor', 'book_id');
483 # 1) Name of relationship, DBIC will create accessor with this name
484 # 2) Name of has_many() relationship this many_to_many() is shortcut for
485 # 3) Name of belongs_to() relationship in model class of has_many() above
486 # You must already have the has_many() defined to use a many_to_many().
487 __PACKAGE__->many_to_many(authors => 'book_authors', 'author');
492 MyAppDB::Book - A model object representing a book.
496 This is an object that represents a row in the 'books' table of your application
497 database. It uses DBIx::Class (aka, DBIC) to do ORM.
499 For Catalyst, this is designed to be used through MyApp::Model::MyAppDB.
500 Offline utilities may wish to use this class directly.
506 This defines both a C<has_many> and a C<many_to_many> relationship. The
507 C<many_to_many> relationship is optional, but it makes it easier to map
508 a book to its collection of authors. Without it, we would have to
509 "walk" though the C<book_authors> table as in
510 C<$book-E<gt>book_authors-E<gt>first-E<gt>author-E<gt>last_name> (we
511 will see examples on how to use DBIC objects in your code soon, but note
512 that because C<$book-E<gt>book_authors> can return multiple authors, we
513 have to use C<first> to display a single author). C<many_to_many> allows
514 us to use the shorter C<$book-E<gt>authors-E<gt>first-E<gt>last_name>.
515 Note that you cannot define a C<many_to_many> relationship without also
516 having the C<has_many> relationship in place.
518 Next, open C<lib/MyAppDB/Author.pm> in your editor and enter:
520 package MyAppDB::Author;
522 use base qw/DBIx::Class/;
524 # Load required DBIC stuff
525 __PACKAGE__->load_components(qw/PK::Auto Core/);
527 __PACKAGE__->table('authors');
528 # Set columns in table
529 __PACKAGE__->add_columns(qw/id first_name last_name/);
530 # Set the primary key for the table
531 __PACKAGE__->set_primary_key(qw/id/);
539 # 1) Name of relationship, DBIC will create accessor with this name
540 # 2) Name of the model class referenced by this relationship
541 # 3) Column name in *foreign* table
542 __PACKAGE__->has_many(book_author => 'MyAppDB::BookAuthor', 'author_id');
546 # 1) Name of relationship, DBIC will create accessor with this name
547 # 2) Name of has_many() relationship this many_to_many() is shortcut for
548 # 3) Name of belongs_to() relationship in model class of has_many() above
549 # You must already have the has_many() defined to use a many_to_many().
550 __PACKAGE__->many_to_many(books => 'book_author', 'book');
555 MyAppDB::Author - A model object representing an author of a book (if a book has
556 multiple authors, each will be represented be separate Author object).
560 This is an object that represents a row in the 'authors' table of your application
561 database. It uses DBIx::Class (aka, DBIC) to do ORM.
563 For Catalyst, this is designed to be used through MyApp::Model::MyAppDB.
564 Offline utilities may wish to use this class directly.
570 Finally, open C<lib/MyAppDB/BookAuthor.pm> in your editor and enter:
572 package MyAppDB::BookAuthor;
574 use base qw/DBIx::Class/;
576 # Load required DBIC stuff
577 __PACKAGE__->load_components(qw/PK::Auto Core/);
579 __PACKAGE__->table('book_authors');
580 # Set columns in table
581 __PACKAGE__->add_columns(qw/book_id author_id/);
582 # Set the primary key for the table
583 __PACKAGE__->set_primary_key(qw/book_id author_id/);
591 # 1) Name of relationship, DBIC will create accessor with this name
592 # 2) Name of the model class referenced by this relationship
593 # 3) Column name in *this* table
594 __PACKAGE__->belongs_to(book => 'MyAppDB::Book', 'book_id');
598 # 1) Name of relationship, DBIC will create accessor with this name
599 # 2) Name of the model class referenced by this relationship
600 # 3) Column name in *this* table
601 __PACKAGE__->belongs_to(author => 'MyAppDB::Author', 'author_id');
606 MyAppDB::BookAuthor - A model object representing the JOIN between an author and
611 This is an object that represents a row in the 'book_authors' table of your
612 application database. It uses DBIx::Class (aka, DBIC) to do ORM.
614 You probably won't need to use this class directly -- it will be automatically
615 used by DBIC where joins are needed.
617 For Catalyst, this is designed to be used through MyApp::Model::MyAppDB.
618 Offline utilities may wish to use this class directly.
624 B<Note:> This sample application uses a plural form for the database
625 tables (e.g., C<books> and C<authors>) and a singular form for the model
626 objects (e.g., C<Book> and C<Author>); however, Catalyst places no
627 restrictions on the naming conventions you wish to use.
629 =head2 Use C<Catalyst::Model::DBIC::Schema> To Load The Model Class
631 When L<Catalyst::Model::DBIC::Schema|Catalyst::Model::DBIC::Schema> is
632 in use, Catalyst essentially reads an existing copy of your database
633 model and creates a new set of objects under C<MyApp::Model> for use
637 L<Catalyst::Model::DBIC::Schema|Catalyst::Model::DBIC::Schema> you
638 essentially end up with two sets of model classes (only one of which
639 you write... the other set is created automatically in memory when
640 your Catalyst application initializes). For this tutorial application,
641 the important points to remember are: you write the I<result source>
642 files in C<MyAppDB>, but I<within Catalyst> you use the I<automatically
643 created model classes> in C<MyApp::Model>.
646 L<Catalyst::Helper::Model::DBIC::Schema|Catalyst::Helper::Model::DBIC::Schema>
647 helper script to create the model class that loads up the model we
648 created in the previous step:
650 $ script/myapp_create.pl model MyAppDB DBIC::Schema MyAppDB dbi:SQLite:myapp.db '' '' '{ AutoCommit => 1 }'
651 exists "/root/dev/MyApp/script/../lib/MyApp/Model"
652 exists "/root/dev/MyApp/script/../t"
653 created "/root/dev/MyApp/script/../lib/MyApp/Model/MyAppDB.pm"
654 created "/root/dev/MyApp/script/../t/model_MyAppDB.t"
657 Where the first C<MyAppDB> is the name of the class to be created by the
658 helper in C<lib/MyApp/Model> and the second C<MyAppDB> is the name of
659 existing schema file we created (in C<lib/MyAppDB.pm>). You can see
660 that the helper creates a model file under C<lib/MyApp/Model> (Catalyst
661 has a separate directory under C<lib/MyApp> for each of the three parts
662 of MVC: C<Model>, C<View>, and C<Controller> [although older Catalyst
663 applications often use the directories C<M>, C<V>, and C<C>]).
666 =head1 CREATE A CATALYST CONTROLLER
668 Controllers are where you write methods that interact with user
669 input--typically, controller methods respond to C<GET> and C<POST>
670 messages from the user's web browser.
672 Use the Catalyst C<create> script to add a controller for book-related
675 $ script/myapp_create.pl controller Books
676 exists "/root/dev/MyApp/script/../lib/MyApp/Controller"
677 exists "/root/dev/MyApp/script/../t"
678 created "/root/dev/MyApp/script/../lib/MyApp/Controller/Books.pm"
679 created "/root/dev/MyApp/script/../t/controller_Books.t"
681 Then edit C<lib/MyApp/Controller/Books.pm> and add the following method
686 Fetch all book objects and pass to books/list.tt2 in stash to be displayed
691 # Retrieve the usual perl OO '$self' for this object. $c is the Catalyst
692 # 'Context' that's used to 'glue together' the various components
693 # that make up the application
696 # Retrieve all of the book records as book model objects and store in the
697 # stash where they can be accessed by the TT template
698 $c->stash->{books} = [$c->model('MyAppDB::Book')->all];
700 # Set the TT template to use. You will almost always want to do this
701 # in your action methods (actions methods respond to user input in
703 $c->stash->{template} = 'books/list.tt2';
706 B<Note:> Programmers experienced with object-oriented Perl should
707 recognize C<$self> as a reference to the object where this method was
708 called. On the other hand, C<$c> will be new to many Perl programmers
709 who have not used Catalyst before (it's sometimes written as
710 C<$context>). The Context object is automatically passed to all
711 Catalyst components. It is used to pass information between components
712 and provide access to Catalyst and plugin functionality.
714 B<TIP>: You may see the C<$c-E<gt>model('MyAppDB::Book')> used above
715 written as C<$c-E<gt>model('MyAppDB')-E<gt>resultset('Book)>. The two
718 B<Note:> Catalyst actions are regular Perl methods, but they make use of
719 Nicholas Clark's C<attributes> module (that's the C<: Local> next to the
720 C<sub list> in the code above) to provide additional information to the
721 Catalyst dispatcher logic.
724 =head1 CATALYST VIEWS
726 Views are where you render output, typically for display in the user's
727 web browser, but also possibly using other display output-generation
728 systems. As with virtually every aspect of Catalyst, options abound
729 when it comes to the specific view technology you adopt inside your
730 application. However, most Catalyst applications use the Template
731 Toolkit, known as TT (for more information on TT, see
732 L<http://www.template-toolkit.org>). Other popular view technologies
733 include Mason (L<http://www.masonhq.com> and
734 L<http://www.masonbook.com>) and L<HTML::Template|HTML::Template>
735 (L<http://html-template.sourceforge.net>).
737 =head2 Create a Catalyst View Using C<TTSite>
739 When using TT for the Catalyst view, there are two main helper scripts:
745 L<Catalyst::Helper::View::TT|Catalyst::Helper::View::TT>
749 L<Catalyst::Helper::View::TTSite|Catalyst::Helper::View::TTSite>
753 Both are similar, but C<TT> merely creates the C<lib/MyApp/View/TT.pm>
754 file and leaves the creation of any hierarchical template organization
755 entirely up to you. (It also creates a C<t/view_TT.t> file for testing;
756 test cases will be discussed in Part 7). The C<TTSite> helper creates a
757 modular and hierarchical view layout with separate Template Toolkit (TT)
758 files for common header and footer information, configuration values, a
759 CSS stylesheet, and more.
761 Enter the following command to enable the C<TTSite> style of view
762 rendering for this tutorial:
764 $ script/myapp_create.pl view TT TTSite
765 exists "/root/dev/MyApp/script/../lib/MyApp/View"
766 exists "/root/dev/MyApp/script/../t"
767 created "/root/dev/MyApp/script/../lib/MyApp/View/TT.pm"
768 created "/root/dev/MyApp/script/../root/lib"
770 created "/root/dev/MyApp/script/../root/src/ttsite.css"
772 This puts a number of files in the C<root/lib> and C<root/src>
773 directories that can be used to customize the look and feel of your
774 application. Also take a look at C<lib/MyApp/View/TT.pm> for config
775 values set by the C<TTSite> helper.
777 B<TIP>: Note that TTSite does one thing that could confuse people who
778 are used to the normal C<TT> Catalyst view: it redefines the Catalyst
779 context object in templates from its usual C<c> to C<Catalyst>. When
780 looking at other Catalyst examples, remember that they almost always use
781 C<c>. Note that Catalyst and TT I<do not complain> when you use the
782 wrong name to access the context object...TT simply outputs blanks for
783 that bogus logic (see next tip to change this behavior with TT C<DEBUG>
784 options). Finally, be aware that this change in name I<only>
785 applies to how the context object is accessed inside your TT templates;
786 your controllers will continue to use C<$c> (or whatever name you use
787 when fetching the reference from C<@_> inside your methods). (You can
788 change back to the "default" behavior be removing the C<CATALYST_VAR>
789 line from C<lib/MyApp/View/TT.pm>, but you will also have to edit
790 C<root/lib/config/main> and C<root/lib/config/url>. If you do this, be
791 careful not to have a collision between your own C<c> variable and the
792 Catalyst C<c> variable.)
794 B<TIP>: When troubleshooting TT it can be helpful to enable variable
795 C<DEBUG> options. You can do this in a Catalyst environment by adding
796 a C<DEBUG> line to the C<__PACKAGE__->config> declaration in
797 C<lib/MyApp/View/TT.pm>:
799 __PACKAGE__->config({
800 CATALYST_VAR => 'Catalyst',
806 There are a variety of options you can use, such as 'undef', 'all',
807 'service', 'context', 'parser', 'provider', and 'service'. See
808 L<Template::Constants> for more information (remove the C<DEBUG_>
809 portion of the name shown in the TT docs and convert to lower case
810 for use inside Catalyst).
812 B<NOTE:> Please be sure to disable TT debug options before
813 continuing the tutorial (especially the 'undef' option -- leaving
814 this enabled will conflict with several of the conventions used
815 by this tutorial and TTSite to leave some variables undefined
819 =head2 Using C<RenderView> for the Default View
821 Once your controller logic has processed the request from a user, it
822 forwards processing to your view in order to generate the appropriate
823 response output. Catalyst v5.7000 ships with a new mechanism,
824 L<Catalyst::Action::RenderView|Catalyst::Action::RenderView>, that
825 automatically performs this operation. If you look in
826 C<lib/MyApp/Controller/Root.pm>, you should see the this empty
827 definition for the C<sub end> method:
829 sub end : ActionClass('RenderView') {}
831 The following bullet points provide a quick overview of the
832 C<RenderView> process:
838 C<Root.pm> is designed to hold application-wide logic.
842 At the end of a given user request, Catalyst will call the most specific
843 C<end> method that's appropriate. For example, if the controller for a
844 request has an C<end> method defined, it will be called. However, if
845 the controller does not define a controller-specific C<end> method, the
846 "global" C<end> method in C<Root.pm> will be called.
850 Because the definition includes an C<ActionClass> attribute, the
851 L<Catalyst::Action::RenderView|Catalyst::Action::RenderView> logic
852 will be executed B<after> any code inside the definition of C<sub end>
853 is run. See L<Catalyst::Manual::Actions|Catalyst::Manual::Actions>
854 for more information on C<ActionClass>.
858 Because C<sub end> is empty, this effectively just runs the default
859 logic in C<RenderView>. However, you can easily extend the
860 C<RenderView> logic by adding your own code inside the empty method body
861 (C<{}>) created by the Catalyst Helpers when we first ran the
862 C<catalyst.pl> to initialize our application. See
863 L<Catalyst::Action::RenderView|Catalyst::Action::RenderView> for more
864 detailed information on how to extended C<RenderView> in C<sub end>.
869 =head3 The History Leading Up To C<RenderView>
871 Although C<RenderView> strikes a nice balance between default
872 behavior and easy extensibility, it is a new feature that won't
873 appear in most existing Catalyst examples. This section provides
874 some brief background on the evolution of default view rendering
875 logic with an eye to how they can be migrated to C<RenderView>:
881 Private C<end> Action in Application Class
883 Older Catalyst-related documents often suggest that you add a "private
884 end action" to your application class (C<MyApp.pm>) or Root.pm
885 (C<MyApp/Controller/Root.pm>). These examples should be easily
886 converted to L<RenderView|Catalyst::Action::RenderView> by simply adding
887 the attribute C<:ActionClass('RenderView')> to the C<sub end>
888 definition. If end sub is defined in your application class
889 (C<MyApp.pm>), you should also migrate it to
890 C<MyApp/Controller/Root.pm>.
894 L<Catalyst::Plugin::DefaultEnd|Catalyst::Plugin::DefaultEnd>
896 C<DefaultEnd> represented the "next step" in passing processing from
897 your controller to your view. It has the advantage of only requiring
898 that C<DefaultEnd> be added to the list of plugins in C<lib/MyApp.pm>.
899 It also allowed you to add "dump_info=1" (precede with "?" or "&"
900 depending on where it is in the URL) to I<force> the debug screen at the
901 end of the Catalyst request processing cycle. However, it was more
902 difficult to extend than the C<RenderView> mechanism, and is now
907 L<Catalyst::Action::RenderView|Catalyst::Action::RenderView>
909 As discussed above, the current recommended approach to handling your
911 L<Catalyst::Action::RenderView|Catalyst::Action::RenderView>. Although
912 similar in first appearance to the "private end action" approach, it
913 utilizes Catalyst's "ActionClass" mechanism to provide both automatic
914 default behavior (you don't have to include a plugin as with
915 C<DefaultEnd>) and easy extensibility. As with C<DefaultEnd>, it allows
916 you to add "dump_info=1" (precede with "?" or "&" depending on where it
917 is in the URL) to I<force> the debug screen at the end of the Catalyst
918 request processing cycle.
922 It is recommended that all Catalyst applications use or migrate to
923 the C<RenderView> approach.
926 =head2 Globally Customize Every View
928 When using TTSite, files in the subdirectories of C<root/lib> can be
929 used to make changes that will appear in every view. For example, to
930 display optional status and error messages in every view, edit
931 C<root/lib/site/layout>, updating it to match the following (the two HTML
932 C<span> elements are new):
934 <div id="header">[% PROCESS site/header %]</div>
937 <span class="message">[% status_msg %]</span>
938 <span class="error">[% error_msg %]</span>
942 <div id="footer">[% PROCESS site/footer %]</div>
944 If we set either message in the Catalyst stash (e.g.,
945 C<$c-E<gt>stash-E<gt>{status_msg} = 'Request was successful!'>) it will
946 be displayed whenever any view used by that request is rendered. The
947 C<message> and C<error> CSS styles are automatically defined in
948 C<root/src/ttsite.css> and can be customized to suit your needs.
950 B<Note:> The Catalyst stash only lasts for a single HTTP request. If
951 you need to retain information across requests you can use
952 L<Catalyst::Plugin::Session|Catalyst::Plugin::Session> (we will use
953 Catalyst sessions in the Authentication part of the tutorial).
956 =head2 Create a TT Template Page
958 To add a new page of content to the TTSite view hierarchy, just create a
959 new C<.tt2> file in C<root/src>. Only include HTML markup that goes
960 inside the HTML <body> and </body> tags, TTSite will use the contents of
961 C<root/lib/site> to add the top and bottom.
963 First create a directory for book-related TT templates:
965 $ mkdir root/src/books
967 Then open C<root/src/books/list.tt2> in your editor and enter:
969 [% # This is a TT comment. The '-' at the end "chomps" the newline. You won't -%]
970 [% # see this "chomping" in your browser because HTML ignores blank lines, but -%]
971 [% # it WILL eliminate a blank line if you view the HTML source. It's purely -%]
972 [%- # optional, but both the beginning and the ending TT tags support chomping. -%]
974 [% # Provide a title to root/lib/site/header -%]
975 [% META title = 'Book List' -%]
978 <tr><th>Title</th><th>Rating</th><th>Author(s)</th></tr>
979 [% # Display each book in a table row %]
980 [% FOREACH book IN books -%]
982 <td>[% book.title %]</td>
983 <td>[% book.rating %]</td>
985 [% # First initialize a TT variable to hold a list. Then use a TT FOREACH -%]
986 [% # loop in 'side effect notation' to load just the last names of the -%]
987 [% # authors into the list. Note that the 'push' TT vmethod does not -%]
988 [% # a value, so nothing will be printed here. But, if you have something -%]
989 [% # in TT that does return a method and you don't want it printed, you -%]
990 [% # can: 1) assign it to a bogus value, or 2) use the CALL keyword to -%]
991 [% # call it and discard the return value. -%]
993 tt_authors.push(author.last_name) FOREACH author = book.authors %]
994 [% # Now use a TT 'virtual method' to display the author count in parens -%]
995 ([% tt_authors.size %])
996 [% # Use another TT vmethod to join & print the names & comma separators -%]
997 [% tt_authors.join(', ') %]
1003 As indicated by the inline comments above, the C<META title> line uses
1004 TT's META feature to provide a title to C<root/lib/site/header>.
1005 Meanwhile, the outer C<FOREACH> loop iterates through each C<book> model
1006 object and prints the C<title> and C<rating> fields. An inner
1007 C<FOREACH> loop prints the last name of each author in a comma-separated
1008 list within a single table cell.
1010 If you are new to TT, the C<[%> and C<%]> tags are used to delimit TT
1011 code. TT supports a wide variety of directives for "calling" other
1012 files, looping, conditional logic, etc. In general, TT simplifies the
1013 usual range of Perl operators down to the single dot (C<.>) operator.
1014 This applies to operations as diverse as method calls, hash lookups, and
1015 list index values (see
1016 L<http://www.template-toolkit.org/docs/default/Manual/Variables.html>
1017 for details and examples). In addition to the usual C<Template> module
1018 Pod documentation, you can access the TT manual at
1019 L<http://www.template-toolkit.org/docs/default/>.
1021 B<NOTE>: The C<TTSite> helper creates several TT files using an
1022 extension of C<.tt2>. Most other Catalyst and TT examples use an
1023 extension of C<.tt>. You can use either extension (or no extension at
1024 all) with TTSite and TT, just be sure to use the appropriate extension
1025 for both the file itself I<and> the C<$c-E<gt>stash-E<gt>{template} =
1026 ...> line in your controller. This document will use C<.tt2> for
1027 consistency with the files already created by the C<TTSite> helper.
1030 =head1 RUN THE APPLICATION
1032 First, let's enable an environment variable option that causes
1033 DBIx::Class to dump the SQL statements it's using to access the database
1034 (this option can provide extremely helpful troubleshooting information):
1036 $ export DBIC_TRACE=1
1038 B<NOTE>: You can also use the older
1039 C<export DBIX_CLASS_STORAGE_DBI_DEBUG=1>, that that's a lot more to
1042 This assumes you are using BASH as your shell -- adjust accordingly if
1043 you are using a different shell (for example, under tcsh, use
1044 C<setenv DBIX_CLASS_STORAGE_DBI_DEBUG 1>).
1046 B<NOTE>: You can also set this in your code using
1047 C<$class-E<gt>storage-E<gt>debug(1);>. See
1048 L<DBIx::Class::Manual::Troubleshooting> for details (including options
1049 to log to file instead of displaying to the Catalyst development server
1052 Then run the Catalyst "demo server" script:
1054 $ script/myapp_server.pl
1056 Your development server log output should display something like:
1058 $ script/myapp_server.pl
1059 [debug] Debug messages enabled
1060 [debug] Loaded plugins:
1061 .----------------------------------------------------------------------------.
1062 | Catalyst::Plugin::ConfigLoader 0.06 |
1063 | Catalyst::Plugin::StackTrace 0.04 |
1064 | Catalyst::Plugin::Static::Simple 0.14 |
1065 '----------------------------------------------------------------------------'
1067 [debug] Loaded dispatcher "Catalyst::Dispatcher"
1068 [debug] Loaded engine "Catalyst::Engine::HTTP"
1069 [debug] Found home "/home/me/MyApp"
1070 [debug] Loaded components:
1071 .-----------------------------------------------------------------+----------.
1073 +-----------------------------------------------------------------+----------+
1074 | MyApp::Controller::Books | instance |
1075 | MyApp::Controller::Root | instance |
1076 | MyApp::Model::MyAppDB | instance |
1077 | MyApp::Model::MyAppDB::Author | class |
1078 | MyApp::Model::MyAppDB::Book | class |
1079 | MyApp::Model::MyAppDB::BookAuthor | class |
1080 | MyApp::View::TT | instance |
1081 '-----------------------------------------------------------------+----------'
1083 [debug] Loaded Private actions:
1084 .----------------------+--------------------------------------+--------------.
1085 | Private | Class | Method |
1086 +----------------------+--------------------------------------+--------------+
1087 | /default | MyApp::Controller::Root | default |
1088 | /end | MyApp::Controller::Root | end |
1089 | /books/index | MyApp::Controller::Books | index |
1090 | /books/list | MyApp::Controller::Books | list |
1091 '----------------------+--------------------------------------+--------------'
1093 [debug] Loaded Path actions:
1094 .-------------------------------------+--------------------------------------.
1096 +-------------------------------------+--------------------------------------+
1097 | /books/list | /books/list |
1098 '-------------------------------------+--------------------------------------'
1100 [info] MyApp powered by Catalyst 5.7000
1101 You can connect to your server at http://localhost.localdomain:3000
1103 Some things you should note in the output above:
1109 Catalyst::Model::DBIC::Schema took our C<MyAppDB::Book> and made it
1110 C<MyApp::Model::MyAppDB::Book> (and similar actions were performed on
1111 C<MyAppDB::Author> and C<MyAppDB::BookAuthor>).
1115 The "list" action in our Books controller showed up with a path of
1120 Point your browser to L<http://localhost:3000> and you should still get
1121 the Catalyst welcome page.
1123 Next, to view the book list, change the URL in your browser to
1124 L<http://localhost:3000/books/list>. You should get a list of the five
1125 books loaded by the C<myapp01.sql> script above, with TTSite providing
1126 the formatting for the very simple output we generated in our template.
1127 The count and space-separated list of author last names appear on the
1130 Also notice in the output of the C<script/myapp_server.pl> that DBIC
1131 used the following SQL to retrieve the data:
1133 SELECT me.id, me.title, me.rating FROM books me
1135 Along with a list of the following commands to retrieve the authors for
1136 each book (the lines have been "word wrapped" here to improve
1139 SELECT author.id, author.first_name, author.last_name
1140 FROM book_authors me
1141 JOIN authors author ON ( author.id = me.author_id )
1142 WHERE ( me.book_id = ? ): `1'
1144 You should see 5 such lines of debug output as DBIC fetches the author
1145 information for each book.
1148 =head1 USING THE DEFAULT TEMPLATE NAME
1150 By default, C<Catalyst::View::TT> will look for a template that uses the
1151 same name as your controller action, allowing you to save the step of
1152 manually specifying the template name in each action. For example, this
1153 would allow us to remove (or comment out) the
1154 C<$c-E<gt>stash-E<gt>{template} = 'books/list.tt2';> line of our
1155 C<list> action in the Books controller. Open
1156 C<lib/MyApp/Controller/Books.pm> in your editor and update it to
1157 match the following:
1161 Fetch all book objects and pass to books/list.tt2 in stash to be displayed
1166 # Retrieve the usual perl OO '$self' for this object. $c is the Catalyst
1167 # 'Context' that's used to 'glue together' the various components
1168 # that make up the application
1169 my ($self, $c) = @_;
1171 # Retrieve all of the book records as book model objects and store in the
1172 # stash where they can be accessed by the TT template
1173 $c->stash->{books} = [$c->model('MyAppDB::Book')->all];
1175 # Automatically look for a template of 'books/list.tt2' template
1176 # (if TEMPLATE_EXTENSION is set to '.tt2')
1179 C<Catalyst::View::TT> defaults to looking for a template with no
1180 extension. In our case, we need to override this to look for an
1181 extension of C<.tt2>. Open C<lib/MyApp/View/TT.pm> and add the
1182 C<TEMPLATE_EXTENSION> definition as follows:
1184 __PACKAGE__->config({
1185 CATALYST_VAR => 'Catalyst',
1187 MyApp->path_to( 'root', 'src' ),
1188 MyApp->path_to( 'root', 'lib' )
1190 PRE_PROCESS => 'config/main',
1191 WRAPPER => 'site/wrapper',
1192 ERROR => 'error.tt2',
1194 TEMPLATE_EXTENSION => '.tt2',
1197 You should now be able to restart the development server as per the
1198 previous section and access the L<http://localhost:3000/books/list>
1201 Although this can be a valuable technique to establish a default
1202 template for each of your actions, the remainder of the tutorial
1203 will manually assign the template name to
1204 C<$c-E<gt>stash-E<gt>{template}> in each action in order to make
1205 the logic as conspicuous as possible.
1210 Kennedy Clark, C<hkclark@gmail.com>
1212 Please report any errors, issues or suggestions to the author. The
1213 most recent version of the Catalyst Tutorial can be found at
1214 L<http://dev.catalyst.perl.org/repos/Catalyst/trunk/Catalyst-Runtime/lib/Catalyst/Manual/Tutorial/>.
1216 Copyright 2006, Kennedy Clark, under Creative Commons License
1217 (L<http://creativecommons.org/licenses/by-nc-sa/2.5/>).