3 Catalyst::Manual::Tutorial::MoreCatalystBasics - Catalyst Tutorial - Part 3: More Catalyst Application Development Basics
8 This is B<Part 3 of 10> for the Catalyst tutorial.
10 L<Tutorial Overview|Catalyst::Manual::Tutorial>
16 L<Introduction|Catalyst::Manual::Tutorial::Intro>
20 L<Catalyst Basics|Catalyst::Manual::Tutorial::CatalystBasics>
24 B<More Catalyst Basics>
28 L<Basic CRUD|Catalyst::Manual::Tutorial::BasicCRUD>
32 L<Authentication|Catalyst::Manual::Tutorial::Authentication>
36 L<Authorization|Catalyst::Manual::Tutorial::Authorization>
40 L<Debugging|Catalyst::Manual::Tutorial::Debugging>
44 L<Testing|Catalyst::Manual::Tutorial::Testing>
48 L<Advanced CRUD|Catalyst::Manual::Tutorial::AdvancedCRUD>
52 L<Appendices|Catalyst::Manual::Tutorial::Appendices>
59 This part of the tutorial builds on the work done in Part 2 to explore
60 some features that are more typical of "real world" web applications.
61 From this part of the tutorial onward, we will be building a simple
62 book database application. Although the application will be too
63 limited to be of use to anyone, it should provide a basic environment
64 where we can explore a variety of features used in virtually all web
67 You can checkout the source code for this example from the catalyst
68 subversion repository as per the instructions in
69 L<Catalyst::Manual::Tutorial::Intro>
72 =head1 CREATE A NEW APPLICATION
74 The remainder of the tutorial will build an application call C<MyApp>.
75 Use the Catalyst C<catalyst.pl> script to initialize the framework for
76 an application called C<MyApp> (make sure you aren't still inside the
77 directory of the C<Hello> application from the previous part of the
82 created "MyApp/script"
86 created "MyApp/script/myapp_create.pl"
89 This creates a similar skeletal structure to what we saw in Part 2 of
90 the tutorial, except with C<MyApp> and C<myapp> substituted for
91 C<Hello> and C<hello>.
94 =head1 EDIT THE LIST OF CATALYST PLUGINS
96 One of the greatest benefits of Catalyst is that it has such a large
97 library of plugins available. Plugins are used to seamlessly integrate
98 existing Perl modules into the overall Catalyst framework. In general,
99 they do this by adding additional methods to the C<context> object
100 (generally written as C<$c>) that Catalyst passes to every component
101 throughout the framework.
103 By default, Catalyst enables three plugins/flags:
111 Enables the Catalyst debug output you saw when we started the
112 C<script/myapp_server.pl> development server earlier. You can remove
113 this item when you place your application into production.
115 As you may have noticed, C<-Debug> is not a plugin, but a I<flag>.
116 Although most of the items specified on the C<use Catalyst> line of your
117 application class will be plugins, Catalyst supports a limited number of
118 flag options (of these, C<-Debug> is the most common). See the
119 documentation for C<Catalyst.pm> to get details on other flags
120 (currently C<-Engine>, C<-Home>, and C<-Log>).
122 If you prefer, you can use the C<$c-E<gt>debug> method to enable debug
125 B<TIP>: Depending on your needs, it can be helpful to permanently
126 remove C<-Debug> from C<lib/MyApp.pm> and then use the C<-d> option
127 to C<script/myapp_server.pl> to re-enable it just for the development
128 server. We will not be using that approach in the tutorial, but feel
129 free to make use of it in your own projects.
133 L<Catalyst::Plugin::ConfigLoader|Catalyst::Plugin::ConfigLoader>
135 C<ConfigLoader> provides an automatic way to load configurable
136 parameters for your application from a central
137 L<Config::General|Config::General> file (versus having the values
138 hard-coded inside your Perl modules). Config::General uses syntax
139 very similar to Apache configuration files. We will see how to use
140 this feature of Catalyst during the authentication and authorization
141 sections (Part 5 and Part 6).
143 B<IMPORTANT NOTE:> If you are following along in Ubuntu 8.04 or
144 otherwise using a version of L<Catalyst::Devel|Catalyst::Devel> prior
145 to version 1.06, you need to be aware that Catalyst changed from a
146 default format of YAML to the more straightforward C<Config::General>
147 format. Because Catalyst has long supported both formats, this
148 tutorial will simply use a configuration file called C<myapp.conf>
149 instead of C<myapp.yml> and Catalyst will automatically use the new
150 format. Just be aware that earlier versions of Catalyst will still
151 create the C<myapp.yml> file and that you will need to B<remove
152 C<myapp.yml>> and create a new C<myapp.conf> file by hand, but
153 otherwise this transition is very painless. The default contents of
154 C<myapp.conf> should only consist of one line: C<name MyApp>. Also be
155 aware that you can continue to use any format supported by
156 L<Catalyst::Plugin::ConfigLoader|Catalyst::Plugin::ConfigLoader> and
157 L<Config::Any|Config::Any>, including YAML -- Catalyst will
158 automatically look for any of the supported configuration file
161 B<TIP>: This script can be useful for converting between configuration
164 perl -Ilib -e 'use MyApp; use Config::General;
165 Config::General->new->save_file("myapp.conf", MyApp->config);'
167 B<NOTE:> The default C<myapp.conf> should look like:
173 L<Catalyst::Plugin::Static::Simple|Catalyst::Plugin::Static::Simple>
175 C<Static::Simple> provides an easy method of serving static content such
176 as images and CSS files under the development server.
180 To modify the list of plugins, edit C<lib/MyApp.pm> (this file is
181 generally referred to as your I<application class>) and delete the line
184 use Catalyst qw/-Debug ConfigLoader Static::Simple/;
196 This tells Catalyst to start using one new plugin:
202 L<Catalyst::Plugin::StackTrace|Catalyst::Plugin::StackTrace>
204 Adds a stack trace to the standard Catalyst "debug screen" (this is the
205 screen Catalyst sends to your browser when an error occurs).
207 Note: L<StackTrace|Catalyst::Plugin::StackTrace> output appears in your
208 browser, not in the console window from which you're running your
209 application, which is where logging output usually goes.
211 B<Note:> You will want to disable
212 L<StackTrace|Catalyst::Plugin::StackTrace> before you put your
213 application into production, but it can be helpful during development.
217 Note that when specifying plugins on the C<use Catalyst> line, you can
218 omit C<Catalyst::Plugin::> from the name. Additionally, you can spread
219 the plugin names across multiple lines as shown here, or place them all
220 on one (or more) lines as with the default configuration.
223 =head1 CREATE A CATALYST CONTROLLER
225 As discussed earlier, controllers are where you write methods that
226 interact with user input. Typically, controller methods respond to
227 C<GET> and C<POST> messages from the user's web browser.
229 Use the Catalyst C<create> script to add a controller for book-related
232 $ script/myapp_create.pl controller Books
233 exists "/home/me/MyApp/script/../lib/MyApp/Controller"
234 exists "/home/me/MyApp/script/../t"
235 created "/home/me/MyApp/script/../lib/MyApp/Controller/Books.pm"
236 created "/home/me/MyApp/script/../t/controller_Books.t"
238 Then edit C<lib/MyApp/Controller/Books.pm> and add the following method
243 Fetch all book objects and pass to books/list.tt2 in stash to be displayed
248 # Retrieve the usual Perl OO '$self' for this object. $c is the Catalyst
249 # 'Context' that's used to 'glue together' the various components
250 # that make up the application
253 # Retrieve all of the book records as book model objects and store in the
254 # stash where they can be accessed by the TT template
255 $c->stash->{books} = [$c->model('DB::Books')->all];
257 # Set the TT template to use. You will almost always want to do this
258 # in your action methods (action methods respond to user input in
260 $c->stash->{template} = 'books/list.tt2';
263 B<Note:> This won't actually work yet since you haven't set up your
264 model yet. We will be covering the model soon.
266 B<Note:> Programmers experienced with object-oriented Perl should
267 recognize C<$self> as a reference to the object where this method was
268 called. On the other hand, C<$c> will be new to many Perl programmers
269 who have not used Catalyst before (it's sometimes written as
270 C<$context>). The Context object is automatically passed to all
271 Catalyst components. It is used to pass information between
272 components and provide access to Catalyst and plugin functionality.
274 B<TIP>: You may see the C<$c-E<gt>model('DB::Book')> used above
275 written as C<$c-E<gt>model('DB')-E<gt>resultset('Book')>. The two
278 B<Note:> Catalyst actions are regular Perl methods, but they make use
279 of Nicholas Clark's C<attributes> module (that's the C<: Local> next
280 to the C<sub list> in the code above) to provide additional
281 information to the Catalyst dispatcher logic. Many newer Catalyst
282 applications are switching to the use of "Literal" C<:Path> actions
283 and C<Args> attribute in lieu of C<: Local> and C<: Private>. For
284 example, C<sub any_method :Path :Args(0)> can be used instead of
285 C<sub index :Private> (because no path was supplied to C<Path> it
286 matches the "empty" URL in the namespace of that module... the same
287 thing C<sub index> would do) or C<sub list :Path('list') :Args(0)>
288 could be used instead of the C<sub list : Local> above (the C<list>
289 argument to C<Path> would make it match on the URL C<list> under
290 C<books>, the namespace of the current module). See "Action Types" in
291 L<Catalyst::Manual::Intro|Catalyst::Manual::Intro> as well as Part 5
292 of this tutorial (Authentication) for additional information. Another
293 popular but more advanced feature is C<Chained> actions that allow a
294 single URL to "chain together" multiple action method calls, each with
295 an appropriate number of arguments (see
296 L<Catalyst::DispatchType::Chained|Catalyst::DispatchType::Chained>
300 =head1 CATALYST VIEWS
302 As mentioned in Part 2 of the tutorial, views are where you render
303 output, typically for display in the user's web browser, but also
304 possibly using other display output- generation systems. As with
305 virtually every aspect of Catalyst, options abound when it comes to
306 the specific view technology you adopt inside your application.
307 However, most Catalyst applications use the Template Toolkit, known as
308 TT (for more information on TT, see
309 L<http://www.template-toolkit.org>). Other popular view technologies
310 include Mason (L<http://www.masonhq.com> and
311 L<http://www.masonbook.com>) and L<HTML::Template>
312 (L<http://html-template.sourceforge.net>).
314 =head2 Create a Catalyst View Using C<TTSite>
316 When using TT for the Catalyst view, there are two main helper scripts:
322 L<Catalyst::Helper::View::TT|Catalyst::Helper::View::TT>
326 L<Catalyst::Helper::View::TTSite|Catalyst::Helper::View::TTSite>
330 Both are similar, but C<TT> merely creates the C<lib/MyApp/View/TT.pm>
331 file and leaves the creation of any hierarchical template organization
332 entirely up to you. (It also creates a C<t/view_TT.t> file for testing;
333 test cases will be discussed in Part 8). The C<TTSite> helper creates a
334 modular and hierarchical view layout with separate Template Toolkit (TT)
335 files for common header and footer information, configuration values, a
336 CSS stylesheet, and more.
338 While TTSite is useful to bootstrap a project, we recommend that
339 unless you know what you're doing or want to pretty much use the
340 supplied templates as is, that you use the plain Template Toolkit view
341 when starting a project from scratch. This is because TTSite can be
342 tricky to customize. Additionally TT contains constructs that you
343 need to learn yourself if you're going to be a serious user of TT.
344 Our experience suggests that you're better off learning these from
345 scratch. We use TTSite here precisely because it is useful for
346 bootstrap/prototype purposes.
348 Enter the following command to enable the C<TTSite> style of view
349 rendering for this tutorial:
351 $ script/myapp_create.pl view TT TTSite
352 exists "/home/me/MyApp/script/../lib/MyApp/View"
353 exists "/home/me/MyApp/script/../t"
354 created "/home/me/MyApp/script/../lib/MyApp/View/TT.pm"
355 created "/home/me/MyApp/script/../root/lib"
357 created "/home/me/MyApp/script/../root/src/ttsite.css"
359 This puts a number of files in the C<root/lib> and C<root/src>
360 directories that can be used to customize the look and feel of your
361 application. Also take a look at C<lib/MyApp/View/TT.pm> for config
362 values set by the C<TTSite> helper.
364 B<TIP>: When troubleshooting TT it can be helpful to enable variable
365 C<DEBUG> options. You can do this in a Catalyst environment by adding
366 a C<DEBUG> line to the C<__PACKAGE__->config> declaration in
367 C<lib/MyApp/View/TT.pm>:
369 __PACKAGE__->config({
375 B<Note:> C<__PACKAGE__> is just a shorthand way of referencing the name
376 of the package where it is used. Therefore, in C<TT.pm>,
377 C<__PACKAGE__> is equivalent to C<TT>.
379 There are a variety of options you can use, such as 'undef', 'all',
380 'service', 'context', 'parser' and 'provider'. See
381 L<Template::Constants> for more information (remove the C<DEBUG_>
382 portion of the name shown in the TT docs and convert to lower case
383 for use inside Catalyst).
385 B<NOTE:> B<Please be sure to disable TT debug options before
386 continuing the tutorial> (especially the 'undef' option -- leaving
387 this enabled will conflict with several of the conventions used
388 by this tutorial and TTSite to leave some variables undefined
392 =head2 Globally Customize Every View
394 When using TTSite, files in the subdirectories of C<root/lib> can be
395 used to make changes that will appear in every view. For example, to
396 display optional status and error messages in every view, edit
397 C<root/lib/site/layout>, updating it to match the following (the two HTML
398 C<span> elements are new):
400 <div id="header">[% PROCESS site/header %]</div>
403 <span class="message">[% status_msg %]</span>
404 <span class="error">[% error_msg %]</span>
408 <div id="footer">[% PROCESS site/footer %]</div>
410 If we set either message in the Catalyst stash (e.g.,
411 C<$c-E<gt>stash-E<gt>{status_msg} = 'Request was successful!'>) it will
412 be displayed whenever any view used by that request is rendered. The
413 C<message> and C<error> CSS styles are automatically defined in
414 C<root/src/ttsite.css> and can be customized to suit your needs.
416 B<Note:> The Catalyst stash only lasts for a single HTTP request. If
417 you need to retain information across requests you can use
418 L<Catalyst::Plugin::Session|Catalyst::Plugin::Session> (we will use
419 Catalyst sessions in the Authentication part of the tutorial).
422 =head2 Create a TT Template Page
424 To add a new page of content to the TTSite view hierarchy, just create a
425 new C<.tt2> file in C<root/src>. Only include HTML markup that goes
426 inside the HTML <body> and </body> tags, TTSite will use the contents of
427 C<root/lib/site> to add the top and bottom.
429 First create a directory for book-related TT templates:
431 $ mkdir root/src/books
433 Then create C<root/src/books/list.tt2> in your editor and enter:
435 [% # This is a TT comment. The '-' at the end "chomps" the newline. You won't -%]
436 [% # see this "chomping" in your browser because HTML ignores blank lines, but -%]
437 [% # it WILL eliminate a blank line if you view the HTML source. It's purely -%]
438 [%- # optional, but both the beginning and the ending TT tags support chomping. -%]
440 [% # Provide a title to root/lib/site/header -%]
441 [% META title = 'Book List' -%]
444 <tr><th>Title</th><th>Rating</th><th>Author(s)</th></tr>
445 [% # Display each book in a table row %]
446 [% FOREACH book IN books -%]
448 <td>[% book.title %]</td>
449 <td>[% book.rating %]</td>
454 As indicated by the inline comments above, the C<META title> line uses
455 TT's META feature to provide a title to C<root/lib/site/header>.
456 Meanwhile, the outer C<FOREACH> loop iterates through each C<book> model
457 object and prints the C<title> and C<rating> fields. An inner
458 C<FOREACH> loop prints the last name of each author in a comma-separated
459 list within a single table cell.
461 If you are new to TT, the C<[%> and C<%]> tags are used to delimit TT
462 code. TT supports a wide variety of directives for "calling" other
463 files, looping, conditional logic, etc. In general, TT simplifies the
464 usual range of Perl operators down to the single dot (C<.>) operator.
465 This applies to operations as diverse as method calls, hash lookups, and
466 list index values (see
467 L<http://search.cpan.org/perldoc?Template::Manual::Variables>
468 for details and examples). In addition to the usual C<Template> module
469 Pod documentation, you can access the TT manual at
470 L<http://search.cpan.org/perldoc?Template::Manual>.
472 B<NOTE:> The C<TTSite> helper creates several TT files using an
473 extension of C<.tt2>. Most other Catalyst and TT examples use an
474 extension of C<.tt>. You can use either extension (or no extension at
475 all) with TTSite and TT, just be sure to use the appropriate extension
476 for both the file itself I<and> the C<$c-E<gt>stash-E<gt>{template} =
477 ...> line in your controller. This document will use C<.tt2> for
478 consistency with the files already created by the C<TTSite> helper.
481 =head1 CREATE A SQLITE DATABASE
483 In this step, we make a text file with the required SQL commands to
484 create a database table and load some sample data. Open C<myapp01.sql>
485 in your editor and enter:
488 -- Create a very simple database to hold book and author information
491 id INTEGER PRIMARY KEY,
495 -- 'book_authors' is a many-to-many join table between books & authors
496 CREATE TABLE book_authors (
499 PRIMARY KEY (book_id, author_id)
501 CREATE TABLE authors (
502 id INTEGER PRIMARY KEY,
507 --- Load some sample data
509 INSERT INTO books VALUES (1, 'CCSP SNRS Exam Certification Guide', 5);
510 INSERT INTO books VALUES (2, 'TCP/IP Illustrated, Volume 1', 5);
511 INSERT INTO books VALUES (3, 'Internetworking with TCP/IP Vol.1', 4);
512 INSERT INTO books VALUES (4, 'Perl Cookbook', 5);
513 INSERT INTO books VALUES (5, 'Designing with Web Standards', 5);
514 INSERT INTO authors VALUES (1, 'Greg', 'Bastien');
515 INSERT INTO authors VALUES (2, 'Sara', 'Nasseh');
516 INSERT INTO authors VALUES (3, 'Christian', 'Degu');
517 INSERT INTO authors VALUES (4, 'Richard', 'Stevens');
518 INSERT INTO authors VALUES (5, 'Douglas', 'Comer');
519 INSERT INTO authors VALUES (6, 'Tom', 'Christiansen');
520 INSERT INTO authors VALUES (7, 'Nathan', 'Torkington');
521 INSERT INTO authors VALUES (8, 'Jeffrey', 'Zeldman');
522 INSERT INTO book_authors VALUES (1, 1);
523 INSERT INTO book_authors VALUES (1, 2);
524 INSERT INTO book_authors VALUES (1, 3);
525 INSERT INTO book_authors VALUES (2, 4);
526 INSERT INTO book_authors VALUES (3, 5);
527 INSERT INTO book_authors VALUES (4, 6);
528 INSERT INTO book_authors VALUES (4, 7);
529 INSERT INTO book_authors VALUES (5, 8);
531 B<TIP>: See Appendix 1 for tips on removing the leading spaces when
532 cutting and pasting example code from POD-based documents.
534 Then use the following command to build a C<myapp.db> SQLite database:
536 $ sqlite3 myapp.db < myapp01.sql
538 If you need to create the database more than once, you probably want to
539 issue the C<rm myapp.db> command to delete the database before you use
540 the C<sqlite3 myapp.db < myapp01.sql> command.
542 Once the C<myapp.db> database file has been created and initialized, you
543 can use the SQLite command line environment to do a quick dump of the
548 Enter ".help" for instructions
549 sqlite> select * from books;
550 1|CCSP SNRS Exam Certification Guide|5
551 2|TCP/IP Illustrated, Volume 1|5
552 3|Internetworking with TCP/IP Vol.1|4
554 5|Designing with Web Standards|5
560 $ sqlite3 myapp.db "select * from books"
561 1|CCSP SNRS Exam Certification Guide|5
562 2|TCP/IP Illustrated, Volume 1|5
563 3|Internetworking with TCP/IP Vol.1|4
565 5|Designing with Web Standards|5
567 As with most other SQL tools, if you are using the full "interactive"
568 environment you need to terminate your SQL commands with a ";" (it's not
569 required if you do a single SQL statement on the command line). Use
570 ".q" to exit from SQLite from the SQLite interactive mode and return to
571 your OS command prompt.
574 =head1 DATABASE ACCESS WITH C<DBIx::Class>
576 Catalyst can be used with virtually any form of persistent datastore
577 available via Perl. For example,
578 L<Catalyst::Model::DBI|Catalyst::Model::DBI> can be used to
579 easily access databases through the traditional Perl C<DBI> interface.
580 However, most Catalyst applications use some form of ORM technology to
581 automatically create and save model objects as they are used. Although
582 Tony Bowden's L<Class::DBI|Class::DBI> has been a popular choice
583 in the past, Matt Trout's L<DBIx::Class|DBIx::Class> (abbreviated
584 as "DBIC") has rapidly emerged as the Perl-based ORM technology of choice.
585 Most new Catalyst applications rely on DBIC, as will this tutorial.
587 =head2 Create a dynamic DBIC Model
589 Use the C<create=dynamic> model helper option to build a model that
590 dynamically reads your database structure every time the application
593 $ script/myapp_create.pl model DB DBIC::Schema MyApp::Schema create=dynamic dbi:SQLite:myapp.db
594 exists "/home/kclark/dev/MyApp/script/../lib/MyApp/Model"
595 exists "/home/kclark/dev/MyApp/script/../t"
596 exists "/home/kclark/dev/MyApp/script/../lib/MyApp"
597 created "/home/kclark/dev/MyApp/script/../lib/MyApp/Schema.pm"
598 created "/home/kclark/dev/MyApp/script/../lib/MyApp/Model/DB.pm"
599 created "/home/kclark/dev/MyApp/script/../t/model_DB.t"
602 C<DB> is the name of the model class to be created by the helper in
603 C<lib/MyApp/Model> (Catalyst has a separate directory under C<lib/MyApp>
604 for each of the three parts of MVC: C<Model>, C<View>, and C<Controller>).
605 C<DBIC::Schema> is the type of the model to create.
606 C<MyApp::Schema> is the name of the DBIC schema file written to
607 C<lib/MyApp/Schema.pm>. Because we specified C<create=dynamic>
608 to the helper, it use L<DBIx::Class::Schema::Loader> to dynamically load
609 the schema information from the database every time the application
610 starts. And finally, C<dbi:SQLite:myapp.db> is the standard DBI connect
611 string for use with SQLite.
613 B<NOTE:> Although the C<create=dynamic> option to the DBIC helper
614 makes for a nifty demonstration, is only really suitable for very
615 small applications. After this demonstration, you should almost always
616 use the C<create=static> option that we switch to below.
619 =head1 RUN THE APPLICATION
621 First, let's enable an environment variable option that causes
622 DBIx::Class to dump the SQL statements it's using to access the database
623 (this option can provide extremely helpful troubleshooting information):
625 $ export DBIC_TRACE=1
627 This assumes you are using BASH as your shell -- adjust accordingly if
628 you are using a different shell (for example, under tcsh, use
629 C<setenv DBIC_TRACE 1>).
631 B<NOTE:> You can also set this in your code using
632 C<$class-E<gt>storage-E<gt>debug(1);>. See
633 L<DBIx::Class::Manual::Troubleshooting> for details (including options
634 to log to file instead of displaying to the Catalyst development server
637 Then run the Catalyst "demo server" script:
639 $ script/myapp_server.pl
641 Your development server log output should display something like:
643 $script/myapp_server.pl
644 [debug] Debug messages enabled
645 [debug] Loaded plugins:
646 .----------------------------------------------------------------------------.
647 | Catalyst::Plugin::ConfigLoader 0.17 |
648 | Catalyst::Plugin::StackTrace 0.06 |
649 | Catalyst::Plugin::Static::Simple 0.20 |
650 '----------------------------------------------------------------------------'
652 [debug] Loaded dispatcher "Catalyst::Dispatcher"
653 [debug] Loaded engine "Catalyst::Engine::HTTP"
654 [debug] Found home "/home/me/MyApp"
655 [debug] Loaded Config "/home/me/MyApp/myapp.conf"
656 [debug] Loaded components:
657 .-----------------------------------------------------------------+----------.
659 +-----------------------------------------------------------------+----------+
660 | MyApp::Controller::Books | instance |
661 | MyApp::Controller::Root | instance |
662 | MyApp::Model::DB | instance |
663 | MyApp::Model::DB::Authors | class |
664 | MyApp::Model::DB::BookAuthors | class |
665 | MyApp::Model::DB::Books | class |
666 | MyApp::View::TT | instance |
667 '-----------------------------------------------------------------+----------'
669 [debug] Loaded Private actions:
670 .----------------------+--------------------------------------+--------------.
671 | Private | Class | Method |
672 +----------------------+--------------------------------------+--------------+
673 | /default | MyApp::Controller::Root | default |
674 | /end | MyApp::Controller::Root | end |
675 | /books/index | MyApp::Controller::Books | index |
676 | /books/list | MyApp::Controller::Books | list |
677 '----------------------+--------------------------------------+--------------'
679 [debug] Loaded Path actions:
680 .-------------------------------------+--------------------------------------.
682 +-------------------------------------+--------------------------------------+
683 | /books/list | /books/list |
684 '-------------------------------------+--------------------------------------'
686 [info] MyApp powered by Catalyst 5.7011
687 You can connect to your server at http://localhost:3000
689 B<NOTE:> Be sure you run the C<script/myapp_server.pl> command from
690 the 'base' directory of your application, not inside the C<script>
691 directory itself or it will not be able to locate the C<myapp.db>
692 database file. You can use a fully qualified or a relative path to
693 locate the database file, but we did not specify that when we ran the
694 model helper earlier.
696 Some things you should note in the output above:
702 Catalyst::Model::DBIC::Schema dynamically created three model classes,
703 one to represent each of the three tables in our database
704 (C<MyApp::Model::DB::Authors>, C<MyApp::Model::DB::BookAuthors>,
705 and C<MyApp::Model::DB::Books>).
709 The "list" action in our Books controller showed up with a path of
714 Point your browser to L<http://localhost:3000> and you should still get
715 the Catalyst welcome page.
717 Next, to view the book list, change the URL in your browser to
718 L<http://localhost:3000/books/list>. You should get a list of the five
719 books loaded by the C<myapp01.sql> script above, with TTSite providing
720 the formatting for the very simple output we generated in our template.
721 The rating for each book should appear on each row.
723 Also notice in the output of the C<script/myapp_server.pl> that DBIC
724 used the following SQL to retrieve the data:
726 SELECT me.id, me.title, me.rating FROM books me
728 because we enabled DBIC_TRACE.
730 You now have the beginnings of a simple but workable web application.
731 Continue on to future sections and we will develop the application
735 =head1 A STATIC DATABASE MODEL WITH C<DBIx::Class>
737 =head2 Create Static DBIC Schema Files
739 Unlike the previous section where we had DBIC automatically discover the
740 structure of the database every time the application started, here we
741 will use static schema files for more control. This is typical of most
742 "real world" applications.
744 One option would be to create a separate schema file for each table in
745 the database, however, lets use the same L<DBIx::Class::Schema::Loader>
746 used earlier with C<create=dynamic> to build the static files for us.
747 First, lets remove the schema file created earlier:
749 $ rm lib/MyApp/Schema.pm
751 Now regenerate the schema using the C<create=static> option:
753 $ script/myapp_create.pl model DB DBIC::Schema MyApp::Schema create=static dbi:SQLite:myapp.db
754 exists "/home/kclark/dev/MyApp/script/../lib/MyApp/Model"
755 exists "/home/kclark/dev/MyApp/script/../t"
756 Dumping manual schema for MyApp::Schema to directory /home/kclark/dev/MyApp/script/../lib ...
757 Schema dump completed.
758 exists "/home/kclark/dev/MyApp/script/../lib/MyApp/Model/DB.pm"
760 We could have also deleted C<lib/MyApp/Model/DB.pm>, but it would
761 have regenerated the same file (note the C<exists> in the output above).
762 If you take a look at C<lib/MyApp/Model/DB.pm>, it simply contains
763 a reference to the actual schema file in C<lib/MyApp/Schema.pm>
764 along with the database connect string.
766 If you look in the C<lib/MyApp/Schema> directory, you will find that
767 C<DB.pm> is no longer using L<DBIx::Class::Schema::Loader> as its
768 base class (L<DBIx::Class::Schema::Loader> is only being used by the
769 helper to load the schema once and then create the static files for us)
770 and that it only contains a call to the C<load_classes> method. You
771 will also find that C<lib/MyApp/Schema> contains a C<Schema>
772 subdirectory, with one file inside this directory for each of the tables
773 in our simple database (C<Authors.pm>, C<BookAuthors.pm>, and
774 C<Books.pm>). These three files were created based on the information
775 found by L<DBIx::Class::Schema::Loader> as the helper ran.
777 The idea with all of the files created under C<lib/MyApp/Schema> by the
778 C<create=static> option is to only edit the files below the C<# DO NOT
779 MODIFY THIS OR ANYTHING ABOVE!> warning. If you place all of your
780 changes below that point in the file, you can regenerate the
781 auto-generated information at the top of each file should your database
782 structure get updated.
784 Also note the "flow" of the model information across the various files
785 and directories. Catalyst will initially load the model from
786 C<lib/MyApp/Model/DB.pm>. This file contains a reference to
787 C<lib/MyApp/Schema.pm>, so that file is loaded next. Finally,
788 the call to C<load_classes> in that file will load each of the
789 table-specific "results source" files from the C<lib/MyApp/Schema>
790 subdirectory. These three table-specific DBIC schema files will then be
791 used to create three table-specific Catalyst models every time the
792 application starts (you can see these three model files listed in
793 the debug output generated when you launch the application).
796 =head2 Updating the Generated DBIC Schema Files
799 Let's manually add some relationship information to the auto-generated
800 schema files. First edit C<lib/MyApp/Schema/Books.pm> and
801 add the following text below the C<# You can replace this text...>
810 # 1) Name of relationship, DBIC will create accessor with this name
811 # 2) Name of the model class referenced by this relationship
812 # 3) Column name in *foreign* table
813 __PACKAGE__->has_many(book_authors => 'MyApp::Schema::BookAuthors', 'book_id');
817 # 1) Name of relationship, DBIC will create accessor with this name
818 # 2) Name of has_many() relationship this many_to_many() is shortcut for
819 # 3) Name of belongs_to() relationship in model class of has_many() above
820 # You must already have the has_many() defined to use a many_to_many().
821 __PACKAGE__->many_to_many(authors => 'book_authors', 'author');
824 B<Note:> Be careful to put this code I<above> the C<1;> at the end of the
825 file. As with any Perl package, we need to end the last line with
826 a statement that evaluates to C<true>. This is customarily done with
827 C<1;> on a line by itself.
829 This code defines both a C<has_many> and a C<many_to_many> relationship.
830 The C<many_to_many> relationship is optional, but it makes it easier to
831 map a book to its collection of authors. Without it, we would have to
832 "walk" though the C<book_authors> table as in C<$book-E<gt>book_authors-
833 E<gt>first-E<gt>author-E<gt>last_name> (we will see examples on how to
834 use DBIC objects in your code soon, but note that because C<$book-
835 E<gt>book_authors> can return multiple authors, we have to use C<first>
836 to display a single author). C<many_to_many> allows us to use the
837 shorter C<$book-E<gt>authors-E<gt>first-E<gt>last_name>. Note that you
838 cannot define a C<many_to_many> relationship without also having the
839 C<has_many> relationship in place.
841 Then edit C<lib/MyApp/Schema/Authors.pm> and add relationship
842 information as follows (again, be careful to put in above the C<1;> but
843 below the C<# DO NOT MODIFY THIS OR ANYTHING ABOVE!> comment):
851 # 1) Name of relationship, DBIC will create accessor with this name
852 # 2) Name of the model class referenced by this relationship
853 # 3) Column name in *foreign* table
854 __PACKAGE__->has_many(book_author => 'MyApp::Schema::BookAuthors', 'author_id');
858 # 1) Name of relationship, DBIC will create accessor with this name
859 # 2) Name of has_many() relationship this many_to_many() is shortcut for
860 # 3) Name of belongs_to() relationship in model class of has_many() above
861 # You must already have the has_many() defined to use a many_to_many().
862 __PACKAGE__->many_to_many(books => 'book_author', 'book');
864 Finally, do the same for the "join table,"
865 C<lib/MyApp/Schema/BookAuthors.pm>:
873 # 1) Name of relationship, DBIC will create accessor with this name
874 # 2) Name of the model class referenced by this relationship
875 # 3) Column name in *this* table
876 __PACKAGE__->belongs_to(book => 'MyApp::Schema::Books', 'book_id');
880 # 1) Name of relationship, DBIC will create accessor with this name
881 # 2) Name of the model class referenced by this relationship
882 # 3) Column name in *this* table
883 __PACKAGE__->belongs_to(author => 'MyApp::Schema::Authors', 'author_id');
886 =head1 RUN THE APPLICATION
888 Run the Catalyst "demo server" script with the C<DBIC_TRACE> option
889 (it might still be enabled from earlier in the tutorial, but here
890 is an alternate way to specify the option just in case):
892 $ DBIC_TRACE=1 script/myapp_server.pl
894 Make sure that the application loads correctly and that you see the
895 three dynamically created model class (one for each of the
896 table-specific schema classes we created).
898 Then hit the URL L<http://localhost:3000/books/list> and be sure that
899 the book list is displayed.
902 =head1 RUNNING THE APPLICATION FROM THE COMMAND LINE
904 In some situations, it can be useful to run your application and
905 display a page without using a browser. Catalyst lets you do this
906 using the C<scripts/myapp_test.pl> script. Just supply the URL you
907 wish to display and it will run that request through the normal
908 controller dispatch logic and use the appropriate view to render the
909 output (obviously, complex pages may dump a lot of text to your
910 terminal window). For example, if you type:
912 $ script/myapp_test.pl "/books/list"
914 You should get the same text as if you visited
915 L<http://localhost:3000/books/list> with the normal development server
916 and asked your browser to view the page source.
919 =head1 UPDATING THE VIEW
921 Let's add a new column to our book list page that takes advantage of
922 the relationship information we manually added to our schema files
923 in the previous section. Edit C<root/src/books/list.tt2> add add the
924 following code below the existing table cell that contains
925 C<book.rating> (IOW, add a new table cell below the existing two
929 [% # First initialize a TT variable to hold a list. Then use a TT FOREACH -%]
930 [% # loop in 'side effect notation' to load just the last names of the -%]
931 [% # authors into the list. Note that the 'push' TT vmethod does not -%]
932 [% # a value, so nothing will be printed here. But, if you have something -%]
933 [% # in TT that does return a method and you don't want it printed, you -%]
934 [% # can: 1) assign it to a bogus value, or 2) use the CALL keyword to -%]
935 [% # call it and discard the return value. -%]
937 tt_authors.push(author.last_name) FOREACH author = book.authors %]
938 [% # Now use a TT 'virtual method' to display the author count in parens -%]
939 [% # Note the use of the TT filter "| html" to escape dangerous characters -%]
940 ([% tt_authors.size | html %])
941 [% # Use another TT vmethod to join & print the names & comma separators -%]
942 [% tt_authors.join(', ') | html %]
945 Then hit C<Ctrl+R> in your browser (not that you don't need to reload
946 the development server or use the C<-r> option when updating TT
947 templates) and you should now the the number of authors each book and
948 a comma-separated list of the author's last names.
950 If you are still running the development server with C<DBIC_TRACE>
951 enabled, you should also now see five more C<SELECT> statements in the
952 debug output (one for each book as the authors are being retrieved by
955 Also note that we are using "| html", a type of TT filter, to escape
956 characters such as E<lt> and E<gt> to < and > and avoid various
957 types of dangerous hacks against your application. In a real
958 application, you would probably want to put "| html" at the end of
959 every field where a user has control over the information that can
960 appear in that field (and can therefore inject markup or code if you
961 don't "neutralize" those fields). In addition to "| html", Template
962 Toolkit has a variety of other useful filters that can found in the
963 documentation for L<Template::Filters|Template::Filters>.
966 =head2 Using C<RenderView> for the Default View
968 B<NOTE: The rest of this part of the tutorial is optional. You can
969 skip to Part 4, L<Basic CRUD|Catalyst::Manual::Tutorial::BasicCRUD>,
972 Once your controller logic has processed the request from a user, it
973 forwards processing to your view in order to generate the appropriate
974 response output. Catalyst uses
975 L<Catalyst::Action::RenderView|Catalyst::Action::RenderView> by
976 default to automatically performs this operation. If you look in
977 C<lib/MyApp/Controller/Root.pm>, you should see the empty
978 definition for the C<sub end> method:
980 sub end : ActionClass('RenderView') {}
982 The following bullet points provide a quick overview of the
983 C<RenderView> process:
989 C<Root.pm> is designed to hold application-wide logic.
993 At the end of a given user request, Catalyst will call the most specific
994 C<end> method that's appropriate. For example, if the controller for a
995 request has an C<end> method defined, it will be called. However, if
996 the controller does not define a controller-specific C<end> method, the
997 "global" C<end> method in C<Root.pm> will be called.
1001 Because the definition includes an C<ActionClass> attribute, the
1002 L<Catalyst::Action::RenderView|Catalyst::Action::RenderView> logic
1003 will be executed B<after> any code inside the definition of C<sub end>
1004 is run. See L<Catalyst::Manual::Actions|Catalyst::Manual::Actions>
1005 for more information on C<ActionClass>.
1009 Because C<sub end> is empty, this effectively just runs the default
1010 logic in C<RenderView>. However, you can easily extend the
1011 C<RenderView> logic by adding your own code inside the empty method body
1012 (C<{}>) created by the Catalyst Helpers when we first ran the
1013 C<catalyst.pl> to initialize our application. See
1014 L<Catalyst::Action::RenderView|Catalyst::Action::RenderView> for more
1015 detailed information on how to extended C<RenderView> in C<sub end>.
1020 =head2 Using The Default Template Name
1022 By default, C<Catalyst::View::TT> will look for a template that uses the
1023 same name as your controller action, allowing you to save the step of
1024 manually specifying the template name in each action. For example, this
1025 would allow us to remove the
1026 C<$c-E<gt>stash-E<gt>{template} = 'books/list.tt2';> line of our
1027 C<list> action in the Books controller. Open
1028 C<lib/MyApp/Controller/Books.pm> in your editor and comment out this line
1029 to match the following (only the C<$c-E<gt>stash-E<gt>{template}> line
1034 Fetch all book objects and pass to books/list.tt2 in stash to be displayed
1039 # Retrieve the usual Perl OO '$self' for this object. $c is the Catalyst
1040 # 'Context' that's used to 'glue together' the various components
1041 # that make up the application
1042 my ($self, $c) = @_;
1044 # Retrieve all of the book records as book model objects and store in the
1045 # stash where they can be accessed by the TT template
1046 $c->stash->{books} = [$c->model('DB::Books')->all];
1048 # Set the TT template to use. You will almost always want to do this
1049 # in your action methods (actions methods respond to user input in
1050 # your controllers).
1051 #$c->stash->{template} = 'books/list.tt2';
1054 C<Catalyst::View::TT> defaults to looking for a template with no
1055 extension. In our case, we need to override this to look for an
1056 extension of C<.tt2>. Open C<lib/MyApp/View/TT.pm> and add the
1057 C<TEMPLATE_EXTENSION> definition as follows:
1059 __PACKAGE__->config({
1060 CATALYST_VAR => 'Catalyst',
1062 MyApp->path_to( 'root', 'src' ),
1063 MyApp->path_to( 'root', 'lib' )
1065 PRE_PROCESS => 'config/main',
1066 WRAPPER => 'site/wrapper',
1067 ERROR => 'error.tt2',
1069 TEMPLATE_EXTENSION => '.tt2',
1072 You should now be able to restart the development server as per the
1073 previous section and access the L<http://localhost:3000/books/list>
1076 B<NOTE:> Please note that if you use the default template technique,
1077 you will B<not> be able to use either the C<$c-E<gt>forward> or
1078 the C<$c-E<gt>detach> mechanisms (these are discussed in Part 2 and
1079 Part 9 of the Tutorial).
1082 =head2 Return To A Manually-Specified Template
1084 In order to be able to use C<$c-E<gt>forward> and C<$c-E<gt>detach>
1085 later in the tutorial, you should remove the comment from the
1086 statement in C<sub list> in C<lib/MyApp/Controller/Books.pm>:
1088 $c->stash->{template} = 'books/list.tt2';
1090 Then delete the C<TEMPLATE_EXTENSION> line in
1091 C<lib/MyApp/View/TT.pm>.
1093 You should then be able to restart the development server and
1094 access L<http://localhost:3000/books/list> in the same manner as
1095 with earlier sections.
1100 Kennedy Clark, C<hkclark@gmail.com>
1102 Please report any errors, issues or suggestions to the author. The
1103 most recent version of the Catalyst Tutorial can be found at
1104 L<http://dev.catalyst.perl.org/repos/Catalyst/trunk/Catalyst-Manual/lib/Catalyst/Manual/Tutorial/>.
1106 Copyright 2006-2008, Kennedy Clark, under Creative Commons License
1107 (L<http://creativecommons.org/licenses/by-nc-sa/2.5/>).