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.13 |
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 "/home/me/MyApp"
149 [debug] Loaded Config "/home/me/myapp.yml"
150 [debug] Loaded components:
151 .-----------------------------------------------------------------+----------.
153 +-----------------------------------------------------------------+----------+
154 | MyApp::Controller::Root | instance |
155 '-----------------------------------------------------------------+----------'
157 [debug] Loaded Private actions:
158 .----------------------+--------------------------------------+--------------.
159 | Private | Class | Method |
160 +----------------------+--------------------------------------+--------------+
161 | /default | MyApp::Controller::Root | default |
162 | /end | MyApp::Controller::Root | end |
163 '----------------------+--------------------------------------+--------------'
165 [info] MyApp powered by Catalyst 5.7002
166 You can connect to your server at http://localhost:3000
168 B<NOTE>: Be sure you run the C<script/myapp_server.pl> command from the
169 'base' directory of your application, not inside the C<script> directory
170 itself. It doesn't make a difference at this point, but it will as soon
171 as we get the database going in the next section.
173 Point your web browser to L<http://localhost:3000> (substituting a
174 different hostname or IP address as appropriate) and you should be
175 greeted by the Catalyst welcome screen. Information similar to the
176 following should be appended to the logging output of the development
179 [info] *** Request 1 (0.043/s) [6003] [Fri Jul 7 13:32:53 2006] ***
180 [debug] "GET" request for "/" from "127.0.0.1"
181 [info] Request took 0.067675s (14.777/s)
182 .----------------------------------------------------------------+-----------.
184 +----------------------------------------------------------------+-----------+
185 | /default | 0.002844s |
187 '----------------------------------------------------------------+-----------'
189 Press Ctrl-C to break out of the development server.
192 =head1 CREATE A SQLITE DATABASE
194 In this step, we make a text file with the required SQL commands to
195 create a database table and load some sample data. Open C<myapp01.sql>
196 in your editor and enter:
199 -- Create a very simple database to hold book and author information
202 id INTEGER PRIMARY KEY,
206 -- 'book_authors' is a many-to-many join table between books & authors
207 CREATE TABLE book_authors (
210 PRIMARY KEY (book_id, author_id)
212 CREATE TABLE authors (
213 id INTEGER PRIMARY KEY,
218 --- Load some sample data
220 INSERT INTO books VALUES (1, 'CCSP SNRS Exam Certification Guide', 5);
221 INSERT INTO books VALUES (2, 'TCP/IP Illustrated, Volume 1', 5);
222 INSERT INTO books VALUES (3, 'Internetworking with TCP/IP Vol.1', 4);
223 INSERT INTO books VALUES (4, 'Perl Cookbook', 5);
224 INSERT INTO books VALUES (5, 'Designing with Web Standards', 5);
225 INSERT INTO authors VALUES (1, 'Greg', 'Bastien');
226 INSERT INTO authors VALUES (2, 'Sara', 'Nasseh');
227 INSERT INTO authors VALUES (3, 'Christian', 'Degu');
228 INSERT INTO authors VALUES (4, 'Richard', 'Stevens');
229 INSERT INTO authors VALUES (5, 'Douglas', 'Comer');
230 INSERT INTO authors VALUES (6, 'Tom', 'Christiansen');
231 INSERT INTO authors VALUES (7, 'Nathan', 'Torkington');
232 INSERT INTO authors VALUES (8, 'Jeffrey', 'Zeldman');
233 INSERT INTO book_authors VALUES (1, 1);
234 INSERT INTO book_authors VALUES (1, 2);
235 INSERT INTO book_authors VALUES (1, 3);
236 INSERT INTO book_authors VALUES (2, 4);
237 INSERT INTO book_authors VALUES (3, 5);
238 INSERT INTO book_authors VALUES (4, 6);
239 INSERT INTO book_authors VALUES (4, 7);
240 INSERT INTO book_authors VALUES (5, 8);
242 B<TIP>: See Appendix 1 for tips on removing the leading spaces when
243 cutting and pasting example code from POD-based documents.
245 Then use the following command to build a C<myapp.db> SQLite database:
247 $ sqlite3 myapp.db < myapp01.sql
249 If you need to create the database more than once, you probably want to
250 issue the C<rm myapp.db> command to delete the database before you use
251 the C<sqlite3 myapp.db < myapp01.sql> command.
253 Once the C<myapp.db> database file has been created and initialized, you
254 can use the SQLite command line environment to do a quick dump of the
259 Enter ".help" for instructions
260 sqlite> select * from books;
261 1|CCSP SNRS Exam Certification Guide|5
262 2|TCP/IP Illustrated, Volume 1|5
263 3|Internetworking with TCP/IP Vol.1|4
265 5|Designing with Web Standards|5
271 $ sqlite3 myapp.db "select * from books"
272 1|CCSP SNRS Exam Certification Guide|5
273 2|TCP/IP Illustrated, Volume 1|5
274 3|Internetworking with TCP/IP Vol.1|4
276 5|Designing with Web Standards|5
278 As with most other SQL tools, if you are using the full "interactive"
279 environment you need to terminate your SQL commands with a ";" (it's not
280 required if you do a single SQL statement on the command line). Use
281 ".q" to exit from SQLite from the SQLite interactive mode and return to
282 your OS command prompt.
285 =head1 EDIT THE LIST OF CATALYST PLUGINS
287 One of the greatest benefits of Catalyst is that it has such a large
288 library of plugins available. Plugins are used to seamlessly integrate
289 existing Perl modules into the overall Catalyst framework. In general,
290 they do this by adding additional methods to the C<context> object
291 (generally written as C<$c>) that Catalyst passes to every component
292 throughout the framework.
294 By default, Catalyst enables three plugins/flags:
302 Enables the Catalyst debug output you saw when we started the
303 C<script/myapp_server.pl> development server earlier. You can remove
304 this plugin when you place your application into production.
306 As you may have noticed, C<-Debug> is not a plugin, but a I<flag>.
307 Although most of the items specified on the C<use Catalyst> line of your
308 application class will be plugins, Catalyst supports a limited number of
309 flag options (of these, C<-Debug> is the most common). See the
310 documentation for C<Catalyst.pm> to get details on other flags
311 (currently C<-Engine>, C<-Home>, and C<-Log>).
313 If you prefer, you can use the C<$c-E<gt>debug> method to enable debug
318 L<Catalyst::Plugin::ConfigLoader|Catalyst::Plugin::ConfigLoader>
320 C<ConfigLoader> provides an automatic way to load configurable
321 parameters for your application from a central YAML file (versus having
322 the values hard-coded inside your Perl modules). If you have not been
323 exposed to YAML before, it is a human-readable data serialization format
324 that can be used to read (and write) values to/from text files. We will
325 see how to use this feature of Catalyst during the authentication and
326 authorization sections (Part 4 and Part 5).
330 L<Catalyst::Plugin::Static::Simple|Catalyst::Plugin::Static::Simple>
332 C<Static::Simple> provides an easy method of serving static content such
333 as images and CSS files under the development server.
337 To modify the list of plugins, edit C<lib/MyApp.pm> (this file is
338 generally referred to as your I<application class>) and delete the line
341 use Catalyst qw/-Debug ConfigLoader Static::Simple/;
353 This tells Catalyst to start using one new plugin:
359 L<Catalyst::Plugin::StackTrace|Catalyst::Plugin::StackTrace>
361 Adds a stack trace to the standard Catalyst "debug screen" (this is the
362 screen Catalyst sends to your browser when an error occurs).
364 Note: L<StackTrace|Catalyst::Plugin::StackTrace> output appears in your
365 browser, not in the console window from which you're running your
366 application, which is where logging output usually goes.
370 Note that when specifying plugins on the C<use Catalyst> line, you can
371 omit C<Catalyst::Plugin::> from the name. Additionally, you can spread
372 the plugin names across multiple lines as shown here, or place them all
373 on one (or more) lines as with the default configuration.
375 B<TIP:> You may see examples that include the
376 L<Catalyst::Plugin::DefaultEnd|Catalyst::Plugin::DefaultEnd>
377 plugins. As of Catalyst 5.7000, C<DefaultEnd> has been
378 deprecated in favor of
379 L<Catalyst::Action::RenderView|Catalyst::Action::RenderView>
380 (as the name of the package suggests, C<RenderView> is not
381 a plugin, but an action). The purpose of both is essentially the same:
382 forward processing to the view to be rendered. Applications generated
383 under 5.7000 should automatically use C<RenderView> and "just work"
384 for most applications. For more information on C<RenderView> and
385 the various options for forwarding to your view logic, please refer
386 to the "Using RenderView for the Default View" section under
387 "CATALYST VIEWS" below.
390 =head1 DATABASE ACCESS WITH C<DBIx::Class>
392 Catalyst can be used with virtually any form of persistent datastore
393 available via Perl. For example,
394 L<Catalyst::Model::DBI|Catalyst::Model::DBI> can be used to
395 easily access databases through the traditional Perl C<DBI> interface.
396 However, most Catalyst applications use some form of ORM technology to
397 automatically create and save model objects as they are used. Although
398 Tony Bowden's L<Class::DBI|Class::DBI> has been the traditional
399 Perl ORM engine, Matt Trout's L<DBIx::Class|DBIx::Class> (abbreviated
400 as "DBIC") has rapidly emerged as the Perl-based ORM technology of choice.
401 Most new Catalyst applications rely on DBIC, as will this tutorial.
403 Note: See L<Catalyst::Model::CDBI> for more information on using
404 Catalyst with L<Class::DBI|Class::DBI>.
406 =head2 Create a DBIC Schema File
408 DBIx::Class uses a schema file to load other classes that represent the
409 tables in your database (DBIC refers to these "table objects" as "result
410 sources"; see L<DBIx::Class::ResultSource>). In this case, we want to
411 load the model object for the C<books>, C<book_authors>, and C<authors>
412 tables created in the previous step.
414 Create C<lib/MyAppDB.pm> in your editor and insert:
420 MyAppDB - DBIC Schema Class
424 # Our schema needs to inherit from 'DBIx::Class::Schema'
425 use base qw/DBIx::Class::Schema/;
427 # Need to load the DB Model classes here.
428 # You can use this syntax if you want:
429 # __PACKAGE__->load_classes(qw/Book BookAuthor Author/);
430 # Also, if you simply want to load all of the classes in a directory
431 # of the same name as your schema class (as we do here) you can use:
432 # __PACKAGE__->load_classes(qw//);
433 # But the variation below is more flexible in that it can be used to
434 # load from multiple namespaces.
435 __PACKAGE__->load_classes({
436 MyAppDB => [qw/Book BookAuthor Author/]
441 B<Note:> C<__PACKAGE__> is just a shorthand way of referencing the name
442 of the package where it is used. Therefore, in C<MyAppDB.pm>,
443 C<__PACKAGE__> is equivalent to C<MyAppDB>.
445 B<Note:> As with any Perl package, we need to end the last line with
446 a statement that evaluates to C<true>. This is customarily done with
447 C<1> on a line by itself as shown above.
450 =head2 Create the DBIC "Result Source" Files
452 In this step, we create "table classes" (again, these are called a
453 "result source" classes in DBIC) that act as model objects for the
454 C<books>, C<book_authors>, and C<authors> tables in our database.
456 First, create a directory to hold the class:
460 Then create C<lib/MyAppDB/Book.pm> in your editor and enter:
462 package MyAppDB::Book;
464 use base qw/DBIx::Class/;
466 # Load required DBIC stuff
467 __PACKAGE__->load_components(qw/PK::Auto Core/);
469 __PACKAGE__->table('books');
470 # Set columns in table
471 __PACKAGE__->add_columns(qw/id title rating/);
472 # Set the primary key for the table
473 __PACKAGE__->set_primary_key(qw/id/);
481 # 1) Name of relationship, DBIC will create accessor with this name
482 # 2) Name of the model class referenced by this relationship
483 # 3) Column name in *foreign* table
484 __PACKAGE__->has_many(book_authors => 'MyAppDB::BookAuthor', 'book_id');
488 # 1) Name of relationship, DBIC will create accessor with this name
489 # 2) Name of has_many() relationship this many_to_many() is shortcut for
490 # 3) Name of belongs_to() relationship in model class of has_many() above
491 # You must already have the has_many() defined to use a many_to_many().
492 __PACKAGE__->many_to_many(authors => 'book_authors', 'author');
497 MyAppDB::Book - A model object representing a book.
501 This is an object that represents a row in the 'books' table of your application
502 database. It uses DBIx::Class (aka, DBIC) to do ORM.
504 For Catalyst, this is designed to be used through MyApp::Model::MyAppDB.
505 Offline utilities may wish to use this class directly.
511 This defines both a C<has_many> and a C<many_to_many> relationship. The
512 C<many_to_many> relationship is optional, but it makes it easier to map
513 a book to its collection of authors. Without it, we would have to
514 "walk" though the C<book_authors> table as in
515 C<$book-E<gt>book_authors-E<gt>first-E<gt>author-E<gt>last_name> (we
516 will see examples on how to use DBIC objects in your code soon, but note
517 that because C<$book-E<gt>book_authors> can return multiple authors, we
518 have to use C<first> to display a single author). C<many_to_many> allows
519 us to use the shorter C<$book-E<gt>authors-E<gt>first-E<gt>last_name>.
520 Note that you cannot define a C<many_to_many> relationship without also
521 having the C<has_many> relationship in place.
523 Next, create C<lib/MyAppDB/Author.pm> in your editor and enter:
525 package MyAppDB::Author;
527 use base qw/DBIx::Class/;
529 # Load required DBIC stuff
530 __PACKAGE__->load_components(qw/PK::Auto Core/);
532 __PACKAGE__->table('authors');
533 # Set columns in table
534 __PACKAGE__->add_columns(qw/id first_name last_name/);
535 # Set the primary key for the table
536 __PACKAGE__->set_primary_key(qw/id/);
544 # 1) Name of relationship, DBIC will create accessor with this name
545 # 2) Name of the model class referenced by this relationship
546 # 3) Column name in *foreign* table
547 __PACKAGE__->has_many(book_author => 'MyAppDB::BookAuthor', 'author_id');
551 # 1) Name of relationship, DBIC will create accessor with this name
552 # 2) Name of has_many() relationship this many_to_many() is shortcut for
553 # 3) Name of belongs_to() relationship in model class of has_many() above
554 # You must already have the has_many() defined to use a many_to_many().
555 __PACKAGE__->many_to_many(books => 'book_author', 'book');
560 MyAppDB::Author - A model object representing an author of a book (if a book has
561 multiple authors, each will be represented be separate Author object).
565 This is an object that represents a row in the 'authors' table of your application
566 database. It uses DBIx::Class (aka, DBIC) to do ORM.
568 For Catalyst, this is designed to be used through MyApp::Model::MyAppDB.
569 Offline utilities may wish to use this class directly.
575 Finally, create C<lib/MyAppDB/BookAuthor.pm> in your editor and enter:
577 package MyAppDB::BookAuthor;
579 use base qw/DBIx::Class/;
581 # Load required DBIC stuff
582 __PACKAGE__->load_components(qw/PK::Auto Core/);
584 __PACKAGE__->table('book_authors');
585 # Set columns in table
586 __PACKAGE__->add_columns(qw/book_id author_id/);
587 # Set the primary key for the table
588 __PACKAGE__->set_primary_key(qw/book_id author_id/);
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(book => 'MyAppDB::Book', 'book_id');
603 # 1) Name of relationship, DBIC will create accessor with this name
604 # 2) Name of the model class referenced by this relationship
605 # 3) Column name in *this* table
606 __PACKAGE__->belongs_to(author => 'MyAppDB::Author', 'author_id');
611 MyAppDB::BookAuthor - A model object representing the JOIN between an author and
616 This is an object that represents a row in the 'book_authors' table of your
617 application database. It uses DBIx::Class (aka, DBIC) to do ORM.
619 You probably won't need to use this class directly -- it will be automatically
620 used by DBIC where joins are needed.
622 For Catalyst, this is designed to be used through MyApp::Model::MyAppDB.
623 Offline utilities may wish to use this class directly.
629 B<Note:> This sample application uses a plural form for the database
630 tables (e.g., C<books> and C<authors>) and a singular form for the model
631 objects (e.g., C<Book> and C<Author>); however, Catalyst places no
632 restrictions on the naming conventions you wish to use.
634 =head2 Use C<Catalyst::Model::DBIC::Schema> To Load The Model Class
636 When L<Catalyst::Model::DBIC::Schema|Catalyst::Model::DBIC::Schema> is
637 in use, Catalyst essentially reads an existing copy of your database
638 model and creates a new set of objects under C<MyApp::Model> for use
642 L<Catalyst::Model::DBIC::Schema|Catalyst::Model::DBIC::Schema> you
643 essentially end up with two sets of model classes (only one of which
644 you write... the other set is created automatically in memory when
645 your Catalyst application initializes). For this tutorial application,
646 the important points to remember are: you write the I<result source>
647 files in C<MyAppDB>, but I<within Catalyst> you use the I<automatically
648 created model classes> in C<MyApp::Model>.
651 L<Catalyst::Helper::Model::DBIC::Schema|Catalyst::Helper::Model::DBIC::Schema>
652 helper script to create the model class that loads up the model we
653 created in the previous step:
655 $ script/myapp_create.pl model MyAppDB DBIC::Schema MyAppDB dbi:SQLite:myapp.db '' '' '{ AutoCommit => 1 }'
656 exists "/root/dev/MyApp/script/../lib/MyApp/Model"
657 exists "/root/dev/MyApp/script/../t"
658 created "/root/dev/MyApp/script/../lib/MyApp/Model/MyAppDB.pm"
659 created "/root/dev/MyApp/script/../t/model_MyAppDB.t"
662 Where the first C<MyAppDB> is the name of the class to be created by the
663 helper in C<lib/MyApp/Model> and the second C<MyAppDB> is the name of
664 existing schema file we created (in C<lib/MyAppDB.pm>). You can see
665 that the helper creates a model file under C<lib/MyApp/Model> (Catalyst
666 has a separate directory under C<lib/MyApp> for each of the three parts
667 of MVC: C<Model>, C<View>, and C<Controller> [although older Catalyst
668 applications often use the directories C<M>, C<V>, and C<C>]).
671 =head1 CREATE A CATALYST CONTROLLER
673 Controllers are where you write methods that interact with user
674 input--typically, controller methods respond to C<GET> and C<POST>
675 messages from the user's web browser.
677 Use the Catalyst C<create> script to add a controller for book-related
680 $ script/myapp_create.pl controller Books
681 exists "/root/dev/MyApp/script/../lib/MyApp/Controller"
682 exists "/root/dev/MyApp/script/../t"
683 created "/root/dev/MyApp/script/../lib/MyApp/Controller/Books.pm"
684 created "/root/dev/MyApp/script/../t/controller_Books.t"
686 Then edit C<lib/MyApp/Controller/Books.pm> and add the following method
691 Fetch all book objects and pass to books/list.tt2 in stash to be displayed
696 # Retrieve the usual perl OO '$self' for this object. $c is the Catalyst
697 # 'Context' that's used to 'glue together' the various components
698 # that make up the application
701 # Retrieve all of the book records as book model objects and store in the
702 # stash where they can be accessed by the TT template
703 $c->stash->{books} = [$c->model('MyAppDB::Book')->all];
705 # Set the TT template to use. You will almost always want to do this
706 # in your action methods (action methods respond to user input in
708 $c->stash->{template} = 'books/list.tt2';
711 B<Note:> Programmers experienced with object-oriented Perl should
712 recognize C<$self> as a reference to the object where this method was
713 called. On the other hand, C<$c> will be new to many Perl programmers
714 who have not used Catalyst before (it's sometimes written as
715 C<$context>). The Context object is automatically passed to all
716 Catalyst components. It is used to pass information between components
717 and provide access to Catalyst and plugin functionality.
719 B<TIP>: You may see the C<$c-E<gt>model('MyAppDB::Book')> used above
720 written as C<$c-E<gt>model('MyAppDB')-E<gt>resultset('Book)>. The two
723 B<Note:> Catalyst actions are regular Perl methods, but they make use of
724 Nicholas Clark's C<attributes> module (that's the C<: Local> next to the
725 C<sub list> in the code above) to provide additional information to the
726 Catalyst dispatcher logic.
729 =head1 CATALYST VIEWS
731 Views are where you render output, typically for display in the user's
732 web browser, but also possibly using other display output-generation
733 systems. As with virtually every aspect of Catalyst, options abound
734 when it comes to the specific view technology you adopt inside your
735 application. However, most Catalyst applications use the Template
736 Toolkit, known as TT (for more information on TT, see
737 L<http://www.template-toolkit.org>). Other popular view technologies
738 include Mason (L<http://www.masonhq.com> and
739 L<http://www.masonbook.com>) and L<HTML::Template|HTML::Template>
740 (L<http://html-template.sourceforge.net>).
742 =head2 Create a Catalyst View Using C<TTSite>
744 When using TT for the Catalyst view, there are two main helper scripts:
750 L<Catalyst::Helper::View::TT|Catalyst::Helper::View::TT>
754 L<Catalyst::Helper::View::TTSite|Catalyst::Helper::View::TTSite>
758 Both are similar, but C<TT> merely creates the C<lib/MyApp/View/TT.pm>
759 file and leaves the creation of any hierarchical template organization
760 entirely up to you. (It also creates a C<t/view_TT.t> file for testing;
761 test cases will be discussed in Part 7). The C<TTSite> helper creates a
762 modular and hierarchical view layout with separate Template Toolkit (TT)
763 files for common header and footer information, configuration values, a
764 CSS stylesheet, and more.
766 While TTSite is useful to bootstrap a project, we recommend that
767 unless you know what your're doing or want to pretty much use the
768 supplied templates as is, that you use the plain Template Toolkit view
769 when starting a project from scratch. This is because TTSite can be
770 tricky to customize. Additionally TT contains constructs that you
771 need to learn yourself if you're going to be a serious user of TT.
772 Our experience suggests that you're better off learning these from
773 scratch. We use TTSite here precisely because it is useful for
774 bootstrap/prototype purposes.
776 Enter the following command to enable the C<TTSite> style of view
777 rendering for this tutorial:
779 $ script/myapp_create.pl view TT TTSite
780 exists "/root/dev/MyApp/script/../lib/MyApp/View"
781 exists "/root/dev/MyApp/script/../t"
782 created "/root/dev/MyApp/script/../lib/MyApp/View/TT.pm"
783 created "/root/dev/MyApp/script/../root/lib"
785 created "/root/dev/MyApp/script/../root/src/ttsite.css"
787 This puts a number of files in the C<root/lib> and C<root/src>
788 directories that can be used to customize the look and feel of your
789 application. Also take a look at C<lib/MyApp/View/TT.pm> for config
790 values set by the C<TTSite> helper.
792 B<TIP>: Note that TTSite does one thing that could confuse people who
793 are used to the normal C<TT> Catalyst view: it redefines the Catalyst
794 context object in templates from its usual C<c> to C<Catalyst>. When
795 looking at other Catalyst examples, remember that they almost always use
796 C<c>. Note that Catalyst and TT I<do not complain> when you use the
797 wrong name to access the context object...TT simply outputs blanks for
798 that bogus logic (see next tip to change this behavior with TT C<DEBUG>
799 options). Finally, be aware that this change in name I<only>
800 applies to how the context object is accessed inside your TT templates;
801 your controllers will continue to use C<$c> (or whatever name you use
802 when fetching the reference from C<@_> inside your methods). (You can
803 change back to the "default" behavior be removing the C<CATALYST_VAR>
804 line from C<lib/MyApp/View/TT.pm>, but you will also have to edit
805 C<root/lib/config/main> and C<root/lib/config/url>. If you do this, be
806 careful not to have a collision between your own C<c> variable and the
807 Catalyst C<c> variable.)
809 B<TIP>: When troubleshooting TT it can be helpful to enable variable
810 C<DEBUG> options. You can do this in a Catalyst environment by adding
811 a C<DEBUG> line to the C<__PACKAGE__->config> declaration in
812 C<lib/MyApp/View/TT.pm>:
814 __PACKAGE__->config({
815 CATALYST_VAR => 'Catalyst',
821 There are a variety of options you can use, such as 'undef', 'all',
822 'service', 'context', 'parser', 'provider', and 'service'. See
823 L<Template::Constants> for more information (remove the C<DEBUG_>
824 portion of the name shown in the TT docs and convert to lower case
825 for use inside Catalyst).
827 B<NOTE:> Please be sure to disable TT debug options before
828 continuing the tutorial (especially the 'undef' option -- leaving
829 this enabled will conflict with several of the conventions used
830 by this tutorial and TTSite to leave some variables undefined
834 =head2 Using C<RenderView> for the Default View
836 Once your controller logic has processed the request from a user, it
837 forwards processing to your view in order to generate the appropriate
838 response output. Catalyst v5.7000 ships with a new mechanism,
839 L<Catalyst::Action::RenderView|Catalyst::Action::RenderView>, that
840 automatically performs this operation. If you look in
841 C<lib/MyApp/Controller/Root.pm>, you should see the empty
842 definition for the C<sub end> method:
844 sub end : ActionClass('RenderView') {}
846 The following bullet points provide a quick overview of the
847 C<RenderView> process:
853 C<Root.pm> is designed to hold application-wide logic.
857 At the end of a given user request, Catalyst will call the most specific
858 C<end> method that's appropriate. For example, if the controller for a
859 request has an C<end> method defined, it will be called. However, if
860 the controller does not define a controller-specific C<end> method, the
861 "global" C<end> method in C<Root.pm> will be called.
865 Because the definition includes an C<ActionClass> attribute, the
866 L<Catalyst::Action::RenderView|Catalyst::Action::RenderView> logic
867 will be executed B<after> any code inside the definition of C<sub end>
868 is run. See L<Catalyst::Manual::Actions|Catalyst::Manual::Actions>
869 for more information on C<ActionClass>.
873 Because C<sub end> is empty, this effectively just runs the default
874 logic in C<RenderView>. However, you can easily extend the
875 C<RenderView> logic by adding your own code inside the empty method body
876 (C<{}>) created by the Catalyst Helpers when we first ran the
877 C<catalyst.pl> to initialize our application. See
878 L<Catalyst::Action::RenderView|Catalyst::Action::RenderView> for more
879 detailed information on how to extended C<RenderView> in C<sub end>.
884 =head3 The History Leading Up To C<RenderView>
886 Although C<RenderView> strikes a nice balance between default
887 behavior and easy extensibility, it is a new feature that won't
888 appear in most existing Catalyst examples. This section provides
889 some brief background on the evolution of default view rendering
890 logic with an eye to how they can be migrated to C<RenderView>:
896 Private C<end> Action in Application Class
898 Older Catalyst-related documents often suggest that you add a "private
899 end action" to your application class (C<MyApp.pm>) or Root.pm
900 (C<MyApp/Controller/Root.pm>). These examples should be easily
901 converted to L<RenderView|Catalyst::Action::RenderView> by simply adding
902 the attribute C<:ActionClass('RenderView')> to the C<sub end>
903 definition. If end sub is defined in your application class
904 (C<MyApp.pm>), you should also migrate it to
905 C<MyApp/Controller/Root.pm>.
909 L<Catalyst::Plugin::DefaultEnd|Catalyst::Plugin::DefaultEnd>
911 C<DefaultEnd> represented the "next step" in passing processing from
912 your controller to your view. It has the advantage of only requiring
913 that C<DefaultEnd> be added to the list of plugins in C<lib/MyApp.pm>.
914 It also allowed you to add "dump_info=1" (precede with "?" or "&"
915 depending on where it is in the URL) to I<force> the debug screen at the
916 end of the Catalyst request processing cycle. However, it was more
917 difficult to extend than the C<RenderView> mechanism, and is now
922 L<Catalyst::Action::RenderView|Catalyst::Action::RenderView>
924 As discussed above, the current recommended approach to handling your
926 L<Catalyst::Action::RenderView|Catalyst::Action::RenderView>. Although
927 similar in first appearance to the "private end action" approach, it
928 utilizes Catalyst's "ActionClass" mechanism to provide both automatic
929 default behavior (you don't have to include a plugin as with
930 C<DefaultEnd>) and easy extensibility. As with C<DefaultEnd>, it allows
931 you to add "dump_info=1" (precede with "?" or "&" depending on where it
932 is in the URL) to I<force> the debug screen at the end of the Catalyst
933 request processing cycle.
937 It is recommended that all Catalyst applications use or migrate to
938 the C<RenderView> approach.
941 =head2 Globally Customize Every View
943 When using TTSite, files in the subdirectories of C<root/lib> can be
944 used to make changes that will appear in every view. For example, to
945 display optional status and error messages in every view, edit
946 C<root/lib/site/layout>, updating it to match the following (the two HTML
947 C<span> elements are new):
949 <div id="header">[% PROCESS site/header %]</div>
952 <span class="message">[% status_msg %]</span>
953 <span class="error">[% error_msg %]</span>
957 <div id="footer">[% PROCESS site/footer %]</div>
959 If we set either message in the Catalyst stash (e.g.,
960 C<$c-E<gt>stash-E<gt>{status_msg} = 'Request was successful!'>) it will
961 be displayed whenever any view used by that request is rendered. The
962 C<message> and C<error> CSS styles are automatically defined in
963 C<root/src/ttsite.css> and can be customized to suit your needs.
965 B<Note:> The Catalyst stash only lasts for a single HTTP request. If
966 you need to retain information across requests you can use
967 L<Catalyst::Plugin::Session|Catalyst::Plugin::Session> (we will use
968 Catalyst sessions in the Authentication part of the tutorial).
971 =head2 Create a TT Template Page
973 To add a new page of content to the TTSite view hierarchy, just create a
974 new C<.tt2> file in C<root/src>. Only include HTML markup that goes
975 inside the HTML <body> and </body> tags, TTSite will use the contents of
976 C<root/lib/site> to add the top and bottom.
978 First create a directory for book-related TT templates:
980 $ mkdir root/src/books
982 Then create C<root/src/books/list.tt2> in your editor and enter:
984 [% # This is a TT comment. The '-' at the end "chomps" the newline. You won't -%]
985 [% # see this "chomping" in your browser because HTML ignores blank lines, but -%]
986 [% # it WILL eliminate a blank line if you view the HTML source. It's purely -%]
987 [%- # optional, but both the beginning and the ending TT tags support chomping. -%]
989 [% # Provide a title to root/lib/site/header -%]
990 [% META title = 'Book List' -%]
993 <tr><th>Title</th><th>Rating</th><th>Author(s)</th></tr>
994 [% # Display each book in a table row %]
995 [% FOREACH book IN books -%]
997 <td>[% book.title %]</td>
998 <td>[% book.rating %]</td>
1000 [% # First initialize a TT variable to hold a list. Then use a TT FOREACH -%]
1001 [% # loop in 'side effect notation' to load just the last names of the -%]
1002 [% # authors into the list. Note that the 'push' TT vmethod does not -%]
1003 [% # a value, so nothing will be printed here. But, if you have something -%]
1004 [% # in TT that does return a method and you don't want it printed, you -%]
1005 [% # can: 1) assign it to a bogus value, or 2) use the CALL keyword to -%]
1006 [% # call it and discard the return value. -%]
1007 [% tt_authors = [ ];
1008 tt_authors.push(author.last_name) FOREACH author = book.authors %]
1009 [% # Now use a TT 'virtual method' to display the author count in parens -%]
1010 ([% tt_authors.size %])
1011 [% # Use another TT vmethod to join & print the names & comma separators -%]
1012 [% tt_authors.join(', ') %]
1018 As indicated by the inline comments above, the C<META title> line uses
1019 TT's META feature to provide a title to C<root/lib/site/header>.
1020 Meanwhile, the outer C<FOREACH> loop iterates through each C<book> model
1021 object and prints the C<title> and C<rating> fields. An inner
1022 C<FOREACH> loop prints the last name of each author in a comma-separated
1023 list within a single table cell.
1025 If you are new to TT, the C<[%> and C<%]> tags are used to delimit TT
1026 code. TT supports a wide variety of directives for "calling" other
1027 files, looping, conditional logic, etc. In general, TT simplifies the
1028 usual range of Perl operators down to the single dot (C<.>) operator.
1029 This applies to operations as diverse as method calls, hash lookups, and
1030 list index values (see
1031 L<http://www.template-toolkit.org/docs/default/Manual/Variables.html>
1032 for details and examples). In addition to the usual C<Template> module
1033 Pod documentation, you can access the TT manual at
1034 L<http://www.template-toolkit.org/docs/default/>.
1036 B<NOTE>: The C<TTSite> helper creates several TT files using an
1037 extension of C<.tt2>. Most other Catalyst and TT examples use an
1038 extension of C<.tt>. You can use either extension (or no extension at
1039 all) with TTSite and TT, just be sure to use the appropriate extension
1040 for both the file itself I<and> the C<$c-E<gt>stash-E<gt>{template} =
1041 ...> line in your controller. This document will use C<.tt2> for
1042 consistency with the files already created by the C<TTSite> helper.
1045 =head1 RUN THE APPLICATION
1047 First, let's enable an environment variable option that causes
1048 DBIx::Class to dump the SQL statements it's using to access the database
1049 (this option can provide extremely helpful troubleshooting information):
1051 $ export DBIC_TRACE=1
1053 B<NOTE>: You can also use the older
1054 C<export DBIX_CLASS_STORAGE_DBI_DEBUG=1>, but that's a lot more to
1057 This assumes you are using BASH as your shell -- adjust accordingly if
1058 you are using a different shell (for example, under tcsh, use
1059 C<setenv DBIX_CLASS_STORAGE_DBI_DEBUG 1>).
1061 B<NOTE>: You can also set this in your code using
1062 C<$class-E<gt>storage-E<gt>debug(1);>. See
1063 L<DBIx::Class::Manual::Troubleshooting> for details (including options
1064 to log to file instead of displaying to the Catalyst development server
1067 Then run the Catalyst "demo server" script:
1069 $ script/myapp_server.pl
1071 Your development server log output should display something like:
1073 $ script/myapp_server.pl
1074 [debug] Debug messages enabled
1075 [debug] Loaded plugins:
1076 .----------------------------------------------------------------------------.
1077 | Catalyst::Plugin::ConfigLoader 0.13 |
1078 | Catalyst::Plugin::StackTrace 0.06 |
1079 | Catalyst::Plugin::Static::Simple 0.14 |
1080 '----------------------------------------------------------------------------'
1082 [debug] Loaded dispatcher "Catalyst::Dispatcher"
1083 [debug] Loaded engine "Catalyst::Engine::HTTP"
1084 [debug] Found home "/home/me/MyApp"
1085 [debug] Loaded Config "/home/me/myapp.yml"
1086 [debug] Loaded components:
1087 .-----------------------------------------------------------------+----------.
1089 +-----------------------------------------------------------------+----------+
1090 | MyApp::Controller::Books | instance |
1091 | MyApp::Controller::Root | instance |
1092 | MyApp::Model::MyAppDB | instance |
1093 | MyApp::Model::MyAppDB::Author | class |
1094 | MyApp::Model::MyAppDB::Book | class |
1095 | MyApp::Model::MyAppDB::BookAuthor | class |
1096 | MyApp::View::TT | instance |
1097 '-----------------------------------------------------------------+----------'
1099 [debug] Loaded Private actions:
1100 .----------------------+--------------------------------------+--------------.
1101 | Private | Class | Method |
1102 +----------------------+--------------------------------------+--------------+
1103 | /default | MyApp::Controller::Root | default |
1104 | /end | MyApp::Controller::Root | end |
1105 | /books/index | MyApp::Controller::Books | index |
1106 | /books/list | MyApp::Controller::Books | list |
1107 '----------------------+--------------------------------------+--------------'
1109 [debug] Loaded Path actions:
1110 .-------------------------------------+--------------------------------------.
1112 +-------------------------------------+--------------------------------------+
1113 | /books/list | /books/list |
1114 '-------------------------------------+--------------------------------------'
1116 [info] MyApp powered by Catalyst 5.7002
1117 You can connect to your server at http://localhost:3000
1119 Some things you should note in the output above:
1125 Catalyst::Model::DBIC::Schema took our C<MyAppDB::Book> and made it
1126 C<MyApp::Model::MyAppDB::Book> (and similar actions were performed on
1127 C<MyAppDB::Author> and C<MyAppDB::BookAuthor>).
1131 The "list" action in our Books controller showed up with a path of
1136 Point your browser to L<http://localhost:3000> and you should still get
1137 the Catalyst welcome page.
1139 Next, to view the book list, change the URL in your browser to
1140 L<http://localhost:3000/books/list>. You should get a list of the five
1141 books loaded by the C<myapp01.sql> script above, with TTSite providing
1142 the formatting for the very simple output we generated in our template.
1143 The count and space-separated list of author last names appear on the
1146 Also notice in the output of the C<script/myapp_server.pl> that DBIC
1147 used the following SQL to retrieve the data:
1149 SELECT me.id, me.title, me.rating FROM books me
1151 Along with a list of the following commands to retrieve the authors for
1152 each book (the lines have been "word wrapped" here to improve
1155 SELECT author.id, author.first_name, author.last_name
1156 FROM book_authors me
1157 JOIN authors author ON ( author.id = me.author_id )
1158 WHERE ( me.book_id = ? ): `1'
1160 You should see 5 such lines of debug output as DBIC fetches the author
1161 information for each book.
1164 =head1 USING THE DEFAULT TEMPLATE NAME
1166 By default, C<Catalyst::View::TT> will look for a template that uses the
1167 same name as your controller action, allowing you to save the step of
1168 manually specifying the template name in each action. For example, this
1169 would allow us to remove the
1170 C<$c-E<gt>stash-E<gt>{template} = 'books/list.tt2';> line of our
1171 C<list> action in the Books controller. Open
1172 C<lib/MyApp/Controller/Books.pm> in your editor and comment out this line
1173 to match the following (only the C<$c-E<gt>stash-E<gt>{template}> line
1178 Fetch all book objects and pass to books/list.tt2 in stash to be displayed
1183 # Retrieve the usual perl OO '$self' for this object. $c is the Catalyst
1184 # 'Context' that's used to 'glue together' the various components
1185 # that make up the application
1186 my ($self, $c) = @_;
1188 # Retrieve all of the book records as book model objects and store in the
1189 # stash where they can be accessed by the TT template
1190 $c->stash->{books} = [$c->model('MyAppDB::Book')->all];
1192 # Set the TT template to use. You will almost always want to do this
1193 # in your action methods (actions methods respond to user input in
1194 # your controllers).
1195 #$c->stash->{template} = 'books/list.tt2';
1198 C<Catalyst::View::TT> defaults to looking for a template with no
1199 extension. In our case, we need to override this to look for an
1200 extension of C<.tt2>. Open C<lib/MyApp/View/TT.pm> and add the
1201 C<TEMPLATE_EXTENSION> definition as follows:
1203 __PACKAGE__->config({
1204 CATALYST_VAR => 'Catalyst',
1206 MyApp->path_to( 'root', 'src' ),
1207 MyApp->path_to( 'root', 'lib' )
1209 PRE_PROCESS => 'config/main',
1210 WRAPPER => 'site/wrapper',
1211 ERROR => 'error.tt2',
1213 TEMPLATE_EXTENSION => '.tt2',
1216 You should now be able to restart the development server as per the
1217 previous section and access the L<http://localhost:3000/books/list>
1220 B<NOTE:> Please note that if you use the default template technique,
1221 you will B<not> be able to use either the C<$c-E<gt>forward> or
1222 the C<$c-E<gt>detach> mechanisms (these are discussed in Part 2 and
1223 Part 8 of the Tutorial).
1226 =head1 RETURN TO A MANUALLY-SPECIFIED TEMPLATE
1228 In order to be able to use C<$c-E<gt>forward> and C<$c-E<gt>detach>
1229 later in the tutorial, you should remove the comment from the
1230 statement in C<sub list>:
1232 $c->stash->{template} = 'books/list.tt2';
1234 Then delete the C<TEMPLATE_EXTENSION> line in
1235 C<lib/MyApp/View/TT.pm>.
1237 You should then be able to restart the development server and
1238 access L<http://localhost:3000/books/list> in the same manner as
1239 with earlier sections.
1244 Kennedy Clark, C<hkclark@gmail.com>
1246 Please report any errors, issues or suggestions to the author. The
1247 most recent version of the Catalyst Tutorial can be found at
1248 L<http://dev.catalyst.perl.org/repos/Catalyst/trunk/Catalyst-Manual/lib/Catalyst/Manual/Tutorial/>.
1250 Copyright 2006, Kennedy Clark, under Creative Commons License
1251 (L<http://creativecommons.org/licenses/by-nc-sa/2.5/>).