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