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