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> or 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 plugin 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 YAML file (versus having
137 the values hard-coded inside your Perl modules). If you have not been
138 exposed to YAML before, it is a human-readable data serialization format
139 that can be used to read (and write) values to/from text files. We will
140 see how to use this feature of Catalyst during the authentication and
141 authorization sections (Part 5 and Part 6).
145 L<Catalyst::Plugin::Static::Simple|Catalyst::Plugin::Static::Simple>
147 C<Static::Simple> provides an easy method of serving static content such
148 as images and CSS files under the development server.
152 To modify the list of plugins, edit C<lib/MyApp.pm> (this file is
153 generally referred to as your I<application class>) and delete the line
156 use Catalyst qw/-Debug ConfigLoader Static::Simple/;
168 This tells Catalyst to start using one new plugin:
174 L<Catalyst::Plugin::StackTrace|Catalyst::Plugin::StackTrace>
176 Adds a stack trace to the standard Catalyst "debug screen" (this is the
177 screen Catalyst sends to your browser when an error occurs).
179 Note: L<StackTrace|Catalyst::Plugin::StackTrace> output appears in your
180 browser, not in the console window from which you're running your
181 application, which is where logging output usually goes.
185 Note that when specifying plugins on the C<use Catalyst> line, you can
186 omit C<Catalyst::Plugin::> from the name. Additionally, you can spread
187 the plugin names across multiple lines as shown here, or place them all
188 on one (or more) lines as with the default configuration.
191 =head1 CREATE A CATALYST CONTROLLER
193 As discussed earlier, controllers are where you write methods that
194 interact with user input. Typically, controller methods respond to
195 C<GET> and C<POST> messages from the user's web browser.
197 Use the Catalyst C<create> script to add a controller for book-related
200 $ script/myapp_create.pl controller Books
201 exists "/home/me/MyApp/script/../lib/MyApp/Controller"
202 exists "/home/me/MyApp/script/../t"
203 created "/home/me/MyApp/script/../lib/MyApp/Controller/Books.pm"
204 created "/home/me/MyApp/script/../t/controller_Books.t"
206 Then edit C<lib/MyApp/Controller/Books.pm> and add the following method
211 Fetch all book objects and pass to books/list.tt2 in stash to be displayed
216 # Retrieve the usual Perl OO '$self' for this object. $c is the Catalyst
217 # 'Context' that's used to 'glue together' the various components
218 # that make up the application
221 # Retrieve all of the book records as book model objects and store in the
222 # stash where they can be accessed by the TT template
223 $c->stash->{books} = [$c->model('MyAppDB::Books')->all];
225 # Set the TT template to use. You will almost always want to do this
226 # in your action methods (action methods respond to user input in
228 $c->stash->{template} = 'books/list.tt2';
231 B<Note:> This won't actually work yet since you haven't set up your
234 B<Note:> Programmers experienced with object-oriented Perl should
235 recognize C<$self> as a reference to the object where this method was
236 called. On the other hand, C<$c> will be new to many Perl programmers
237 who have not used Catalyst before (it's sometimes written as
238 C<$context>). The Context object is automatically passed to all
239 Catalyst components. It is used to pass information between
240 components and provide access to Catalyst and plugin functionality.
242 B<TIP>: You may see the C<$c-E<gt>model('MyAppDB::Book')> used above
243 written as C<$c-E<gt>model('MyAppDB')-E<gt>resultset('Book)>. The two
246 B<Note:> Catalyst actions are regular Perl methods, but they make use
247 of Nicholas Clark's C<attributes> module (that's the C<: Local> next
248 to the C<sub list> in the code above) to provide additional
249 information to the Catalyst dispatcher logic. Many newer Catalyst
250 applications are switching to the use of "Literal" C<: Path> actions
251 and C<Args> attribute in lieu of C<: Local> and C<: Private>. For
252 example, C<sub any_method : Path Args(0)> can be used instead of
253 C<sub index :Private> (because no path was supplied to C<Path> it
254 matches the "empty" URL in the namespace of that module... the same
255 thing C<sub index> would do) or C<sub list : Path('list') Args(0)>
256 could be used instead of the C<sub list : Local> above (the C<list>
257 argument to C<Path> would make it match on the URL C<list> under
258 C<books>, the namespace of the current module). See "Action Types" in
259 L<Catalyst::Manual::Intro|Catalyst::Manual::Intro> as well as Part 5
260 of this tutorial (Authentication) for additional information. Another
261 popular but more advanced feature is C<Chained> actions that allow a
262 single URL to "chain together" multiple action method calls, each with
263 an appropriate number of arguments (see
264 L<Catalyst::DispatchType::Chained|Catalyst::DispatchType::Chained>
268 =head1 CATALYST VIEWS
270 As mentioned in Part 2 of the tutorial, views are where you render
271 output, typically for display in the user's web browser, but also
272 possibly using other display output- generation systems. As with
273 virtually every aspect of Catalyst, options abound when it comes to
274 the specific view technology you adopt inside your application.
275 However, most Catalyst applications use the Template Toolkit, known as
276 TT (for more information on TT, see L<http://www.template-
277 toolkit.org>). Other popular view technologies include Mason
278 (L<http://www.masonhq.com> and L<http://www.masonbook.com>) and
279 L<HTML::Template|HTML::Template> (L<http://html-
280 template.sourceforge.net>).
282 =head2 Create a Catalyst View Using C<TTSite>
284 When using TT for the Catalyst view, there are two main helper scripts:
290 L<Catalyst::Helper::View::TT|Catalyst::Helper::View::TT>
294 L<Catalyst::Helper::View::TTSite|Catalyst::Helper::View::TTSite>
298 Both are similar, but C<TT> merely creates the C<lib/MyApp/View/TT.pm>
299 file and leaves the creation of any hierarchical template organization
300 entirely up to you. (It also creates a C<t/view_TT.t> file for testing;
301 test cases will be discussed in Part 8). The C<TTSite> helper creates a
302 modular and hierarchical view layout with separate Template Toolkit (TT)
303 files for common header and footer information, configuration values, a
304 CSS stylesheet, and more.
306 While TTSite is useful to bootstrap a project, we recommend that
307 unless you know what you're doing or want to pretty much use the
308 supplied templates as is, that you use the plain Template Toolkit view
309 when starting a project from scratch. This is because TTSite can be
310 tricky to customize. Additionally TT contains constructs that you
311 need to learn yourself if you're going to be a serious user of TT.
312 Our experience suggests that you're better off learning these from
313 scratch. We use TTSite here precisely because it is useful for
314 bootstrap/prototype purposes.
316 Enter the following command to enable the C<TTSite> style of view
317 rendering for this tutorial:
319 $ script/myapp_create.pl view TT TTSite
320 exists "/home/me/MyApp/script/../lib/MyApp/View"
321 exists "/home/me/MyApp/script/../t"
322 created "/home/me/MyApp/script/../lib/MyApp/View/TT.pm"
323 created "/home/me/MyApp/script/../root/lib"
325 created "/home/me/MyApp/script/../root/src/ttsite.css"
327 This puts a number of files in the C<root/lib> and C<root/src>
328 directories that can be used to customize the look and feel of your
329 application. Also take a look at C<lib/MyApp/View/TT.pm> for config
330 values set by the C<TTSite> helper.
332 B<TIP>: Note that TTSite does one thing that could confuse people who
333 are used to the normal C<TT> Catalyst view: it redefines the Catalyst
334 context object in templates from its usual C<c> to C<Catalyst>. When
335 looking at other Catalyst examples, remember that they almost always use
336 C<c>. Note that Catalyst and TT I<do not complain> when you use the
337 wrong name to access the context object...TT simply outputs blanks for
338 that bogus logic (see next tip to change this behavior with TT C<DEBUG>
339 options). Finally, be aware that this change in name I<only>
340 applies to how the context object is accessed inside your TT templates;
341 your controllers will continue to use C<$c> (or whatever name you use
342 when fetching the reference from C<@_> inside your methods). (You can
343 change back to the "default" behavior be removing the C<CATALYST_VAR>
344 line from C<lib/MyApp/View/TT.pm>, but you will also have to edit
345 C<root/lib/config/main> and C<root/lib/config/url>. If you do this, be
346 careful not to have a collision between your own C<c> variable and the
347 Catalyst C<c> variable.)
349 B<TIP>: When troubleshooting TT it can be helpful to enable variable
350 C<DEBUG> options. You can do this in a Catalyst environment by adding
351 a C<DEBUG> line to the C<__PACKAGE__->config> declaration in
352 C<lib/MyApp/View/TT.pm>:
354 __PACKAGE__->config({
355 CATALYST_VAR => 'Catalyst',
361 B<Note:> C<__PACKAGE__> is just a shorthand way of referencing the name
362 of the package where it is used. Therefore, in C<TT.pm>,
363 C<__PACKAGE__> is equivalent to C<TT>.
365 There are a variety of options you can use, such as 'undef', 'all',
366 'service', 'context', 'parser', 'provider', and 'service'. See
367 L<Template::Constants> for more information (remove the C<DEBUG_>
368 portion of the name shown in the TT docs and convert to lower case
369 for use inside Catalyst).
371 B<NOTE:> B<Please be sure to disable TT debug options before
372 continuing the tutorial> (especially the 'undef' option -- leaving
373 this enabled will conflict with several of the conventions used
374 by this tutorial and TTSite to leave some variables undefined
378 =head2 Globally Customize Every View
380 When using TTSite, files in the subdirectories of C<root/lib> can be
381 used to make changes that will appear in every view. For example, to
382 display optional status and error messages in every view, edit
383 C<root/lib/site/layout>, updating it to match the following (the two HTML
384 C<span> elements are new):
386 <div id="header">[% PROCESS site/header %]</div>
389 <span class="message">[% status_msg %]</span>
390 <span class="error">[% error_msg %]</span>
394 <div id="footer">[% PROCESS site/footer %]</div>
396 If we set either message in the Catalyst stash (e.g.,
397 C<$c-E<gt>stash-E<gt>{status_msg} = 'Request was successful!'>) it will
398 be displayed whenever any view used by that request is rendered. The
399 C<message> and C<error> CSS styles are automatically defined in
400 C<root/src/ttsite.css> and can be customized to suit your needs.
402 B<Note:> The Catalyst stash only lasts for a single HTTP request. If
403 you need to retain information across requests you can use
404 L<Catalyst::Plugin::Session|Catalyst::Plugin::Session> (we will use
405 Catalyst sessions in the Authentication part of the tutorial).
408 =head2 Create a TT Template Page
410 To add a new page of content to the TTSite view hierarchy, just create a
411 new C<.tt2> file in C<root/src>. Only include HTML markup that goes
412 inside the HTML <body> and </body> tags, TTSite will use the contents of
413 C<root/lib/site> to add the top and bottom.
415 First create a directory for book-related TT templates:
417 $ mkdir root/src/books
419 Then create C<root/src/books/list.tt2> in your editor and enter:
421 [% # This is a TT comment. The '-' at the end "chomps" the newline. You won't -%]
422 [% # see this "chomping" in your browser because HTML ignores blank lines, but -%]
423 [% # it WILL eliminate a blank line if you view the HTML source. It's purely -%]
424 [%- # optional, but both the beginning and the ending TT tags support chomping. -%]
426 [% # Provide a title to root/lib/site/header -%]
427 [% META title = 'Book List' -%]
430 <tr><th>Title</th><th>Rating</th><th>Author(s)</th></tr>
431 [% # Display each book in a table row %]
432 [% FOREACH book IN books -%]
434 <td>[% book.title %]</td>
435 <td>[% book.rating %]</td>
440 As indicated by the inline comments above, the C<META title> line uses
441 TT's META feature to provide a title to C<root/lib/site/header>.
442 Meanwhile, the outer C<FOREACH> loop iterates through each C<book> model
443 object and prints the C<title> and C<rating> fields. An inner
444 C<FOREACH> loop prints the last name of each author in a comma-separated
445 list within a single table cell.
447 If you are new to TT, the C<[%> and C<%]> tags are used to delimit TT
448 code. TT supports a wide variety of directives for "calling" other
449 files, looping, conditional logic, etc. In general, TT simplifies the
450 usual range of Perl operators down to the single dot (C<.>) operator.
451 This applies to operations as diverse as method calls, hash lookups, and
452 list index values (see
453 L<http://www.template-toolkit.org/docs/default/Manual/Variables.html>
454 for details and examples). In addition to the usual C<Template> module
455 Pod documentation, you can access the TT manual at
456 L<http://www.template-toolkit.org/docs/default/>.
458 B<NOTE>: The C<TTSite> helper creates several TT files using an
459 extension of C<.tt2>. Most other Catalyst and TT examples use an
460 extension of C<.tt>. You can use either extension (or no extension at
461 all) with TTSite and TT, just be sure to use the appropriate extension
462 for both the file itself I<and> the C<$c-E<gt>stash-E<gt>{template} =
463 ...> line in your controller. This document will use C<.tt2> for
464 consistency with the files already created by the C<TTSite> helper.
467 =head1 CREATE A SQLITE DATABASE
469 In this step, we make a text file with the required SQL commands to
470 create a database table and load some sample data. Open C<myapp01.sql>
471 in your editor and enter:
474 -- Create a very simple database to hold book and author information
477 id INTEGER PRIMARY KEY,
481 -- 'book_authors' is a many-to-many join table between books & authors
482 CREATE TABLE book_authors (
485 PRIMARY KEY (book_id, author_id)
487 CREATE TABLE authors (
488 id INTEGER PRIMARY KEY,
493 --- Load some sample data
495 INSERT INTO books VALUES (1, 'CCSP SNRS Exam Certification Guide', 5);
496 INSERT INTO books VALUES (2, 'TCP/IP Illustrated, Volume 1', 5);
497 INSERT INTO books VALUES (3, 'Internetworking with TCP/IP Vol.1', 4);
498 INSERT INTO books VALUES (4, 'Perl Cookbook', 5);
499 INSERT INTO books VALUES (5, 'Designing with Web Standards', 5);
500 INSERT INTO authors VALUES (1, 'Greg', 'Bastien');
501 INSERT INTO authors VALUES (2, 'Sara', 'Nasseh');
502 INSERT INTO authors VALUES (3, 'Christian', 'Degu');
503 INSERT INTO authors VALUES (4, 'Richard', 'Stevens');
504 INSERT INTO authors VALUES (5, 'Douglas', 'Comer');
505 INSERT INTO authors VALUES (6, 'Tom', 'Christiansen');
506 INSERT INTO authors VALUES (7, 'Nathan', 'Torkington');
507 INSERT INTO authors VALUES (8, 'Jeffrey', 'Zeldman');
508 INSERT INTO book_authors VALUES (1, 1);
509 INSERT INTO book_authors VALUES (1, 2);
510 INSERT INTO book_authors VALUES (1, 3);
511 INSERT INTO book_authors VALUES (2, 4);
512 INSERT INTO book_authors VALUES (3, 5);
513 INSERT INTO book_authors VALUES (4, 6);
514 INSERT INTO book_authors VALUES (4, 7);
515 INSERT INTO book_authors VALUES (5, 8);
517 B<TIP>: See Appendix 1 for tips on removing the leading spaces when
518 cutting and pasting example code from POD-based documents.
520 Then use the following command to build a C<myapp.db> SQLite database:
522 $ sqlite3 myapp.db < myapp01.sql
524 If you need to create the database more than once, you probably want to
525 issue the C<rm myapp.db> command to delete the database before you use
526 the C<sqlite3 myapp.db < myapp01.sql> command.
528 Once the C<myapp.db> database file has been created and initialized, you
529 can use the SQLite command line environment to do a quick dump of the
534 Enter ".help" for instructions
535 sqlite> select * from books;
536 1|CCSP SNRS Exam Certification Guide|5
537 2|TCP/IP Illustrated, Volume 1|5
538 3|Internetworking with TCP/IP Vol.1|4
540 5|Designing with Web Standards|5
546 $ sqlite3 myapp.db "select * from books"
547 1|CCSP SNRS Exam Certification Guide|5
548 2|TCP/IP Illustrated, Volume 1|5
549 3|Internetworking with TCP/IP Vol.1|4
551 5|Designing with Web Standards|5
553 As with most other SQL tools, if you are using the full "interactive"
554 environment you need to terminate your SQL commands with a ";" (it's not
555 required if you do a single SQL statement on the command line). Use
556 ".q" to exit from SQLite from the SQLite interactive mode and return to
557 your OS command prompt.
560 =head1 DATABASE ACCESS WITH C<DBIx::Class>
562 Catalyst can be used with virtually any form of persistent datastore
563 available via Perl. For example,
564 L<Catalyst::Model::DBI|Catalyst::Model::DBI> can be used to
565 easily access databases through the traditional Perl C<DBI> interface.
566 However, most Catalyst applications use some form of ORM technology to
567 automatically create and save model objects as they are used. Although
568 Tony Bowden's L<Class::DBI|Class::DBI> has been a popular choice
569 in the past, Matt Trout's L<DBIx::Class|DBIx::Class> (abbreviated
570 as "DBIC") has rapidly emerged as the Perl-based ORM technology of choice.
571 Most new Catalyst applications rely on DBIC, as will this tutorial.
573 =head2 Create a Dynamic DBIC Model
575 Use the C<create=dynamic> model helper option to build a model that
576 dynamically reads your database structure every time the application
579 $ script/myapp_create.pl model MyAppDB DBIC::Schema MyApp::Schema::MyAppDB create=dynamic dbi:SQLite:myapp.db
580 exists "/home/me/MyApp/script/../lib/MyApp/Model"
581 exists "/home/me/MyApp/script/../t"
582 created "/home/me/MyApp/script/../lib/MyApp/Schema"
583 created "/home/me/MyApp/script/../lib/MyApp/Schema/MyAppDB.pm"
584 created "/home/me/MyApp/script/../lib/MyApp/Model/MyAppDB.pm"
585 created "/home/me/MyApp/script/../t/model_MyAppDB.t"
588 C<MyAppDB> is the name of the model class to be created by the helper in
589 C<lib/MyApp/Model> (Catalyst has a separate directory under C<lib/MyApp>
590 for each of the three parts of MVC: C<Model>, C<View>, and C<Controller>
591 [although older Catalyst applications often use the directories C<M>,
592 C<V>, and C<C>]). C<DBIC::Schema> is the type of the model to create.
593 C<MyApp::Schema::MyAppDB> is the name of the DBIC schema file written to
594 C<lib/MyApp/Schema/MyAppDB.pm>. Because we specified C<create=dynamic>
595 to the helper, it use L<DBIx::Class::Schema::Loader> to dynamically load
596 the schema information from the database every time the application
597 starts. And finally, C<dbi:SQLite:myapp.db> is the standard DBI connect
598 string for use with SQLite.
600 B<NOTE>: Although the C<create=dynamic> option to the DBIC helper
601 makes for a nifty demonstration, is not suitable for real world
602 applications. Moreover, it may not be supported in future versions of
603 DBIC. After this demonstration, please use the C<create=static>
604 option that we switch to below.
607 =head1 RUN THE APPLICATION
609 First, let's enable an environment variable option that causes
610 DBIx::Class to dump the SQL statements it's using to access the database
611 (this option can provide extremely helpful troubleshooting information):
613 $ export DBIC_TRACE=1
615 This assumes you are using BASH as your shell -- adjust accordingly if
616 you are using a different shell (for example, under tcsh, use
617 C<setenv DBIC_TRACE 1>).
619 B<NOTE>: You can also set this in your code using
620 C<$class-E<gt>storage-E<gt>debug(1);>. See
621 L<DBIx::Class::Manual::Troubleshooting> for details (including options
622 to log to file instead of displaying to the Catalyst development server
625 Then run the Catalyst "demo server" script:
627 $ script/myapp_server.pl
629 Your development server log output should display something like:
631 $script/myapp_server.pl
632 [debug] Debug messages enabled
633 [debug] Loaded plugins:
634 .----------------------------------------------------------------------------.
635 | Catalyst::Plugin::ConfigLoader 0.17 |
636 | Catalyst::Plugin::StackTrace 0.06 |
637 | Catalyst::Plugin::Static::Simple 0.20 |
638 '----------------------------------------------------------------------------'
640 [debug] Loaded dispatcher "Catalyst::Dispatcher"
641 [debug] Loaded engine "Catalyst::Engine::HTTP"
642 [debug] Found home "/home/me/MyApp"
643 [debug] Loaded Config "/home/me/MyApp/myapp.yml"
644 [debug] Loaded components:
645 .-----------------------------------------------------------------+----------.
647 +-----------------------------------------------------------------+----------+
648 | MyApp::Controller::Books | instance |
649 | MyApp::Controller::Root | instance |
650 | MyApp::Model::MyAppDB | instance |
651 | MyApp::Model::MyAppDB::Authors | class |
652 | MyApp::Model::MyAppDB::BookAuthors | class |
653 | MyApp::Model::MyAppDB::Books | class |
654 | MyApp::View::TT | instance |
655 '-----------------------------------------------------------------+----------'
657 [debug] Loaded Private actions:
658 .----------------------+--------------------------------------+--------------.
659 | Private | Class | Method |
660 +----------------------+--------------------------------------+--------------+
661 | /default | MyApp::Controller::Root | default |
662 | /end | MyApp::Controller::Root | end |
663 | /books/index | MyApp::Controller::Books | index |
664 | /books/list | MyApp::Controller::Books | list |
665 '----------------------+--------------------------------------+--------------'
667 [debug] Loaded Path actions:
668 .-------------------------------------+--------------------------------------.
670 +-------------------------------------+--------------------------------------+
671 | /books/list | /books/list |
672 '-------------------------------------+--------------------------------------'
674 [info] MyApp powered by Catalyst 5.7011
675 You can connect to your server at http://localhost:3000
677 B<NOTE>: Be sure you run the C<script/myapp_server.pl> command from
678 the 'base' directory of your application, not inside the C<script>
679 directory itself or it will not be able to locate the C<myapp.db>
680 database file. You can use a fully qualified or a relative path to
681 locate the database file, but we did not specify that when we ran the
682 model helper earlier.
684 Some things you should note in the output above:
690 Catalyst::Model::DBIC::Schema dynamically created three model classes,
691 one to represent each of the three tables in our database
692 (C<MyApp::Model::MyAppDB::Authors>, C<MyApp::Model::MyAppDB::BookAuthors>,
693 and C<MyApp::Model::MyAppDB::Books>).
697 The "list" action in our Books controller showed up with a path of
702 Point your browser to L<http://localhost:3000> and you should still get
703 the Catalyst welcome page.
705 Next, to view the book list, change the URL in your browser to
706 L<http://localhost:3000/books/list>. You should get a list of the five
707 books loaded by the C<myapp01.sql> script above, with TTSite providing
708 the formatting for the very simple output we generated in our template.
709 The rating for each book should appear on each row.
711 Also notice in the output of the C<script/myapp_server.pl> that DBIC
712 used the following SQL to retrieve the data:
714 SELECT me.id, me.title, me.rating FROM books me
716 because we enabled DBIC_TRACE.
718 You now the beginnings of a simple but workable web application.
719 Continue on to future sections and we will develop the application
723 =head1 A STATIC DATABASE MODEL WITH C<DBIx::Class>
725 =head2 Create Static DBIC Schema Files
727 Unlike the previous section where we had DBIC automatically discover the
728 structure of the database every time the application started, here we
729 will use static schema files for more control. This is typical of most
730 "real world" applications.
732 One option would be to create a separate schema file for each table in
733 the database, however, lets use the same L<DBIx::Class::Schema::Loader>
734 used earlier with C<create=dynamic> to build the static files for us.
735 First, lets remove the schema file created in Part 2:
737 $ rm lib/MyApp/Schema/MyAppDB.pm
739 Now regenerate the schema using the C<create=static> option:
741 $ script/myapp_create.pl model MyAppDB DBIC::Schema MyApp::Schema::MyAppDB create=static dbi:SQLite:myapp.db
742 exists "/home/me/MyApp/script/../lib/MyApp/Model"
743 exists "/home/me/MyApp/script/../t"
744 Dumping manual schema for MyApp::Schema::MyAppDB to directory /home/me/MyApp/script/../lib ...
745 Schema dump completed.
746 exists "/home/me/MyApp/script/../lib/MyApp/Model/MyAppDB.pm"
748 We could have also deleted C<lib/MyApp/Model/MyAppDB.pm>, but it would
749 have regenerated the same file (note the C<exists> in the output above).
750 If you take a look at C<lib/MyApp/Model/MyAppDB.pm>, it simply contains
751 a reference to the actual schema file in C<lib/MyApp/Schema/MyAppDB.pm>
752 along with the database connect string.
754 If you look in the C<lib/MyApp/Schema> directory, you will find that
755 C<MyAppDB.pm> is no longer using L<DBIx::Class::Schema::Loader> as its
756 base class (L<DBIx::Class::Schema::Loader> is only being used by the
757 helper to load the schema once and then create the static files for us)
758 and that it only contains a call to the C<load_classes> method. You
759 will also find that C<lib/MyApp/Schema> contains a C<MyAppDB>
760 subdirectory, with one file inside this directory for each of the tables
761 in our simple database (C<Authors.pm>, C<BookAuthors.pm>, and
762 C<Books.pm>). These three files were created based on the information
763 found by L<DBIx::Class::Schema::Loader> as the helper ran.
765 The idea with all of the files created under C<lib/MyApp/Schema> by the
766 C<create=static> option is to only edit the files below the C<# DO NOT
767 MODIFY THIS OR ANYTHING ABOVE!> warning. If you place all of your
768 changes below that point in the file, you can regenerate the
769 auto-generated information at the top of each file should your database
770 structure get updated.
772 Also note the "flow" of the model information across the various files
773 and directories. Catalyst will initially load the model from
774 C<lib/MyApp/Model/MyAppDB.pm>. This file contains a reference to
775 C<lib/MyApp/Schema/MyAppDB.pm>, so that file is loaded next. Finally,
776 the call to C<load_classes> in that file will load each of the
777 table-specific "results source" files from the C<lib/MyApp/Schema/MyAppDB>
778 subdirectory. These three table-specific DBIC schema files will then be
779 used to create three table-specific Catalyst models every time the
780 application starts (you can see these three model files listed in
781 the debug output generated when you launch the application).
784 =head2 Updating the Generated DBIC Schema Files
787 Let's manually add some relationship information to the auto-generated
788 schema files. First edit C<lib/MyApp/Schema/MyAppDB/Books.pm> and
789 add the following text below the C<# You can replace this text...>
798 # 1) Name of relationship, DBIC will create accessor with this name
799 # 2) Name of the model class referenced by this relationship
800 # 3) Column name in *foreign* table
801 __PACKAGE__->has_many(book_authors => 'MyApp::Schema::MyAppDB::BookAuthors', 'book_id');
805 # 1) Name of relationship, DBIC will create accessor with this name
806 # 2) Name of has_many() relationship this many_to_many() is shortcut for
807 # 3) Name of belongs_to() relationship in model class of has_many() above
808 # You must already have the has_many() defined to use a many_to_many().
809 __PACKAGE__->many_to_many(authors => 'book_authors', 'author');
812 B<Note:> Be careful to put this code I<above> the C<1;> at the end of the
813 file. As with any Perl package, we need to end the last line with
814 a statement that evaluates to C<true>. This is customarily done with
815 C<1;> on a line by itself.
817 This code defines both a C<has_many> and a C<many_to_many> relationship.
818 The C<many_to_many> relationship is optional, but it makes it easier to
819 map a book to its collection of authors. Without it, we would have to
820 "walk" though the C<book_authors> table as in C<$book-E<gt>book_authors-
821 E<gt>first-E<gt>author-E<gt>last_name> (we will see examples on how to
822 use DBIC objects in your code soon, but note that because C<$book-
823 E<gt>book_authors> can return multiple authors, we have to use C<first>
824 to display a single author). C<many_to_many> allows us to use the
825 shorter C<$book-E<gt>authors-E<gt>first-E<gt>last_name>. Note that you
826 cannot define a C<many_to_many> relationship without also having the
827 C<has_many> relationship in place.
829 Then edit C<lib/MyApp/Schema/MyAppDB/Authors.pm> and add relationship
830 information as follows (again, be careful to put in above the C<1;> but
831 below the C<# DO NOT MODIFY THIS OR ANYTHING ABOVE!> comment):
839 # 1) Name of relationship, DBIC will create accessor with this name
840 # 2) Name of the model class referenced by this relationship
841 # 3) Column name in *foreign* table
842 __PACKAGE__->has_many(book_author => 'MyApp::Schema::MyAppDB::BookAuthors', 'author_id');
846 # 1) Name of relationship, DBIC will create accessor with this name
847 # 2) Name of has_many() relationship this many_to_many() is shortcut for
848 # 3) Name of belongs_to() relationship in model class of has_many() above
849 # You must already have the has_many() defined to use a many_to_many().
850 __PACKAGE__->many_to_many(books => 'book_author', 'book');
852 Finally, do the same for the "join table,"
853 C<lib/MyApp/Schema/MyAppDB/BookAuthors.pm>:
861 # 1) Name of relationship, DBIC will create accessor with this name
862 # 2) Name of the model class referenced by this relationship
863 # 3) Column name in *this* table
864 __PACKAGE__->belongs_to(book => 'MyApp::Schema::MyAppDB::Books', 'book_id');
868 # 1) Name of relationship, DBIC will create accessor with this name
869 # 2) Name of the model class referenced by this relationship
870 # 3) Column name in *this* table
871 __PACKAGE__->belongs_to(author => 'MyApp::Schema::MyAppDB::Authors', 'author_id');
874 =head1 RUN THE APPLICATION
876 Run the Catalyst "demo server" script with the C<DBIC_TRACE> option
877 (it might still be enabled from earlier in the tutorial, but here
878 is an alternate way to specify the option just in case):
880 $ DBIC_TRACE=1 script/myapp_server.pl
882 Make sure that the application loads correctly and that you see the
883 three dynamically created model class (one for each of the
884 table-specific schema classes we created).
886 Then hit the URL L<http://localhost:3000/books/list> and be sure that
887 the book list is displayed.
890 =head1 RUNNING THE APPLICATION FROM THE COMMAND LINE
892 In some situations, it can be useful to run your application and
893 display a page without using a browser. Catalyst lets you do this
894 using the C<scripts/myapp_test.pl> script. Just supply the URL you
895 wish to display and it will run that request through the normal
896 controller dispatch logic and use the appropriate view to render the
897 output (obviously, complex pages may dump a lot of text to your
898 terminal window). For example, if you type:
900 $ script/myapp_test.pl "/books/list"
902 You should get the same text as if you visited
903 L<http://localhost:3000/books/list> with the normal development server
904 and asked your browser to view the page source.
907 =head1 UPDATING THE VIEW
909 Let's add a new column to our book list page that takes advantage of
910 the relationship information we manually added to our schema files
911 in the previous section. Edit C<root/src/books/list.tt2> add add the
912 following code below the existing table cell that contains
913 C<book.rating> (IOW, add a new table cell below the existing two
917 [% # First initialize a TT variable to hold a list. Then use a TT FOREACH -%]
918 [% # loop in 'side effect notation' to load just the last names of the -%]
919 [% # authors into the list. Note that the 'push' TT vmethod does not -%]
920 [% # a value, so nothing will be printed here. But, if you have something -%]
921 [% # in TT that does return a method and you don't want it printed, you -%]
922 [% # can: 1) assign it to a bogus value, or 2) use the CALL keyword to -%]
923 [% # call it and discard the return value. -%]
925 tt_authors.push(author.last_name) FOREACH author = book.authors %]
926 [% # Now use a TT 'virtual method' to display the author count in parens -%]
927 [% # Note the use of the TT filter "| html" to escape dangerous characters -%]
928 ([% tt_authors.size | html %])
929 [% # Use another TT vmethod to join & print the names & comma separators -%]
930 [% tt_authors.join(', ') | html %]
933 Then hit C<Ctrl+R> in your browser (not that you don't need to reload
934 the development server or use the C<-r> option when updating TT
935 templates) and you should now the the number of authors each book and
936 a comma-separated list of the author's last names.
938 If you are still running the development server with C<DBIC_TRACE>
939 enabled, you should also now see five more C<SELECT> statements in the
940 debug output (one for each book as the authors are being retrieved by
943 Also note that we are using "| html", a type of TT filter, to escape
944 characters such as E<lt> and E<gt> to < and > and avoid various
945 types of dangerous hacks against your application. In a real
946 application, you would probably want to put "| html" at the end of
947 every field where a user has control over the information that can
948 appear in that field (and can therefore inject markup or code if you
949 don't "neutralize" those fields). In addition to "| html", Template
950 Toolkit has a variety of other useful filters that can found in the
951 documentation for L<Template::Filters|Template::Filters>.
954 =head2 Using C<RenderView> for the Default View
956 B<NOTE: The rest of this part of the tutorial is optional. You can
957 skip to Part 4, L<Basic CRUD|Catalyst::Manual::Tutorial::BasicCRUD>,
960 Once your controller logic has processed the request from a user, it
961 forwards processing to your view in order to generate the appropriate
962 response output. Catalyst uses
963 L<Catalyst::Action::RenderView|Catalyst::Action::RenderView> by
964 default to automatically performs this operation. If you look in
965 C<lib/MyApp/Controller/Root.pm>, you should see the empty
966 definition for the C<sub end> method:
968 sub end : ActionClass('RenderView') {}
970 The following bullet points provide a quick overview of the
971 C<RenderView> process:
977 C<Root.pm> is designed to hold application-wide logic.
981 At the end of a given user request, Catalyst will call the most specific
982 C<end> method that's appropriate. For example, if the controller for a
983 request has an C<end> method defined, it will be called. However, if
984 the controller does not define a controller-specific C<end> method, the
985 "global" C<end> method in C<Root.pm> will be called.
989 Because the definition includes an C<ActionClass> attribute, the
990 L<Catalyst::Action::RenderView|Catalyst::Action::RenderView> logic
991 will be executed B<after> any code inside the definition of C<sub end>
992 is run. See L<Catalyst::Manual::Actions|Catalyst::Manual::Actions>
993 for more information on C<ActionClass>.
997 Because C<sub end> is empty, this effectively just runs the default
998 logic in C<RenderView>. However, you can easily extend the
999 C<RenderView> logic by adding your own code inside the empty method body
1000 (C<{}>) created by the Catalyst Helpers when we first ran the
1001 C<catalyst.pl> to initialize our application. See
1002 L<Catalyst::Action::RenderView|Catalyst::Action::RenderView> for more
1003 detailed information on how to extended C<RenderView> in C<sub end>.
1008 =head2 Using The Default Template Name
1010 By default, C<Catalyst::View::TT> will look for a template that uses the
1011 same name as your controller action, allowing you to save the step of
1012 manually specifying the template name in each action. For example, this
1013 would allow us to remove the
1014 C<$c-E<gt>stash-E<gt>{template} = 'books/list.tt2';> line of our
1015 C<list> action in the Books controller. Open
1016 C<lib/MyApp/Controller/Books.pm> in your editor and comment out this line
1017 to match the following (only the C<$c-E<gt>stash-E<gt>{template}> line
1022 Fetch all book objects and pass to books/list.tt2 in stash to be displayed
1027 # Retrieve the usual Perl OO '$self' for this object. $c is the Catalyst
1028 # 'Context' that's used to 'glue together' the various components
1029 # that make up the application
1030 my ($self, $c) = @_;
1032 # Retrieve all of the book records as book model objects and store in the
1033 # stash where they can be accessed by the TT template
1034 $c->stash->{books} = [$c->model('MyAppDB::Books')->all];
1036 # Set the TT template to use. You will almost always want to do this
1037 # in your action methods (actions methods respond to user input in
1038 # your controllers).
1039 #$c->stash->{template} = 'books/list.tt2';
1042 C<Catalyst::View::TT> defaults to looking for a template with no
1043 extension. In our case, we need to override this to look for an
1044 extension of C<.tt2>. Open C<lib/MyApp/View/TT.pm> and add the
1045 C<TEMPLATE_EXTENSION> definition as follows:
1047 __PACKAGE__->config({
1048 CATALYST_VAR => 'Catalyst',
1050 MyApp->path_to( 'root', 'src' ),
1051 MyApp->path_to( 'root', 'lib' )
1053 PRE_PROCESS => 'config/main',
1054 WRAPPER => 'site/wrapper',
1055 ERROR => 'error.tt2',
1057 TEMPLATE_EXTENSION => '.tt2',
1060 You should now be able to restart the development server as per the
1061 previous section and access the L<http://localhost:3000/books/list>
1064 B<NOTE:> Please note that if you use the default template technique,
1065 you will B<not> be able to use either the C<$c-E<gt>forward> or
1066 the C<$c-E<gt>detach> mechanisms (these are discussed in Part 2 and
1067 Part 9 of the Tutorial).
1070 =head2 Return To A Manually-Specified Template
1072 In order to be able to use C<$c-E<gt>forward> and C<$c-E<gt>detach>
1073 later in the tutorial, you should remove the comment from the
1074 statement in C<sub list> in C<lib/MyApp/Controller/Books.pm>:
1076 $c->stash->{template} = 'books/list.tt2';
1078 Then delete the C<TEMPLATE_EXTENSION> line in
1079 C<lib/MyApp/View/TT.pm>.
1081 You should then be able to restart the development server and
1082 access L<http://localhost:3000/books/list> in the same manner as
1083 with earlier sections.
1088 Kennedy Clark, C<hkclark@gmail.com>
1090 Please report any errors, issues or suggestions to the author. The
1091 most recent version of the Catalyst Tutorial can be found at
1092 L<http://dev.catalyst.perl.org/repos/Catalyst/trunk/Catalyst-Manual/lib/Catalyst/Manual/Tutorial/>.
1094 Copyright 2006, Kennedy Clark, under Creative Commons License
1095 (L<http://creativecommons.org/licenses/by-nc-sa/2.5/>).