Update license
[catagits/Catalyst-Manual.git] / lib / Catalyst / Manual / Tutorial / MoreCatalystBasics.pod
CommitLineData
3533daff 1=head1 NAME
2
3Catalyst::Manual::Tutorial::MoreCatalystBasics - Catalyst Tutorial - Part 3: More Catalyst Application Development Basics
4
5
6=head1 OVERVIEW
7
8This is B<Part 3 of 10> for the Catalyst tutorial.
9
10L<Tutorial Overview|Catalyst::Manual::Tutorial>
11
12=over 4
13
14=item 1
15
16L<Introduction|Catalyst::Manual::Tutorial::Intro>
17
18=item 2
19
20L<Catalyst Basics|Catalyst::Manual::Tutorial::CatalystBasics>
21
22=item 3
23
24B<More Catalyst Basics>
25
26=item 4
27
28L<Basic CRUD|Catalyst::Manual::Tutorial::BasicCRUD>
29
30=item 5
31
32L<Authentication|Catalyst::Manual::Tutorial::Authentication>
33
34=item 6
35
36L<Authorization|Catalyst::Manual::Tutorial::Authorization>
37
38=item 7
39
40L<Debugging|Catalyst::Manual::Tutorial::Debugging>
41
42=item 8
43
44L<Testing|Catalyst::Manual::Tutorial::Testing>
45
46=item 9
47
48L<Advanced CRUD|Catalyst::Manual::Tutorial::AdvancedCRUD>
49
50=item 10
51
52L<Appendices|Catalyst::Manual::Tutorial::Appendices>
53
54=back
55
56
57=head1 DESCRIPTION
58
59This part of the tutorial builds on the work done in Part 2 to explore
60some features that are more typical of "real world" web applications.
61From this part of the tutorial onward, we will be building a simple
62book database application. Although the application will be too
63limited to be of use to anyone, it should provide a basic environment
64where we can explore a variety of features used in virtually all web
65applications.
66
67You can checkout the source code for this example from the catalyst
68subversion repository as per the instructions in
69L<Catalyst::Manual::Tutorial::Intro>
70
71
72=head1 CREATE A NEW APPLICATION
73
74The remainder of the tutorial will build an application call C<MyApp>.
75Use the Catalyst C<catalyst.pl> script to initialize the framework for
76an application called C<MyApp> (make sure you aren't still inside the
77directory of the C<Hello> application from the previous part of the
78tutorial):
79
80 $ catalyst.pl MyApp
81 created "MyApp"
82 created "MyApp/script"
83 created "MyApp/lib"
84 created "MyApp/root"
85 ...
86 created "MyApp/script/myapp_create.pl"
87 $ cd MyApp
88
89This creates a similar skeletal structure to what we saw in Part 2 of
8a7c5151 90the tutorial, except with C<MyApp> and C<myapp> substituted for
3533daff 91C<Hello> and C<hello>.
92
93
94=head1 EDIT THE LIST OF CATALYST PLUGINS
95
96One of the greatest benefits of Catalyst is that it has such a large
97library of plugins available. Plugins are used to seamlessly integrate
98existing Perl modules into the overall Catalyst framework. In general,
99they do this by adding additional methods to the C<context> object
100(generally written as C<$c>) that Catalyst passes to every component
101throughout the framework.
102
103By default, Catalyst enables three plugins/flags:
104
105=over 4
106
107=item *
108
109C<-Debug> Flag
110
111Enables the Catalyst debug output you saw when we started the
112C<script/myapp_server.pl> development server earlier. You can remove
79a529cc 113this item when you place your application into production.
3533daff 114
115As you may have noticed, C<-Debug> is not a plugin, but a I<flag>.
116Although most of the items specified on the C<use Catalyst> line of your
117application class will be plugins, Catalyst supports a limited number of
118flag options (of these, C<-Debug> is the most common). See the
119documentation for C<Catalyst.pm> to get details on other flags
120(currently C<-Engine>, C<-Home>, and C<-Log>).
121
122If you prefer, you can use the C<$c-E<gt>debug> method to enable debug
123messages.
124
125B<TIP>: Depending on your needs, it can be helpful to permanently
126remove C<-Debug> from C<lib/MyApp.pm> and then use the C<-d> option
127to C<script/myapp_server.pl> to re-enable it just for the development
128server. We will not be using that approach in the tutorial, but feel
129free to make use of it in your own projects.
130
131=item *
132
133L<Catalyst::Plugin::ConfigLoader|Catalyst::Plugin::ConfigLoader>
134
135C<ConfigLoader> provides an automatic way to load configurable
c010ae0d 136parameters for your application from a central
137L<Config::General|Config::General> file (versus having the values
138hard-coded inside your Perl modules). Config::General uses syntax
139very similar to Apache configuration files. We will see how to use
140this feature of Catalyst during the authentication and authorization
141sections (Part 5 and Part 6).
3533daff 142
d0496197 143B<IMPORTANT NOTE:> If you are following along in Ubuntu 8.04 or
056394af 144otherwise using a version of L<Catalyst::Devel|Catalyst::Devel> prior
145to version 1.06, you need to be aware that Catalyst changed from a
146default format of YAML to the more straightforward C<Config::General>
147format. Because Catalyst has long supported both formats, this
148tutorial will simply use a configuration file called C<myapp.conf>
79a529cc 149instead of C<myapp.yml> and Catalyst will automatically use the new
056394af 150format. Just be aware that earlier versions of Catalyst will still
151create the C<myapp.yml> file and that you will need to B<remove
152C<myapp.yml>> and create a new C<myapp.conf> file by hand, but
153otherwise this transition is very painless. The default contents of
154C<myapp.conf> should only consist of one line: C<name MyApp>. Also be
155aware that you can continue to use any format supported by
156L<Catalyst::Plugin::ConfigLoader|Catalyst::Plugin::ConfigLoader> and
157L<Config::Any|Config::Any>, including YAML -- Catalyst will
158automatically look for any of the supported configuration file
159formats.
15e1d0b2 160
d0496197 161B<TIP>: This script can be useful for converting between configuration
15e1d0b2 162formats:
163
164 perl -Ilib -e 'use MyApp; use Config::General;
165 Config::General->new->save_file("myapp.conf", MyApp->config);'
166
d0496197 167B<NOTE:> The default C<myapp.conf> should look like:
168
169 name MyApp
15e1d0b2 170
3533daff 171=item *
172
173L<Catalyst::Plugin::Static::Simple|Catalyst::Plugin::Static::Simple>
174
175C<Static::Simple> provides an easy method of serving static content such
176as images and CSS files under the development server.
177
178=back
179
180To modify the list of plugins, edit C<lib/MyApp.pm> (this file is
181generally referred to as your I<application class>) and delete the line
182with:
183
b411df01 184 use Catalyst qw/-Debug ConfigLoader Static::Simple/;
3533daff 185
186Replace it with:
187
b411df01 188 use Catalyst qw/
189 -Debug
190 ConfigLoader
191 Static::Simple
192
193 StackTrace
194 /;
3533daff 195
196This tells Catalyst to start using one new plugin:
197
198=over 4
199
200=item *
201
202L<Catalyst::Plugin::StackTrace|Catalyst::Plugin::StackTrace>
203
204Adds a stack trace to the standard Catalyst "debug screen" (this is the
205screen Catalyst sends to your browser when an error occurs).
206
207Note: L<StackTrace|Catalyst::Plugin::StackTrace> output appears in your
208browser, not in the console window from which you're running your
209application, which is where logging output usually goes.
210
cca5cd98 211B<Note:> You will want to disable
212L<StackTrace|Catalyst::Plugin::StackTrace> before you put your
213application into production, but it can be helpful during development.
214
3533daff 215=back
216
217Note that when specifying plugins on the C<use Catalyst> line, you can
218omit C<Catalyst::Plugin::> from the name. Additionally, you can spread
219the plugin names across multiple lines as shown here, or place them all
220on one (or more) lines as with the default configuration.
221
222
223=head1 CREATE A CATALYST CONTROLLER
224
225As discussed earlier, controllers are where you write methods that
226interact with user input. Typically, controller methods respond to
227C<GET> and C<POST> messages from the user's web browser.
228
229Use the Catalyst C<create> script to add a controller for book-related
230actions:
231
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"
237
238Then edit C<lib/MyApp/Controller/Books.pm> and add the following method
239to the controller:
240
241 =head2 list
242
243 Fetch all book objects and pass to books/list.tt2 in stash to be displayed
244
245 =cut
246
247 sub list : Local {
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
251 my ($self, $c) = @_;
252
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
d0496197 255 $c->stash->{books} = [$c->model('DB::Books')->all];
3533daff 256
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
259 # your controllers).
260 $c->stash->{template} = 'books/list.tt2';
261 }
262
263B<Note:> This won't actually work yet since you haven't set up your
d0496197 264model yet. We will be covering the model soon.
3533daff 265
266B<Note:> Programmers experienced with object-oriented Perl should
267recognize C<$self> as a reference to the object where this method was
268called. On the other hand, C<$c> will be new to many Perl programmers
269who have not used Catalyst before (it's sometimes written as
270C<$context>). The Context object is automatically passed to all
271Catalyst components. It is used to pass information between
272components and provide access to Catalyst and plugin functionality.
273
d0496197 274B<TIP>: You may see the C<$c-E<gt>model('DB::Book')> used above
0c51850e 275written as C<$c-E<gt>model('DB')-E<gt>resultset('Book')>. The two
3533daff 276are equivalent.
277
278B<Note:> Catalyst actions are regular Perl methods, but they make use
279of Nicholas Clark's C<attributes> module (that's the C<: Local> next
280to the C<sub list> in the code above) to provide additional
281information to the Catalyst dispatcher logic. Many newer Catalyst
ae492862 282applications are switching to the use of "Literal" C<:Path> actions
3533daff 283and C<Args> attribute in lieu of C<: Local> and C<: Private>. For
ae492862 284example, C<sub any_method :Path :Args(0)> can be used instead of
3533daff 285C<sub index :Private> (because no path was supplied to C<Path> it
286matches the "empty" URL in the namespace of that module... the same
ae492862 287thing C<sub index> would do) or C<sub list :Path('list') :Args(0)>
3533daff 288could be used instead of the C<sub list : Local> above (the C<list>
289argument to C<Path> would make it match on the URL C<list> under
290C<books>, the namespace of the current module). See "Action Types" in
291L<Catalyst::Manual::Intro|Catalyst::Manual::Intro> as well as Part 5
292of this tutorial (Authentication) for additional information. Another
293popular but more advanced feature is C<Chained> actions that allow a
294single URL to "chain together" multiple action method calls, each with
295an appropriate number of arguments (see
296L<Catalyst::DispatchType::Chained|Catalyst::DispatchType::Chained>
297for details).
298
299
300=head1 CATALYST VIEWS
301
302As mentioned in Part 2 of the tutorial, views are where you render
303output, typically for display in the user's web browser, but also
304possibly using other display output- generation systems. As with
305virtually every aspect of Catalyst, options abound when it comes to
306the specific view technology you adopt inside your application.
307However, most Catalyst applications use the Template Toolkit, known as
d0496197 308TT (for more information on TT, see
309L<http://www.template-toolkit.org>). Other popular view technologies
310include Mason (L<http://www.masonhq.com> and
311L<http://www.masonbook.com>) and L<HTML::Template>
0c51850e 312(L<http://html-template.sourceforge.net>).
3533daff 313
314=head2 Create a Catalyst View Using C<TTSite>
315
316When using TT for the Catalyst view, there are two main helper scripts:
317
318=over 4
319
320=item *
321
322L<Catalyst::Helper::View::TT|Catalyst::Helper::View::TT>
323
324=item *
325
326L<Catalyst::Helper::View::TTSite|Catalyst::Helper::View::TTSite>
327
328=back
329
330Both are similar, but C<TT> merely creates the C<lib/MyApp/View/TT.pm>
331file and leaves the creation of any hierarchical template organization
332entirely up to you. (It also creates a C<t/view_TT.t> file for testing;
333test cases will be discussed in Part 8). The C<TTSite> helper creates a
334modular and hierarchical view layout with separate Template Toolkit (TT)
335files for common header and footer information, configuration values, a
336CSS stylesheet, and more.
337
338While TTSite is useful to bootstrap a project, we recommend that
339unless you know what you're doing or want to pretty much use the
340supplied templates as is, that you use the plain Template Toolkit view
341when starting a project from scratch. This is because TTSite can be
342tricky to customize. Additionally TT contains constructs that you
343need to learn yourself if you're going to be a serious user of TT.
344Our experience suggests that you're better off learning these from
345scratch. We use TTSite here precisely because it is useful for
346bootstrap/prototype purposes.
347
348Enter the following command to enable the C<TTSite> style of view
349rendering for this tutorial:
350
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"
356 ...
357 created "/home/me/MyApp/script/../root/src/ttsite.css"
358
359This puts a number of files in the C<root/lib> and C<root/src>
360directories that can be used to customize the look and feel of your
361application. Also take a look at C<lib/MyApp/View/TT.pm> for config
362values set by the C<TTSite> helper.
363
3533daff 364B<TIP>: When troubleshooting TT it can be helpful to enable variable
365C<DEBUG> options. You can do this in a Catalyst environment by adding
366a C<DEBUG> line to the C<__PACKAGE__->config> declaration in
367C<lib/MyApp/View/TT.pm>:
368
369 __PACKAGE__->config({
3533daff 370 ...
371 DEBUG => 'undef',
372 ...
373 });
374
375B<Note:> C<__PACKAGE__> is just a shorthand way of referencing the name
376of the package where it is used. Therefore, in C<TT.pm>,
377C<__PACKAGE__> is equivalent to C<TT>.
378
379There are a variety of options you can use, such as 'undef', 'all',
0c51850e 380'service', 'context', 'parser' and 'provider'. See
3533daff 381L<Template::Constants> for more information (remove the C<DEBUG_>
382portion of the name shown in the TT docs and convert to lower case
383for use inside Catalyst).
384
385B<NOTE:> B<Please be sure to disable TT debug options before
386continuing the tutorial> (especially the 'undef' option -- leaving
387this enabled will conflict with several of the conventions used
388by this tutorial and TTSite to leave some variables undefined
389on purpose).
390
391
392=head2 Globally Customize Every View
393
394When using TTSite, files in the subdirectories of C<root/lib> can be
395used to make changes that will appear in every view. For example, to
396display optional status and error messages in every view, edit
397C<root/lib/site/layout>, updating it to match the following (the two HTML
398C<span> elements are new):
399
400 <div id="header">[% PROCESS site/header %]</div>
401
402 <div id="content">
403 <span class="message">[% status_msg %]</span>
404 <span class="error">[% error_msg %]</span>
405 [% content %]
406 </div>
407
408 <div id="footer">[% PROCESS site/footer %]</div>
409
410If we set either message in the Catalyst stash (e.g.,
411C<$c-E<gt>stash-E<gt>{status_msg} = 'Request was successful!'>) it will
412be displayed whenever any view used by that request is rendered. The
413C<message> and C<error> CSS styles are automatically defined in
414C<root/src/ttsite.css> and can be customized to suit your needs.
415
416B<Note:> The Catalyst stash only lasts for a single HTTP request. If
417you need to retain information across requests you can use
418L<Catalyst::Plugin::Session|Catalyst::Plugin::Session> (we will use
419Catalyst sessions in the Authentication part of the tutorial).
420
421
422=head2 Create a TT Template Page
423
424To add a new page of content to the TTSite view hierarchy, just create a
425new C<.tt2> file in C<root/src>. Only include HTML markup that goes
426inside the HTML <body> and </body> tags, TTSite will use the contents of
427C<root/lib/site> to add the top and bottom.
428
429First create a directory for book-related TT templates:
430
431 $ mkdir root/src/books
432
433Then create C<root/src/books/list.tt2> in your editor and enter:
434
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. -%]
439
440 [% # Provide a title to root/lib/site/header -%]
441 [% META title = 'Book List' -%]
442
443 <table>
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 -%]
447 <tr>
448 <td>[% book.title %]</td>
449 <td>[% book.rating %]</td>
450 </tr>
451 [% END -%]
452 </table>
453
454As indicated by the inline comments above, the C<META title> line uses
455TT's META feature to provide a title to C<root/lib/site/header>.
a0c5188a 456Meanwhile, the C<FOREACH> loop iterates through each C<book> model
457object and prints the C<title> and C<rating> fields.
3533daff 458
459If you are new to TT, the C<[%> and C<%]> tags are used to delimit TT
460code. TT supports a wide variety of directives for "calling" other
461files, looping, conditional logic, etc. In general, TT simplifies the
462usual range of Perl operators down to the single dot (C<.>) operator.
463This applies to operations as diverse as method calls, hash lookups, and
464list index values (see
55beb65d 465L<http://search.cpan.org/perldoc?Template::Manual::Variables>
3533daff 466for details and examples). In addition to the usual C<Template> module
467Pod documentation, you can access the TT manual at
55beb65d 468L<http://search.cpan.org/perldoc?Template::Manual>.
3533daff 469
d0496197 470B<NOTE:> The C<TTSite> helper creates several TT files using an
3533daff 471extension of C<.tt2>. Most other Catalyst and TT examples use an
472extension of C<.tt>. You can use either extension (or no extension at
473all) with TTSite and TT, just be sure to use the appropriate extension
474for both the file itself I<and> the C<$c-E<gt>stash-E<gt>{template} =
475...> line in your controller. This document will use C<.tt2> for
476consistency with the files already created by the C<TTSite> helper.
477
478
479=head1 CREATE A SQLITE DATABASE
480
481In this step, we make a text file with the required SQL commands to
482create a database table and load some sample data. Open C<myapp01.sql>
483in your editor and enter:
484
485 --
486 -- Create a very simple database to hold book and author information
487 --
488 CREATE TABLE books (
489 id INTEGER PRIMARY KEY,
490 title TEXT ,
491 rating INTEGER
492 );
493 -- 'book_authors' is a many-to-many join table between books & authors
494 CREATE TABLE book_authors (
495 book_id INTEGER,
496 author_id INTEGER,
497 PRIMARY KEY (book_id, author_id)
498 );
499 CREATE TABLE authors (
500 id INTEGER PRIMARY KEY,
501 first_name TEXT,
502 last_name TEXT
503 );
504 ---
505 --- Load some sample data
506 ---
507 INSERT INTO books VALUES (1, 'CCSP SNRS Exam Certification Guide', 5);
508 INSERT INTO books VALUES (2, 'TCP/IP Illustrated, Volume 1', 5);
509 INSERT INTO books VALUES (3, 'Internetworking with TCP/IP Vol.1', 4);
510 INSERT INTO books VALUES (4, 'Perl Cookbook', 5);
511 INSERT INTO books VALUES (5, 'Designing with Web Standards', 5);
512 INSERT INTO authors VALUES (1, 'Greg', 'Bastien');
513 INSERT INTO authors VALUES (2, 'Sara', 'Nasseh');
514 INSERT INTO authors VALUES (3, 'Christian', 'Degu');
515 INSERT INTO authors VALUES (4, 'Richard', 'Stevens');
516 INSERT INTO authors VALUES (5, 'Douglas', 'Comer');
517 INSERT INTO authors VALUES (6, 'Tom', 'Christiansen');
518 INSERT INTO authors VALUES (7, 'Nathan', 'Torkington');
519 INSERT INTO authors VALUES (8, 'Jeffrey', 'Zeldman');
520 INSERT INTO book_authors VALUES (1, 1);
521 INSERT INTO book_authors VALUES (1, 2);
522 INSERT INTO book_authors VALUES (1, 3);
523 INSERT INTO book_authors VALUES (2, 4);
524 INSERT INTO book_authors VALUES (3, 5);
525 INSERT INTO book_authors VALUES (4, 6);
526 INSERT INTO book_authors VALUES (4, 7);
527 INSERT INTO book_authors VALUES (5, 8);
528
529B<TIP>: See Appendix 1 for tips on removing the leading spaces when
530cutting and pasting example code from POD-based documents.
531
532Then use the following command to build a C<myapp.db> SQLite database:
533
534 $ sqlite3 myapp.db < myapp01.sql
535
536If you need to create the database more than once, you probably want to
537issue the C<rm myapp.db> command to delete the database before you use
538the C<sqlite3 myapp.db < myapp01.sql> command.
539
540Once the C<myapp.db> database file has been created and initialized, you
541can use the SQLite command line environment to do a quick dump of the
542database contents:
543
544 $ sqlite3 myapp.db
545 SQLite version 3.4.2
546 Enter ".help" for instructions
547 sqlite> select * from books;
548 1|CCSP SNRS Exam Certification Guide|5
549 2|TCP/IP Illustrated, Volume 1|5
550 3|Internetworking with TCP/IP Vol.1|4
551 4|Perl Cookbook|5
552 5|Designing with Web Standards|5
553 sqlite> .q
554 $
555
556Or:
557
558 $ sqlite3 myapp.db "select * from books"
559 1|CCSP SNRS Exam Certification Guide|5
560 2|TCP/IP Illustrated, Volume 1|5
561 3|Internetworking with TCP/IP Vol.1|4
562 4|Perl Cookbook|5
563 5|Designing with Web Standards|5
564
565As with most other SQL tools, if you are using the full "interactive"
566environment you need to terminate your SQL commands with a ";" (it's not
567required if you do a single SQL statement on the command line). Use
568".q" to exit from SQLite from the SQLite interactive mode and return to
569your OS command prompt.
570
571
572=head1 DATABASE ACCESS WITH C<DBIx::Class>
573
574Catalyst can be used with virtually any form of persistent datastore
575available via Perl. For example,
576L<Catalyst::Model::DBI|Catalyst::Model::DBI> can be used to
577easily access databases through the traditional Perl C<DBI> interface.
578However, most Catalyst applications use some form of ORM technology to
579automatically create and save model objects as they are used. Although
580Tony Bowden's L<Class::DBI|Class::DBI> has been a popular choice
581in the past, Matt Trout's L<DBIx::Class|DBIx::Class> (abbreviated
582as "DBIC") has rapidly emerged as the Perl-based ORM technology of choice.
583Most new Catalyst applications rely on DBIC, as will this tutorial.
584
bb2dbfb8 585=head2 Create a dynamic DBIC Model
3533daff 586
bb2dbfb8 587Use the C<create=dynamic> model helper option to build a model that
3533daff 588dynamically reads your database structure every time the application
589starts:
590
d0496197 591 $ script/myapp_create.pl model DB DBIC::Schema MyApp::Schema create=dynamic dbi:SQLite:myapp.db
592 exists "/home/kclark/dev/MyApp/script/../lib/MyApp/Model"
593 exists "/home/kclark/dev/MyApp/script/../t"
594 exists "/home/kclark/dev/MyApp/script/../lib/MyApp"
595 created "/home/kclark/dev/MyApp/script/../lib/MyApp/Schema.pm"
596 created "/home/kclark/dev/MyApp/script/../lib/MyApp/Model/DB.pm"
597 created "/home/kclark/dev/MyApp/script/../t/model_DB.t"
3533daff 598
599
d0496197 600C<DB> is the name of the model class to be created by the helper in
3533daff 601C<lib/MyApp/Model> (Catalyst has a separate directory under C<lib/MyApp>
d0496197 602for each of the three parts of MVC: C<Model>, C<View>, and C<Controller>).
603C<DBIC::Schema> is the type of the model to create.
604C<MyApp::Schema> is the name of the DBIC schema file written to
605C<lib/MyApp/Schema.pm>. Because we specified C<create=dynamic>
3533daff 606to the helper, it use L<DBIx::Class::Schema::Loader> to dynamically load
607the schema information from the database every time the application
608starts. And finally, C<dbi:SQLite:myapp.db> is the standard DBI connect
609string for use with SQLite.
610
d0496197 611B<NOTE:> Although the C<create=dynamic> option to the DBIC helper
19c49089 612makes for a nifty demonstration, is only really suitable for very
613small applications. After this demonstration, you should almost always
614use the C<create=static> option that we switch to below.
dc9a0503 615
616
3533daff 617=head1 RUN THE APPLICATION
618
619First, let's enable an environment variable option that causes
620DBIx::Class to dump the SQL statements it's using to access the database
621(this option can provide extremely helpful troubleshooting information):
622
623 $ export DBIC_TRACE=1
624
625This assumes you are using BASH as your shell -- adjust accordingly if
626you are using a different shell (for example, under tcsh, use
627C<setenv DBIC_TRACE 1>).
628
d0496197 629B<NOTE:> You can also set this in your code using
3533daff 630C<$class-E<gt>storage-E<gt>debug(1);>. See
631L<DBIx::Class::Manual::Troubleshooting> for details (including options
632to log to file instead of displaying to the Catalyst development server
633log).
634
635Then run the Catalyst "demo server" script:
636
637 $ script/myapp_server.pl
638
639Your development server log output should display something like:
640
641 $script/myapp_server.pl
642 [debug] Debug messages enabled
643 [debug] Loaded plugins:
644 .----------------------------------------------------------------------------.
645 | Catalyst::Plugin::ConfigLoader 0.17 |
646 | Catalyst::Plugin::StackTrace 0.06 |
647 | Catalyst::Plugin::Static::Simple 0.20 |
648 '----------------------------------------------------------------------------'
649
650 [debug] Loaded dispatcher "Catalyst::Dispatcher"
651 [debug] Loaded engine "Catalyst::Engine::HTTP"
652 [debug] Found home "/home/me/MyApp"
45d511e0 653 [debug] Loaded Config "/home/me/MyApp/myapp.conf"
3533daff 654 [debug] Loaded components:
655 .-----------------------------------------------------------------+----------.
656 | Class | Type |
657 +-----------------------------------------------------------------+----------+
658 | MyApp::Controller::Books | instance |
659 | MyApp::Controller::Root | instance |
d0496197 660 | MyApp::Model::DB | instance |
661 | MyApp::Model::DB::Authors | class |
662 | MyApp::Model::DB::BookAuthors | class |
663 | MyApp::Model::DB::Books | class |
3533daff 664 | MyApp::View::TT | instance |
665 '-----------------------------------------------------------------+----------'
666
667 [debug] Loaded Private actions:
668 .----------------------+--------------------------------------+--------------.
669 | Private | Class | Method |
670 +----------------------+--------------------------------------+--------------+
671 | /default | MyApp::Controller::Root | default |
672 | /end | MyApp::Controller::Root | end |
673 | /books/index | MyApp::Controller::Books | index |
674 | /books/list | MyApp::Controller::Books | list |
675 '----------------------+--------------------------------------+--------------'
676
677 [debug] Loaded Path actions:
678 .-------------------------------------+--------------------------------------.
679 | Path | Private |
680 +-------------------------------------+--------------------------------------+
681 | /books/list | /books/list |
682 '-------------------------------------+--------------------------------------'
683
684 [info] MyApp powered by Catalyst 5.7011
685 You can connect to your server at http://localhost:3000
686
d0496197 687B<NOTE:> Be sure you run the C<script/myapp_server.pl> command from
3533daff 688the 'base' directory of your application, not inside the C<script>
689directory itself or it will not be able to locate the C<myapp.db>
690database file. You can use a fully qualified or a relative path to
691locate the database file, but we did not specify that when we ran the
692model helper earlier.
693
694Some things you should note in the output above:
695
696=over 4
697
698=item *
699
700Catalyst::Model::DBIC::Schema dynamically created three model classes,
701one to represent each of the three tables in our database
d0496197 702(C<MyApp::Model::DB::Authors>, C<MyApp::Model::DB::BookAuthors>,
703and C<MyApp::Model::DB::Books>).
3533daff 704
705=item *
706
707The "list" action in our Books controller showed up with a path of
708C</books/list>.
709
710=back
711
712Point your browser to L<http://localhost:3000> and you should still get
713the Catalyst welcome page.
714
715Next, to view the book list, change the URL in your browser to
716L<http://localhost:3000/books/list>. You should get a list of the five
717books loaded by the C<myapp01.sql> script above, with TTSite providing
718the formatting for the very simple output we generated in our template.
719The rating for each book should appear on each row.
720
721Also notice in the output of the C<script/myapp_server.pl> that DBIC
722used the following SQL to retrieve the data:
723
724 SELECT me.id, me.title, me.rating FROM books me
725
726because we enabled DBIC_TRACE.
727
0c51850e 728You now have the beginnings of a simple but workable web application.
3533daff 729Continue on to future sections and we will develop the application
730more fully.
731
732
733=head1 A STATIC DATABASE MODEL WITH C<DBIx::Class>
734
735=head2 Create Static DBIC Schema Files
736
737Unlike the previous section where we had DBIC automatically discover the
738structure of the database every time the application started, here we
739will use static schema files for more control. This is typical of most
740"real world" applications.
741
742One option would be to create a separate schema file for each table in
743the database, however, lets use the same L<DBIx::Class::Schema::Loader>
744used earlier with C<create=dynamic> to build the static files for us.
9ad715b3 745First, lets remove the schema file created earlier:
3533daff 746
d0496197 747 $ rm lib/MyApp/Schema.pm
3533daff 748
749Now regenerate the schema using the C<create=static> option:
750
d0496197 751 $ script/myapp_create.pl model DB DBIC::Schema MyApp::Schema create=static dbi:SQLite:myapp.db
752 exists "/home/kclark/dev/MyApp/script/../lib/MyApp/Model"
753 exists "/home/kclark/dev/MyApp/script/../t"
754 Dumping manual schema for MyApp::Schema to directory /home/kclark/dev/MyApp/script/../lib ...
3533daff 755 Schema dump completed.
d0496197 756 exists "/home/kclark/dev/MyApp/script/../lib/MyApp/Model/DB.pm"
3533daff 757
d0496197 758We could have also deleted C<lib/MyApp/Model/DB.pm>, but it would
3533daff 759have regenerated the same file (note the C<exists> in the output above).
d0496197 760If you take a look at C<lib/MyApp/Model/DB.pm>, it simply contains
761a reference to the actual schema file in C<lib/MyApp/Schema.pm>
3533daff 762along with the database connect string.
763
764If you look in the C<lib/MyApp/Schema> directory, you will find that
d0496197 765C<DB.pm> is no longer using L<DBIx::Class::Schema::Loader> as its
3533daff 766base class (L<DBIx::Class::Schema::Loader> is only being used by the
767helper to load the schema once and then create the static files for us)
768and that it only contains a call to the C<load_classes> method. You
d0496197 769will also find that C<lib/MyApp/Schema> contains a C<Schema>
3533daff 770subdirectory, with one file inside this directory for each of the tables
771in our simple database (C<Authors.pm>, C<BookAuthors.pm>, and
772C<Books.pm>). These three files were created based on the information
773found by L<DBIx::Class::Schema::Loader> as the helper ran.
774
775The idea with all of the files created under C<lib/MyApp/Schema> by the
776C<create=static> option is to only edit the files below the C<# DO NOT
777MODIFY THIS OR ANYTHING ABOVE!> warning. If you place all of your
778changes below that point in the file, you can regenerate the
779auto-generated information at the top of each file should your database
780structure get updated.
781
782Also note the "flow" of the model information across the various files
783and directories. Catalyst will initially load the model from
d0496197 784C<lib/MyApp/Model/DB.pm>. This file contains a reference to
785C<lib/MyApp/Schema.pm>, so that file is loaded next. Finally,
3533daff 786the call to C<load_classes> in that file will load each of the
d0496197 787table-specific "results source" files from the C<lib/MyApp/Schema>
3533daff 788subdirectory. These three table-specific DBIC schema files will then be
789used to create three table-specific Catalyst models every time the
790application starts (you can see these three model files listed in
791the debug output generated when you launch the application).
792
793
794=head2 Updating the Generated DBIC Schema Files
795
796
797Let's manually add some relationship information to the auto-generated
d0496197 798schema files. First edit C<lib/MyApp/Schema/Books.pm> and
3533daff 799add the following text below the C<# You can replace this text...>
800comment:
801
802 #
803 # Set relationships:
804 #
805
806 # has_many():
807 # args:
808 # 1) Name of relationship, DBIC will create accessor with this name
809 # 2) Name of the model class referenced by this relationship
810 # 3) Column name in *foreign* table
d0496197 811 __PACKAGE__->has_many(book_authors => 'MyApp::Schema::BookAuthors', 'book_id');
3533daff 812
813 # many_to_many():
814 # args:
815 # 1) Name of relationship, DBIC will create accessor with this name
816 # 2) Name of has_many() relationship this many_to_many() is shortcut for
817 # 3) Name of belongs_to() relationship in model class of has_many() above
818 # You must already have the has_many() defined to use a many_to_many().
819 __PACKAGE__->many_to_many(authors => 'book_authors', 'author');
820
821
822B<Note:> Be careful to put this code I<above> the C<1;> at the end of the
823file. As with any Perl package, we need to end the last line with
824a statement that evaluates to C<true>. This is customarily done with
825C<1;> on a line by itself.
826
827This code defines both a C<has_many> and a C<many_to_many> relationship.
828The C<many_to_many> relationship is optional, but it makes it easier to
829map a book to its collection of authors. Without it, we would have to
830"walk" though the C<book_authors> table as in C<$book-E<gt>book_authors-
831E<gt>first-E<gt>author-E<gt>last_name> (we will see examples on how to
832use DBIC objects in your code soon, but note that because C<$book-
833E<gt>book_authors> can return multiple authors, we have to use C<first>
834to display a single author). C<many_to_many> allows us to use the
835shorter C<$book-E<gt>authors-E<gt>first-E<gt>last_name>. Note that you
836cannot define a C<many_to_many> relationship without also having the
837C<has_many> relationship in place.
838
d0496197 839Then edit C<lib/MyApp/Schema/Authors.pm> and add relationship
3533daff 840information as follows (again, be careful to put in above the C<1;> but
841below the C<# DO NOT MODIFY THIS OR ANYTHING ABOVE!> comment):
842
843 #
844 # Set relationships:
845 #
846
847 # has_many():
848 # args:
849 # 1) Name of relationship, DBIC will create accessor with this name
850 # 2) Name of the model class referenced by this relationship
851 # 3) Column name in *foreign* table
d0496197 852 __PACKAGE__->has_many(book_author => 'MyApp::Schema::BookAuthors', 'author_id');
3533daff 853
854 # many_to_many():
855 # args:
856 # 1) Name of relationship, DBIC will create accessor with this name
857 # 2) Name of has_many() relationship this many_to_many() is shortcut for
858 # 3) Name of belongs_to() relationship in model class of has_many() above
859 # You must already have the has_many() defined to use a many_to_many().
860 __PACKAGE__->many_to_many(books => 'book_author', 'book');
861
862Finally, do the same for the "join table,"
d0496197 863C<lib/MyApp/Schema/BookAuthors.pm>:
3533daff 864
865 #
866 # Set relationships:
867 #
868
869 # belongs_to():
870 # args:
871 # 1) Name of relationship, DBIC will create accessor with this name
872 # 2) Name of the model class referenced by this relationship
873 # 3) Column name in *this* table
d0496197 874 __PACKAGE__->belongs_to(book => 'MyApp::Schema::Books', 'book_id');
3533daff 875
876 # belongs_to():
877 # args:
878 # 1) Name of relationship, DBIC will create accessor with this name
879 # 2) Name of the model class referenced by this relationship
880 # 3) Column name in *this* table
d0496197 881 __PACKAGE__->belongs_to(author => 'MyApp::Schema::Authors', 'author_id');
3533daff 882
883
884=head1 RUN THE APPLICATION
885
886Run the Catalyst "demo server" script with the C<DBIC_TRACE> option
887(it might still be enabled from earlier in the tutorial, but here
888is an alternate way to specify the option just in case):
889
890 $ DBIC_TRACE=1 script/myapp_server.pl
891
892Make sure that the application loads correctly and that you see the
893three dynamically created model class (one for each of the
894table-specific schema classes we created).
895
896Then hit the URL L<http://localhost:3000/books/list> and be sure that
897the book list is displayed.
898
899
900=head1 RUNNING THE APPLICATION FROM THE COMMAND LINE
901
902In some situations, it can be useful to run your application and
903display a page without using a browser. Catalyst lets you do this
904using the C<scripts/myapp_test.pl> script. Just supply the URL you
905wish to display and it will run that request through the normal
906controller dispatch logic and use the appropriate view to render the
907output (obviously, complex pages may dump a lot of text to your
908terminal window). For example, if you type:
909
910 $ script/myapp_test.pl "/books/list"
911
912You should get the same text as if you visited
913L<http://localhost:3000/books/list> with the normal development server
914and asked your browser to view the page source.
915
916
917=head1 UPDATING THE VIEW
918
919Let's add a new column to our book list page that takes advantage of
920the relationship information we manually added to our schema files
921in the previous section. Edit C<root/src/books/list.tt2> add add the
922following code below the existing table cell that contains
923C<book.rating> (IOW, add a new table cell below the existing two
924C<td> cells):
925
926 <td>
927 [% # First initialize a TT variable to hold a list. Then use a TT FOREACH -%]
928 [% # loop in 'side effect notation' to load just the last names of the -%]
a0c5188a 929 [% # authors into the list. Note that the 'push' TT vmethod does not print -%]
3533daff 930 [% # a value, so nothing will be printed here. But, if you have something -%]
931 [% # in TT that does return a method and you don't want it printed, you -%]
932 [% # can: 1) assign it to a bogus value, or 2) use the CALL keyword to -%]
933 [% # call it and discard the return value. -%]
934 [% tt_authors = [ ];
935 tt_authors.push(author.last_name) FOREACH author = book.authors %]
936 [% # Now use a TT 'virtual method' to display the author count in parens -%]
937 [% # Note the use of the TT filter "| html" to escape dangerous characters -%]
938 ([% tt_authors.size | html %])
939 [% # Use another TT vmethod to join & print the names & comma separators -%]
940 [% tt_authors.join(', ') | html %]
941 </td>
942
bb7d1193 943Then hit C<Ctrl+R> in your browser (note that you don't need to reload
3533daff 944the development server or use the C<-r> option when updating TT
bb7d1193 945templates) and you should now see the the number of authors each book
946along with a comma-separated list of the author's last names.
3533daff 947
948If you are still running the development server with C<DBIC_TRACE>
949enabled, you should also now see five more C<SELECT> statements in the
950debug output (one for each book as the authors are being retrieved by
951DBIC).
952
953Also note that we are using "| html", a type of TT filter, to escape
954characters such as E<lt> and E<gt> to &lt; and &gt; and avoid various
955types of dangerous hacks against your application. In a real
956application, you would probably want to put "| html" at the end of
957every field where a user has control over the information that can
958appear in that field (and can therefore inject markup or code if you
959don't "neutralize" those fields). In addition to "| html", Template
960Toolkit has a variety of other useful filters that can found in the
961documentation for L<Template::Filters|Template::Filters>.
962
963
964=head2 Using C<RenderView> for the Default View
965
966B<NOTE: The rest of this part of the tutorial is optional. You can
967skip to Part 4, L<Basic CRUD|Catalyst::Manual::Tutorial::BasicCRUD>,
968if you wish.>
969
970Once your controller logic has processed the request from a user, it
971forwards processing to your view in order to generate the appropriate
972response output. Catalyst uses
973L<Catalyst::Action::RenderView|Catalyst::Action::RenderView> by
974default to automatically performs this operation. If you look in
975C<lib/MyApp/Controller/Root.pm>, you should see the empty
976definition for the C<sub end> method:
977
978 sub end : ActionClass('RenderView') {}
979
980The following bullet points provide a quick overview of the
981C<RenderView> process:
982
983=over 4
984
985=item *
986
987C<Root.pm> is designed to hold application-wide logic.
988
989=item *
990
991At the end of a given user request, Catalyst will call the most specific
992C<end> method that's appropriate. For example, if the controller for a
993request has an C<end> method defined, it will be called. However, if
994the controller does not define a controller-specific C<end> method, the
995"global" C<end> method in C<Root.pm> will be called.
996
997=item *
998
999Because the definition includes an C<ActionClass> attribute, the
1000L<Catalyst::Action::RenderView|Catalyst::Action::RenderView> logic
1001will be executed B<after> any code inside the definition of C<sub end>
1002is run. See L<Catalyst::Manual::Actions|Catalyst::Manual::Actions>
1003for more information on C<ActionClass>.
1004
1005=item *
1006
1007Because C<sub end> is empty, this effectively just runs the default
1008logic in C<RenderView>. However, you can easily extend the
1009C<RenderView> logic by adding your own code inside the empty method body
1010(C<{}>) created by the Catalyst Helpers when we first ran the
1011C<catalyst.pl> to initialize our application. See
1012L<Catalyst::Action::RenderView|Catalyst::Action::RenderView> for more
1013detailed information on how to extended C<RenderView> in C<sub end>.
1014
1015=back
1016
1017
1018=head2 Using The Default Template Name
1019
1020By default, C<Catalyst::View::TT> will look for a template that uses the
1021same name as your controller action, allowing you to save the step of
1022manually specifying the template name in each action. For example, this
1023would allow us to remove the
1024C<$c-E<gt>stash-E<gt>{template} = 'books/list.tt2';> line of our
1025C<list> action in the Books controller. Open
1026C<lib/MyApp/Controller/Books.pm> in your editor and comment out this line
1027to match the following (only the C<$c-E<gt>stash-E<gt>{template}> line
1028has changed):
1029
1030 =head2 list
1031
1032 Fetch all book objects and pass to books/list.tt2 in stash to be displayed
1033
1034 =cut
1035
1036 sub list : Local {
1037 # Retrieve the usual Perl OO '$self' for this object. $c is the Catalyst
1038 # 'Context' that's used to 'glue together' the various components
1039 # that make up the application
1040 my ($self, $c) = @_;
1041
1042 # Retrieve all of the book records as book model objects and store in the
1043 # stash where they can be accessed by the TT template
d0496197 1044 $c->stash->{books} = [$c->model('DB::Books')->all];
3533daff 1045
1046 # Set the TT template to use. You will almost always want to do this
1047 # in your action methods (actions methods respond to user input in
1048 # your controllers).
1049 #$c->stash->{template} = 'books/list.tt2';
1050 }
1051
1052C<Catalyst::View::TT> defaults to looking for a template with no
1053extension. In our case, we need to override this to look for an
1054extension of C<.tt2>. Open C<lib/MyApp/View/TT.pm> and add the
1055C<TEMPLATE_EXTENSION> definition as follows:
1056
1057 __PACKAGE__->config({
1058 CATALYST_VAR => 'Catalyst',
1059 INCLUDE_PATH => [
1060 MyApp->path_to( 'root', 'src' ),
1061 MyApp->path_to( 'root', 'lib' )
1062 ],
1063 PRE_PROCESS => 'config/main',
1064 WRAPPER => 'site/wrapper',
1065 ERROR => 'error.tt2',
1066 TIMER => 0,
1067 TEMPLATE_EXTENSION => '.tt2',
1068 });
1069
1070You should now be able to restart the development server as per the
1071previous section and access the L<http://localhost:3000/books/list>
1072as before.
1073
1074B<NOTE:> Please note that if you use the default template technique,
1075you will B<not> be able to use either the C<$c-E<gt>forward> or
1076the C<$c-E<gt>detach> mechanisms (these are discussed in Part 2 and
1077Part 9 of the Tutorial).
1078
1079
1080=head2 Return To A Manually-Specified Template
1081
1082In order to be able to use C<$c-E<gt>forward> and C<$c-E<gt>detach>
1083later in the tutorial, you should remove the comment from the
1084statement in C<sub list> in C<lib/MyApp/Controller/Books.pm>:
1085
1086 $c->stash->{template} = 'books/list.tt2';
1087
1088Then delete the C<TEMPLATE_EXTENSION> line in
1089C<lib/MyApp/View/TT.pm>.
1090
1091You should then be able to restart the development server and
1092access L<http://localhost:3000/books/list> in the same manner as
1093with earlier sections.
1094
1095
1096=head1 AUTHOR
1097
1098Kennedy Clark, C<hkclark@gmail.com>
1099
1100Please report any errors, issues or suggestions to the author. The
1101most recent version of the Catalyst Tutorial can be found at
1102L<http://dev.catalyst.perl.org/repos/Catalyst/trunk/Catalyst-Manual/lib/Catalyst/Manual/Tutorial/>.
1103
45c7830f 1104Copyright 2006-2008, Kennedy Clark, under Creative Commons License
3533daff 1105(L<http://creativecommons.org/licenses/by-nc-sa/2.5/>).
1106