Convert to more of a mixture of "DBIC" and "DBIx::Class" as per suggestion from Castaway
[catagits/Catalyst-Manual.git] / lib / Catalyst / Manual / Tutorial / MoreCatalystBasics.pod
CommitLineData
3533daff 1=head1 NAME
2
4b4d3884 3Catalyst::Manual::Tutorial::MoreCatalystBasics - Catalyst Tutorial - Chapter 3: More Catalyst Application Development Basics
3533daff 4
5
6=head1 OVERVIEW
7
4b4d3884 8This is B<Chapter 3 of 10> for the Catalyst tutorial.
3533daff 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
4b4d3884 59This chapter of the tutorial builds on the work done in Chapter 2 to
60explore some features that are more typical of "real world" web
61applications. From this chapter of the tutorial onward, we will be
62building a simple book database application. Although the application
63will be too limited to be of use to anyone, it should provide a basic
64environment where we can explore a variety of features used in
65virtually all web applications.
3533daff 66
4d63a0d5 67You can check out the source code for this example from the Catalyst
68Subversion repository as per the instructions in
1390ef0e 69L<Catalyst::Manual::Tutorial::Intro|Catalyst::Manual::Tutorial::Intro>.
3533daff 70
a586a09f 71Please take a look at
72L<Catalyst::Manual::Tutorial::Intro/CATALYST INSTALLATION> before
73doing the rest of this tutorial. Although the tutorial should work
74correctly under most any recent version of Perl running on any
75operating system, the tutorial has been written using Debian 5 and
76tested to be sure it runs correctly in this environment.
77
3533daff 78
79=head1 CREATE A NEW APPLICATION
80
1390ef0e 81The remainder of the tutorial will build an application called C<MyApp>.
82First use the Catalyst C<catalyst.pl> script to initialize the framework
83for the C<MyApp> application (make sure you aren't still inside the
4b4d3884 84directory of the C<Hello> application from the previous chapter of the
acbd7bdd 85tutorial or in a directory that already has a "MyApp" subdirectory):
3533daff 86
87 $ catalyst.pl MyApp
88 created "MyApp"
89 created "MyApp/script"
90 created "MyApp/lib"
91 created "MyApp/root"
92 ...
93 created "MyApp/script/myapp_create.pl"
94 $ cd MyApp
95
4b4d3884 96This creates a similar skeletal structure to what we saw in Chapter 2 of
1390ef0e 97the tutorial, except with C<MyApp> and C<myapp> substituted for
3533daff 98C<Hello> and C<hello>.
99
100
101=head1 EDIT THE LIST OF CATALYST PLUGINS
102
103One of the greatest benefits of Catalyst is that it has such a large
1390ef0e 104library of plugins and base classes available. Plugins are used to
105seamlessly integrate existing Perl modules into the overall Catalyst
106framework. In general, they do this by adding additional methods to the
107C<context> object (generally written as C<$c>) that Catalyst passes to
108every component throughout the framework.
3533daff 109
110By default, Catalyst enables three plugins/flags:
111
112=over 4
113
1390ef0e 114=item *
3533daff 115
116C<-Debug> Flag
117
118Enables the Catalyst debug output you saw when we started the
119C<script/myapp_server.pl> development server earlier. You can remove
79a529cc 120this item when you place your application into production.
3533daff 121
1390ef0e 122As you may have noticed, C<-Debug> is not a plugin, but a I<flag>.
123Although most of the items specified on the C<__PACKAGE__-E<gt>setup>
124line of your application class will be plugins, Catalyst supports a
125limited number of flag options (of these, C<-Debug> is the most
126common). See the documentation for C<Catalyst.pm> to get details on
127other flags (currently C<-Engine>, C<-Home>, and C<-Log>).
3533daff 128
129If you prefer, you can use the C<$c-E<gt>debug> method to enable debug
130messages.
131
132B<TIP>: Depending on your needs, it can be helpful to permanently
133remove C<-Debug> from C<lib/MyApp.pm> and then use the C<-d> option
134to C<script/myapp_server.pl> to re-enable it just for the development
1390ef0e 135server. We will not be using that approach in the tutorial, but feel
3533daff 136free to make use of it in your own projects.
137
138=item *
139
140L<Catalyst::Plugin::ConfigLoader|Catalyst::Plugin::ConfigLoader>
141
142C<ConfigLoader> provides an automatic way to load configurable
c010ae0d 143parameters for your application from a central
144L<Config::General|Config::General> file (versus having the values
145hard-coded inside your Perl modules). Config::General uses syntax
146very similar to Apache configuration files. We will see how to use
147this feature of Catalyst during the authentication and authorization
4b4d3884 148sections (Chapter 5 and Chapter 6).
3533daff 149
1435672d 150B<IMPORTANT NOTE:> If you are using a version of
151L<Catalyst::Devel|Catalyst::Devel> prior to version 1.06, be aware
152that Catalyst changed the default format from YAML to the more
153straightforward C<Config::General> style. This tutorial uses the
154newer C<myapp.conf> file for C<Config::General>. However, Catalyst
155supports both formats and will automatically use either C<myapp.conf>
156or C<myapp.yml> (or any other format supported by
157L<Catalyst::Plugin::ConfigLoader|Catalyst::Plugin::ConfigLoader> and
158L<Config::Any|Config::Any>). If you are using a version of
159Catalyst::Devel prior to 1.06, you can convert to the newer format by
160simply creating the C<myapp.conf> file manually and deleting
161C<myapp.yml>. The default contents of the C<myapp.conf> you create
162should only consist of one line:
163
164 name MyApp
15e1d0b2 165
1390ef0e 166B<TIP>: This script can be useful for converting between configuration
15e1d0b2 167formats:
168
1390ef0e 169 perl -Ilib -e 'use MyApp; use Config::General;
15e1d0b2 170 Config::General->new->save_file("myapp.conf", MyApp->config);'
171
3533daff 172=item *
173
174L<Catalyst::Plugin::Static::Simple|Catalyst::Plugin::Static::Simple>
175
4d63a0d5 176C<Static::Simple> provides an easy way to serve static content, such
177as images and CSS files, from the development server.
3533daff 178
179=back
180
94d8da41 181For our application, we want to add one new plugin into the mix. To
1390ef0e 182do this, edit C<lib/MyApp.pm> (this file is generally referred to as
acbd7bdd 183your I<application class>) and delete the lines with:
3533daff 184
acbd7bdd 185 use Catalyst qw/-Debug
186 ConfigLoader
187 Static::Simple/;
3533daff 188
1390ef0e 189Then replace it with:
b411df01 190
acbd7bdd 191 # Load plugins
192 use Catalyst qw/-Debug
193 ConfigLoader
194 Static::Simple
195
196 StackTrace
197 /;
1390ef0e 198
94d8da41 199B<Note:> Recent versions of C<Catalyst::Devel> have used a variety of
acbd7bdd 200techniques to load these plugins/flags. For example, you might see
201the following:
94d8da41 202
acbd7bdd 203 __PACKAGE__->setup(qw/-Debug ConfigLoader Static::Simple/);
94d8da41 204
205Don't let these variations confuse you -- they all accomplish the same
206result.
207
1390ef0e 208This tells Catalyst to start using one new plugin,
209L<Catalyst::Plugin::StackTrace|Catalyst::Plugin::StackTrace>, to add a
210stack trace to the standard Catalyst "debug screen" (the screen
211Catalyst sends to your browser when an error occurs). Be aware that
212L<StackTrace|Catalyst::Plugin::StackTrace> output appears in your
213browser, not in the console window from which you're running your
214application, which is where logging output usually goes.
3533daff 215
1390ef0e 216B<Notes:>
3533daff 217
218=over 4
219
1390ef0e 220=item *
221
222C<__PACKAGE__> is just a shorthand way of referencing the name of the
223package where it is used. Therefore, in C<MyApp.pm>, C<__PACKAGE__>
224is equivalent to C<MyApp>.
3533daff 225
1390ef0e 226=item *
3533daff 227
1390ef0e 228You will want to disable L<StackTrace|Catalyst::Plugin::StackTrace>
229before you put your application into production, but it can be helpful
230during development.
3533daff 231
1390ef0e 232=item *
3533daff 233
1390ef0e 234When specifying plugins on the C<__PACKAGE__-E<gt>setup> line, you can
235omit C<Catalyst::Plugin::> from the name. Additionally, you can
236spread the plugin names across multiple lines as shown here, or place
237them all on one (or more) lines as with the default configuration.
cca5cd98 238
3533daff 239=back
240
3533daff 241
242=head1 CREATE A CATALYST CONTROLLER
243
1390ef0e 244As discussed earlier, controllers are where you write methods that
245interact with user input. Typically, controller methods respond to
4d63a0d5 246C<GET> and C<POST> requests from the user's web browser.
3533daff 247
248Use the Catalyst C<create> script to add a controller for book-related
249actions:
250
251 $ script/myapp_create.pl controller Books
252 exists "/home/me/MyApp/script/../lib/MyApp/Controller"
253 exists "/home/me/MyApp/script/../t"
254 created "/home/me/MyApp/script/../lib/MyApp/Controller/Books.pm"
255 created "/home/me/MyApp/script/../t/controller_Books.t"
256
4b4d3884 257Then edit C<lib/MyApp/Controller/Books.pm> (as discussed in Chapter 2 of
1390ef0e 258the Tutorial, Catalyst has a separate directory under C<lib/MyApp> for
259each of the three parts of MVC: C<Model>, C<View>, and C<Controller>)
260and add the following method to the controller:
3533daff 261
262 =head2 list
263
264 Fetch all book objects and pass to books/list.tt2 in stash to be displayed
265
266 =cut
1390ef0e 267
3533daff 268 sub list : Local {
269 # Retrieve the usual Perl OO '$self' for this object. $c is the Catalyst
270 # 'Context' that's used to 'glue together' the various components
271 # that make up the application
272 my ($self, $c) = @_;
273
274 # Retrieve all of the book records as book model objects and store in the
275 # stash where they can be accessed by the TT template
1390ef0e 276 # $c->stash->{books} = [$c->model('DB::Books')->all];
277 # But, for now, use this code until we create the model later
278 $c->stash->{books} = '';
279
3533daff 280 # Set the TT template to use. You will almost always want to do this
281 # in your action methods (action methods respond to user input in
282 # your controllers).
283 $c->stash->{template} = 'books/list.tt2';
284 }
285
1390ef0e 286B<TIP>: See Appendix 1 for tips on removing the leading spaces when
287cutting and pasting example code from POD-based documents.
3533daff 288
1390ef0e 289Programmers experienced with object-oriented Perl should recognize
290C<$self> as a reference to the object where this method was called.
291On the other hand, C<$c> will be new to many Perl programmers who have
292not used Catalyst before (it's sometimes written as C<$context>). The
293Context object is automatically passed to all Catalyst components. It
294is used to pass information between components and provide access to
295Catalyst and plugin functionality.
3533daff 296
245b41d1 297Catalyst actions are regular Perl methods, but they make use of
298attributes (the "C<: Local>" next to the "C<sub list>" in the code
0416017e 299above) to provide additional information to the Catalyst dispatcher
300logic (note that the space between the colon and the attribute name is
4d63a0d5 301optional; you will see attributes written both ways). Most Catalyst
245b41d1 302Controllers use one of five action types:
0416017e 303
304=over 4
305
306=item *
307
245b41d1 308B<:Private> -- Use C<:Private> for methods that you want to make into
4d63a0d5 309an action, but you do not want Catalyst to directly expose
245b41d1 310to your users. Catalyst will not map C<:Private> methods to a URI.
311Use them for various sorts of "special" methods (the C<begin>,
312C<auto>, etc. discussed below) or for methods you want to be able to
313C<forward> or C<detach> to. (If the method is a plain old "helper
314method" that you don't want to be an action at all, then just define
315the method without any attribute -- you can call it in your code, but
316the Catalyst dispatcher will ignore it.)
0416017e 317
245b41d1 318There are five types of "special" build-in C<:Private> actions:
319C<begin>, C<end>, C<default>, C<index>, and C<auto>.
0416017e 320
26c9cad5 321=over 4
322
0416017e 323=item *
324
325With C<begin>, C<end>, C<default>, C<index> private actions, only the
326most specific action of each type will be called. For example, if you
327define a C<begin> action in your controller it will I<override> a
328C<begin> action in your application/root controller -- I<only> the
329action in your controller will be called.
330
331=item *
332
333Unlike the other actions where only a single method is called for each
334request, I<every> auto action along the chain of namespaces will be
335called. Each C<auto> action will be called I<from the application/root
336controller down through the most specific class>.
337
338=back
339
340=item *
341
245b41d1 342B<:Path> -- C<:Path> actions let you map a method to an explicit URI
343path. For example, "C<:Path('list')>" in
0416017e 344C<lib/MyApp/Controller/Books.pm> would match on the URL
245b41d1 345C<http://localhost:3000/books/list> but "C<:Path('/list')>" would match
346on C<http://localhost:3000/list>. You can use C<:Args()> to specify
7e8cd009 347how many arguments an action should accept. See
245b41d1 348L<Catalyst::Manual::Intro/Action_types> for more information and a few
0416017e 349examples.
350
351=item *
352
245b41d1 353B<:Local> -- C<:Local> is merely a shorthand for
354"C<:Path('_name_of_method_')>". For example, these are equivalent:
355"C<sub create_book :Local {...}>" and
356"C<sub create_book :Path('create_book') {...}>".
357
358=item *
359
360B<:Global> -- C<:Global> is merely a shorthand for
361"C<:Path('/_name_of_method_')>". For example, these are equivalent:
362"C<sub create_book :Global {...}>" and
363"C<sub create_book :Path('/create_book') {...}>".
364
365=item *
366
367B<:Chained> -- Newer Catalyst applications tend to use the Chained
0416017e 368dispatch form of action types because of its power and flexibility.
4d63a0d5 369It allows a series of controller methods to be automatically dispatched
0416017e 370to service a single user request. See
371L<Catalyst::Manual::Tutorial::BasicCRUD|Catalyst::Manual::Tutorial::BasicCRUD>
372and L<Catalyst::DispatchType::Chained|Catalyst::DispatchType::Chained>
373for more information on chained actions.
374
375=back
376
377You should refer to L<Catalyst::Manual::Intro/Action_types> for
378additional information and for coverage of some lesser-used action
245b41d1 379types not discussed here (C<Regex> and C<LocalRegex>).
3533daff 380
381
382=head1 CATALYST VIEWS
383
4d63a0d5 384As mentioned in Chapter 2 of the tutorial, views are where you render
385output, typically for display in the user's web browser (but also
386possibly using into output-generation systems, such as PDF or JSON).
387The code in C<lib/MyApp/View> selects the I<type> of view to use, with
388the actual rendering template found in the C<root> directory. As with
389virtually every aspect of Catalyst, options abound when it comes to the
390specific view technology you adopt inside your application. However,
391most Catalyst applications use the Template Toolkit, known as TT (for
392more information on TT, see L<http://www.template-toolkit.org>). Other
393somewhat popular view technologies include Mason
394(L<http://www.masonhq.com> and L<http://www.masonbook.com>) and
1390ef0e 395L<HTML::Template> (L<http://html-template.sourceforge.net>).
396
397
398=head2 Create a Catalyst View
3533daff 399
400When using TT for the Catalyst view, there are two main helper scripts:
401
402=over 4
403
404=item *
405
406L<Catalyst::Helper::View::TT|Catalyst::Helper::View::TT>
407
408=item *
409
410L<Catalyst::Helper::View::TTSite|Catalyst::Helper::View::TTSite>
411
412=back
413
de966eb4 414Both helpers are similar. C<TT> creates the C<lib/MyApp/View/TT.pm>
3533daff 415file and leaves the creation of any hierarchical template organization
416entirely up to you. (It also creates a C<t/view_TT.t> file for testing;
4b4d3884 417test cases will be discussed in Chapter 8.) C<TTSite>, on the other hand,
de966eb4 418creates a modular and hierarchical view layout with
1390ef0e 419separate Template Toolkit (TT) files for common header and footer
420information, configuration values, a CSS stylesheet, and more.
421
de966eb4 422While C<TTSite> was useful to bootstrap a project, its use is now
4d63a0d5 423deprecated and it should be considered historical. For most Catalyst
de966eb4 424applications it adds redundant functionality and structure; many in the
425Catalyst community recommend that it's easier to learn both Catalyst and
426Template Toolkit if you use the more basic C<TT> approach.
427Consequently, this tutorial will use "plain old TT."
1390ef0e 428
429Enter the following command to enable the C<TT> style of view
3533daff 430rendering for this tutorial:
431
1390ef0e 432 $ script/myapp_create.pl view TT TT
3533daff 433 exists "/home/me/MyApp/script/../lib/MyApp/View"
434 exists "/home/me/MyApp/script/../t"
1390ef0e 435 created "/home/me/MyApp/script/../lib/MyApp/View/TT.pm"
436 created "/home/me/MyApp/script/../t/view_TT.t"
3533daff 437
1390ef0e 438This simply creates a view called C<TT> (the second 'TT' argument) in
439a file called C<TT.pm> (the first 'TT' argument). It is now up to you
440to decide how you want to structure your view layout. For the
441tutorial, we will start with a very simple TT template to initially
442demonstrate the concepts, but quickly migrate to a more typical
443"wrapper page" type of configuration (where the "wrapper" controls the
444overall "look and feel" of your site from a single file or set of
445files).
3533daff 446
1390ef0e 447Edit C<lib/MyApp/View/TT.pm> and you should see that the default
448contents contains something similar to the following:
3533daff 449
1390ef0e 450 __PACKAGE__->config(TEMPLATE_EXTENSION => '.tt');
3533daff 451
1390ef0e 452And update it to match:
453
454 __PACKAGE__->config(
455 # Change default TT extension
456 TEMPLATE_EXTENSION => '.tt2',
457 # Set the location for TT files
458 INCLUDE_PATH => [
6abd3023 459 MyApp->path_to( 'root', 'src' ),
1390ef0e 460 ],
461 );
3533daff 462
1390ef0e 463B<NOTE:> Make sure to add a comma after '.tt2' outside the single
464quote.
465
191dee29 466This changes the default extension for Template Toolkit from '.tt' to
1390ef0e 467'.tt2' and changes the base directory for your template files from
de966eb4 468C<root> to C<root/src>. These changes from the default are done mostly
469to facilitate the application we're developing in this tutorial; as with
470most things Perl, there's more than one way to do it...
1390ef0e 471
acbd7bdd 472B<Note:> We will use C<root/src> as the base directory for our
473template files, which a full naming convention of
474C<root/src/_controller_name_/_action_name_.tt2>. Another popular option is to
475use C<root/> as the base (with a full filename pattern of
476C<root/_controller_name_/_action_name_.tt2>).
477
1390ef0e 478
479=head2 Create a TT Template Page
3533daff 480
481First create a directory for book-related TT templates:
482
1390ef0e 483 $ mkdir -p root/src/books
3533daff 484
485Then create C<root/src/books/list.tt2> in your editor and enter:
486
487 [% # This is a TT comment. The '-' at the end "chomps" the newline. You won't -%]
488 [% # see this "chomping" in your browser because HTML ignores blank lines, but -%]
489 [% # it WILL eliminate a blank line if you view the HTML source. It's purely -%]
490 [%- # optional, but both the beginning and the ending TT tags support chomping. -%]
491
1390ef0e 492 [% # Provide a title -%]
3533daff 493 [% META title = 'Book List' -%]
494
495 <table>
496 <tr><th>Title</th><th>Rating</th><th>Author(s)</th></tr>
497 [% # Display each book in a table row %]
498 [% FOREACH book IN books -%]
499 <tr>
500 <td>[% book.title %]</td>
501 <td>[% book.rating %]</td>
a46b474e 502 <td></td>
3533daff 503 </tr>
504 [% END -%]
505 </table>
506
507As indicated by the inline comments above, the C<META title> line uses
1390ef0e 508TT's META feature to provide a title to the "wrapper" that we will
509create later. Meanwhile, the C<FOREACH> loop iterates through each
510C<book> model object and prints the C<title> and C<rating> fields.
3533daff 511
4d63a0d5 512The C<[%> and C<%]> tags are used to delimit Template Toolkit code. TT
513supports a wide variety of directives for "calling" other files,
514looping, conditional logic, etc. In general, TT simplifies the usual
515range of Perl operators down to the single dot (C<.>) operator. This
516applies to operations as diverse as method calls, hash lookups, and list
517index values (see
518L<http://search.cpan.org/perldoc?Template::Manual::Variables> for
519details and examples). In addition to the usual C<Template> module Pod
520documentation, you can access the TT manual at
55beb65d 521L<http://search.cpan.org/perldoc?Template::Manual>.
3533daff 522
1390ef0e 523B<TIP:> While you can build all sorts of complex logic into your TT
524templates, you should in general keep the "code" part of your templates
525as simple as possible. If you need more complex logic, create helper
526methods in your model that abstract out a set of code into a single call
527from your TT template. (Note that the same is true of your controller
528logic as well -- complex sections of code in your controllers should
529often be pulled out and placed into your model objects.)
530
531
532=head2 Test Run The Application
533
534To test your work so far, first start the development server:
535
536 $ script/myapp_server.pl
537
538Then point your browser to L<http://localhost:3000> and you should
539still get the Catalyst welcome page. Next, change the URL in your
540browser to L<http://localhost:3000/books/list>. If you have
541everything working so far, you should see a web page that displays
542nothing other than our column headers for "Title", "Rating", and
543"Author(s)" -- we will not see any books until we get the database and
544model working below.
545
546If you run into problems getting your application to run correctly, it
547might be helpful to refer to some of the debugging techniques covered in
548the L<Debugging|Catalyst::Manual::Tutorial::Debugging> part of the
549tutorial.
3533daff 550
551
552=head1 CREATE A SQLITE DATABASE
553
554In this step, we make a text file with the required SQL commands to
1390ef0e 555create a database table and load some sample data. We will use SQLite,
556a popular database that is lightweight and easy to use. Open
557C<myapp01.sql> in your editor and enter:
3533daff 558
559 --
560 -- Create a very simple database to hold book and author information
561 --
562 CREATE TABLE books (
563 id INTEGER PRIMARY KEY,
564 title TEXT ,
565 rating INTEGER
566 );
567 -- 'book_authors' is a many-to-many join table between books & authors
568 CREATE TABLE book_authors (
569 book_id INTEGER,
570 author_id INTEGER,
571 PRIMARY KEY (book_id, author_id)
572 );
573 CREATE TABLE authors (
574 id INTEGER PRIMARY KEY,
575 first_name TEXT,
576 last_name TEXT
577 );
578 ---
579 --- Load some sample data
580 ---
581 INSERT INTO books VALUES (1, 'CCSP SNRS Exam Certification Guide', 5);
582 INSERT INTO books VALUES (2, 'TCP/IP Illustrated, Volume 1', 5);
583 INSERT INTO books VALUES (3, 'Internetworking with TCP/IP Vol.1', 4);
584 INSERT INTO books VALUES (4, 'Perl Cookbook', 5);
585 INSERT INTO books VALUES (5, 'Designing with Web Standards', 5);
586 INSERT INTO authors VALUES (1, 'Greg', 'Bastien');
587 INSERT INTO authors VALUES (2, 'Sara', 'Nasseh');
588 INSERT INTO authors VALUES (3, 'Christian', 'Degu');
589 INSERT INTO authors VALUES (4, 'Richard', 'Stevens');
590 INSERT INTO authors VALUES (5, 'Douglas', 'Comer');
591 INSERT INTO authors VALUES (6, 'Tom', 'Christiansen');
592 INSERT INTO authors VALUES (7, 'Nathan', 'Torkington');
593 INSERT INTO authors VALUES (8, 'Jeffrey', 'Zeldman');
594 INSERT INTO book_authors VALUES (1, 1);
595 INSERT INTO book_authors VALUES (1, 2);
596 INSERT INTO book_authors VALUES (1, 3);
597 INSERT INTO book_authors VALUES (2, 4);
598 INSERT INTO book_authors VALUES (3, 5);
599 INSERT INTO book_authors VALUES (4, 6);
600 INSERT INTO book_authors VALUES (4, 7);
601 INSERT INTO book_authors VALUES (5, 8);
602
3533daff 603Then use the following command to build a C<myapp.db> SQLite database:
604
605 $ sqlite3 myapp.db < myapp01.sql
606
607If you need to create the database more than once, you probably want to
608issue the C<rm myapp.db> command to delete the database before you use
1390ef0e 609the C<sqlite3 myapp.db E<lt> myapp01.sql> command.
3533daff 610
611Once the C<myapp.db> database file has been created and initialized, you
612can use the SQLite command line environment to do a quick dump of the
613database contents:
614
615 $ sqlite3 myapp.db
acbd7bdd 616 SQLite version 3.5.9
3533daff 617 Enter ".help" for instructions
618 sqlite> select * from books;
619 1|CCSP SNRS Exam Certification Guide|5
620 2|TCP/IP Illustrated, Volume 1|5
621 3|Internetworking with TCP/IP Vol.1|4
622 4|Perl Cookbook|5
623 5|Designing with Web Standards|5
624 sqlite> .q
625 $
626
627Or:
628
629 $ sqlite3 myapp.db "select * from books"
630 1|CCSP SNRS Exam Certification Guide|5
631 2|TCP/IP Illustrated, Volume 1|5
632 3|Internetworking with TCP/IP Vol.1|4
633 4|Perl Cookbook|5
634 5|Designing with Web Standards|5
635
636As with most other SQL tools, if you are using the full "interactive"
637environment you need to terminate your SQL commands with a ";" (it's not
638required if you do a single SQL statement on the command line). Use
639".q" to exit from SQLite from the SQLite interactive mode and return to
640your OS command prompt.
641
a6d800ac 642For using other databases, such as PostgreSQL or MySQL, see
643L<Appendix 2|Catalyst::Manual::Tutorial::Appendices>.
3533daff 644
acbd7bdd 645
8a472b34 646=head1 DATABASE ACCESS WITH DBIx::Class
3533daff 647
27909ed4 648Catalyst can be used with virtually any form of datastore available
649via Perl. For example, L<Catalyst::Model::DBI|Catalyst::Model::DBI>
650can be used to access databases through the traditional Perl C<DBI>
651interface or you can use a model to access files of any type on the
652filesystem. However, most Catalyst applications use some form of
653object-relational mapping (ORM) technology to create objects
654associated with tables in a relational database. Matt Trout's
655L<DBIx::Class|DBIx::Class> (abbreviated as "DBIC") has rapidly emerged
656as the Perl-based ORM technology of choice. Most new Catalyst
a46b474e 657applications rely on DBIx::Class, as will this tutorial.
3533daff 658
a46b474e 659Although DBIx::Class has included support for a C<create=dynamic> mode
660to automatically read the database structure every time the
661application starts, it's use is no longer recommended. While it can
662make for "flashy" demos, the use of the C<create=static> mode we use
663below can be implemented just as quickly and provides many advantages
664(such as the ability to add your own methods to the overall DBIC
665framework, a technique that we see in Chapter 4).
3533daff 666
1390ef0e 667
a46b474e 668=head2 Make Sure You Have a Recent Version of the DBIx::Class Model
27909ed4 669
670First, let's be sure we have a recent version of the DBIC helper,
671L<Catalyst::Model::DBIC::Schema|Catalyst::Model::DBIC::Schema>, by
672running this command:
673
674 $ perl -MCatalyst::Model::DBIC::Schema -e \
675 'print "$Catalyst::Model::DBIC::Schema::VERSION\n"'
676 0.23
677
678If you don't have version 0.23 or higher, please run this command
679to install it directly from CPAN:
680
681 $ sudo cpan Catalyst::Model::DBIC::Schema
682
683And re-run the version print command to verify that you are now at
6840.23 or higher.
685
686
a46b474e 687=head2 Create Static DBIx::Class Schema Files
27909ed4 688
689Use the model helper with the C<create=static> option to read the
690database with
691L<DBIx::Class::Schema::Loader|DBIx::Class::Schema::Loader> and
692automatically build the required files for us:
3533daff 693
4ab6212d 694 $ script/myapp_create.pl model DB DBIC::Schema MyApp::Schema \
27909ed4 695 create=static components=TimeStamp dbi:SQLite:myapp.db
1390ef0e 696 exists "/home/me/MyApp/script/../lib/MyApp/Model"
697 exists "/home/me/MyApp/script/../t"
27909ed4 698 Dumping manual schema for MyApp::Schema to directory /home/me/MyApp/script/../lib ...
699 Schema dump completed.
1390ef0e 700 created "/home/me/MyApp/script/../lib/MyApp/Model/DB.pm"
701 created "/home/me/MyApp/script/../t/model_DB.t"
3533daff 702
27909ed4 703The C<script/myapp_create.pl> command breaks down like this:
704
705=over 4
706
707=item *
708
709C<DB> is the name of the model class to be created by the helper in
710C<lib/MyApp/Model>.
711
712=item *
713
714C<DBIC::Schema> is the type of the model to create.
715
716=item *
717
718C<MyApp::Schema> is the name of the DBIC schema file written to
719C<lib/MyApp/Schema.pm>.
720
721=item *
722
723C<create=static> causes
724L<DBIx::Class::Schema::Loader|DBIx::Class::Schema::Loader> to
725load the schema as it runs and then write that information out
726into files.
727
728=item *
729
730C<components=TimeStamp> causes the help to include the
731L<DBIx::Class::TimeStamp|DBIx::Class::TimeStamp> DBIC component.
732
733=item *
734
735And finally, C<dbi:SQLite:myapp.db> is the standard DBI connect string
736for use with SQLite.
737
738=back
739
740If you look in the C<lib/MyApp/Schema.pm> file, you will find that it
741only contains a call to the C<load_namespaces> method. You will also
742find that C<lib/MyApp> contains a C<Schema> subdirectory, which then
743has a subdirectory called "Result". This "Result" subdirectory then
744has files named according to each of the tables in our simple database
745(C<Authors.pm>, C<BookAuthors.pm>, and C<Books.pm>). These three
a46b474e 746files are called "Result Classes" in DBIx::Class nomenclature. Although the
27909ed4 747Result Class files are named after tables in our database, the classes
748correspond to the I<row-level data> that is returned by DBIC (more on
749this later, especially in
750L<Catalyst::Manual::Tutorial::BasicCRUD/EXPLORING THE POWER OF DBIC>).
751
752The idea with the Result Source files created under
753C<lib/MyApp/Schema/Result> by the C<create=static> option is to only
754edit the files below the C<# DO NOT MODIFY THIS OR ANYTHING ABOVE!>
755warning. If you place all of your changes below that point in the
756file, you can regenerate the automatically created information at the
757top of each file should your database structure get updated.
758
759Also note the "flow" of the model information across the various files
760and directories. Catalyst will initially load the model from
761C<lib/MyApp/Model/DB.pm>. This file contains a reference to
762C<lib/MyApp/Schema.pm>, so that file is loaded next. Finally, the
763call to C<load_namespaces> in C<Schema.pm> will load each of the
764"Result Class" files from the C<lib/MyApp/Schema/Result> subdirectory.
765The final outcome is that Catalyst will dynamically create three
766table-specific Catalyst models every time the application starts (you
767can see these three model files listed in the debug output generated
768when you launch the application).
769
770B<NOTE:> Older versions of
771L<Catalyst::Model::DBIC::Schema|Catalyst::Model::DBIC::Schema> use the
a46b474e 772deprecated DBIx::Class C<load_classes> technique instead of the newer
27909ed4 773C<load_namspaces>. For new applications, please try to use
774C<load_namespaces> since it more easily supports a very useful DBIC
775technique called "ResultSet Classes." If you need to convert an
776existing application from "load_classes" to "load_namespaces," you can
777use this process to automate the migration (but first make sure you
778have v0.23 C<Catalyst::Model::DBIC::Schema> as discussed above):
779
780 $ # First delete the existing schema file to disable "compatibility" mode
781 $ rm lib/MyApp/Schema.pm
782 $
783 $ # Then re-run the helper to build the files for "load_namespaces"
784 $ script/myapp_create.pl model DB DBIC::Schema MyApp::Schema \
785 create=static components=TimeStamp dbi:SQLite:myapp.db
786 $
787 $ # Now convert the existing files over
788 $ cd lib/MyApp/Schema
789 $ perl -MIO::All -e 'for (@ARGV) { my $s < io($_); $s =~ s/.*\n\# You can replace.*?\n//s;
790 $s =~ s/'MyApp::Schema::/'MyApp::Schema::Result::/g; my $d < io("Result/$_");
791 $d =~ s/1;\n?//; "$d$s" > io("Result/$_"); }' *.pm
792 $ cd ../../..
793 $
794 $ # And finally delete the old files
795 $ rm lib/MyApp/Schema/*.pm
796
797The "C<perl -MIO::ALL ...>" script will copy all the customized
798relationship (and other) information below "C<# DO NOT MODIFY>" line
799from the old files in C<lib/MyApp/Schema> to the new files in
800C<lib/MyApp/Schema/Result> (we will be starting to add some
801"customized relationship information in the section below).
3533daff 802
1435672d 803The C<script/myapp_create.pl> command breaks down like this:
804
805=over 4
806
807=item *
808
d0496197 809C<DB> is the name of the model class to be created by the helper in
1435672d 810C<lib/MyApp/Model>.
811
812=item *
813
814C<DBIC::Schema> is the type of the model to create.
815
816=item *
817
818C<MyApp::Schema> is the name of the DBIC schema file written to
819C<lib/MyApp/Schema.pm>.
820
821=item *
822
823Because we specified C<create=dynamic> to the helper, it use
1390ef0e 824L<DBIx::Class::Schema::Loader|DBIx::Class::Schema::Loader> to
825dynamically load the schema information from the database every time
1435672d 826the application starts.
827
828=item *
829
830And finally, C<dbi:SQLite:myapp.db> is the standard DBI connect string
831for use with SQLite.
832
833=back
3533daff 834
dc9a0503 835
1390ef0e 836=head1 ENABLE THE MODEL IN THE CONTROLLER
837
acbd7bdd 838Open C<lib/MyApp/Controller/Books.pm> and un-comment the model code we
839left disabled earlier so that your version matches the following (un-
840comment the line containing C<[$c-E<gt>model('DB::Books')-E<gt>all]>
841and delete the next 2 lines):
1390ef0e 842
843 =head2 list
844
845 Fetch all book objects and pass to books/list.tt2 in stash to be displayed
846
847 =cut
848
849 sub list : Local {
850 # Retrieve the usual Perl OO '$self' for this object. $c is the Catalyst
851 # 'Context' that's used to 'glue together' the various components
852 # that make up the application
853 my ($self, $c) = @_;
854
855 # Retrieve all of the book records as book model objects and store in the
856 # stash where they can be accessed by the TT template
857 $c->stash->{books} = [$c->model('DB::Books')->all];
858
859 # Set the TT template to use. You will almost always want to do this
860 # in your action methods (action methods respond to user input in
861 # your controllers).
862 $c->stash->{template} = 'books/list.tt2';
863 }
864
1435672d 865B<TIP>: You may see the C<$c-E<gt>model('DB::Books')> un-commented
866above written as C<$c-E<gt>model('DB')-E<gt>resultset('Books')>. The
c93b5eaa 867two are equivalent. Either way, C<$c-E<gt>model> returns a
868L<DBIx::Class::ResultSet|DBIx::Class::ResultSet> which handles queries
4d63a0d5 869against the database and iterating over the set of results that is
c93b5eaa 870returned.
871
872We are using the C<-E<gt>all> to fetch all of the books. DBIC
873supports a wide variety of more advanced operations to easily do
874things like filtering and sorting the results. For example, the
518f3851 875following could be used to sort the results by descending title:
c93b5eaa 876
877 $c->model('DB::Books')->search({}, {order_by => 'title DESC'});
878
879Some other examples are provided in
880L<DBIx::Class::Manual::Cookbook/Complex WHERE clauses>, with
881additional information found at L<DBIx::Class::ResultSet/search>,
882L<DBIx::Class::Manual::FAQ/Searching>,
883L<DBIx::Class::Manual::Intro|DBIx::Class::Manual::Intro>
884and L<Catalyst::Model::DBIC::Schema|Catalyst::Model::DBIC::Schema>.
1390ef0e 885
886
887=head2 Test Run The Application
3533daff 888
1435672d 889First, let's enable an environment variable that causes DBIx::Class to
acbd7bdd 890dump the SQL statements used to access the database. This is a
1435672d 891helpful trick when you are trying to debug your database-oriented
892code:
3533daff 893
894 $ export DBIC_TRACE=1
895
4d63a0d5 896This assumes you are using bash as your shell -- adjust accordingly if
3533daff 897you are using a different shell (for example, under tcsh, use
898C<setenv DBIC_TRACE 1>).
899
d0496197 900B<NOTE:> You can also set this in your code using
3533daff 901C<$class-E<gt>storage-E<gt>debug(1);>. See
902L<DBIx::Class::Manual::Troubleshooting> for details (including options
4d63a0d5 903to log to a file instead of displaying to the Catalyst development server
3533daff 904log).
905
1390ef0e 906Then launch the Catalyst development server. The log output should
907display something like:
3533daff 908
acbd7bdd 909 $ script/myapp_server.pl
3533daff 910 [debug] Debug messages enabled
1390ef0e 911 [debug] Statistics enabled
3533daff 912 [debug] Loaded plugins:
913 .----------------------------------------------------------------------------.
1390ef0e 914 | Catalyst::Plugin::ConfigLoader 0.20 |
915 | Catalyst::Plugin::StackTrace 0.08 |
3533daff 916 | Catalyst::Plugin::Static::Simple 0.20 |
917 '----------------------------------------------------------------------------'
918
919 [debug] Loaded dispatcher "Catalyst::Dispatcher"
920 [debug] Loaded engine "Catalyst::Engine::HTTP"
921 [debug] Found home "/home/me/MyApp"
45d511e0 922 [debug] Loaded Config "/home/me/MyApp/myapp.conf"
3533daff 923 [debug] Loaded components:
924 .-----------------------------------------------------------------+----------.
925 | Class | Type |
926 +-----------------------------------------------------------------+----------+
927 | MyApp::Controller::Books | instance |
928 | MyApp::Controller::Root | instance |
d0496197 929 | MyApp::Model::DB | instance |
930 | MyApp::Model::DB::Authors | class |
931 | MyApp::Model::DB::BookAuthors | class |
932 | MyApp::Model::DB::Books | class |
3533daff 933 | MyApp::View::TT | instance |
934 '-----------------------------------------------------------------+----------'
935
936 [debug] Loaded Private actions:
937 .----------------------+--------------------------------------+--------------.
938 | Private | Class | Method |
939 +----------------------+--------------------------------------+--------------+
940 | /default | MyApp::Controller::Root | default |
941 | /end | MyApp::Controller::Root | end |
1390ef0e 942 | /index | MyApp::Controller::Root | index |
3533daff 943 | /books/index | MyApp::Controller::Books | index |
944 | /books/list | MyApp::Controller::Books | list |
945 '----------------------+--------------------------------------+--------------'
946
947 [debug] Loaded Path actions:
948 .-------------------------------------+--------------------------------------.
949 | Path | Private |
950 +-------------------------------------+--------------------------------------+
1390ef0e 951 | / | /default |
952 | / | /index |
953 | /books | /books/index |
3533daff 954 | /books/list | /books/list |
955 '-------------------------------------+--------------------------------------'
956
acbd7bdd 957 [info] MyApp powered by Catalyst 5.71000
958 You can connect to your server at http://debian:3000
3533daff 959
1390ef0e 960B<NOTE:> Be sure you run the C<script/myapp_server.pl> command from
961the 'base' directory of your application, not inside the C<script>
962directory itself or it will not be able to locate the C<myapp.db>
963database file. You can use a fully qualified or a relative path to
964locate the database file, but we did not specify that when we ran the
3533daff 965model helper earlier.
966
967Some things you should note in the output above:
968
969=over 4
970
1390ef0e 971=item *
3533daff 972
1390ef0e 973Catalyst::Model::DBIC::Schema dynamically created three model classes,
974one to represent each of the three tables in our database
d0496197 975(C<MyApp::Model::DB::Authors>, C<MyApp::Model::DB::BookAuthors>,
976and C<MyApp::Model::DB::Books>).
3533daff 977
1390ef0e 978=item *
3533daff 979
980The "list" action in our Books controller showed up with a path of
981C</books/list>.
982
983=back
984
985Point your browser to L<http://localhost:3000> and you should still get
986the Catalyst welcome page.
987
988Next, to view the book list, change the URL in your browser to
989L<http://localhost:3000/books/list>. You should get a list of the five
1390ef0e 990books loaded by the C<myapp01.sql> script above without any formatting.
991The rating for each book should appear on each row, but the "Author(s)"
191dee29 992column will still be blank (we will fill that in later).
3533daff 993
a46b474e 994Also notice in the output of the C<script/myapp_server.pl> that
995DBIx::Class used the following SQL to retrieve the data:
3533daff 996
997 SELECT me.id, me.title, me.rating FROM books me
998
999because we enabled DBIC_TRACE.
1000
0c51850e 1001You now have the beginnings of a simple but workable web application.
3533daff 1002Continue on to future sections and we will develop the application
1003more fully.
1004
1005
1390ef0e 1006=head1 CREATE A WRAPPER FOR THE VIEW
1007
acbd7bdd 1008When using TT, you can (and should) create a wrapper that will
1390ef0e 1009literally wrap content around each of your templates. This is
1010certainly useful as you have one main source for changing things that
1011will appear across your entire site/application instead of having to
1012edit many individual files.
1013
1014
1015=head2 Configure TT.pm For The Wrapper
1016
1017In order to create a wrapper, you must first edit your TT view and
1018tell it where to find your wrapper file. Your TT view is located in
1019C<lib/MyApp/View/TT.pm>.
1020
1021Edit C<lib/MyApp/View/TT.pm> and change it to match the following:
1022
1023 __PACKAGE__->config(
1024 # Change default TT extension
1025 TEMPLATE_EXTENSION => '.tt2',
1026 # Set the location for TT files
1027 INCLUDE_PATH => [
c2dfb562 1028 MyApp->path_to( 'root', 'src' ),
1390ef0e 1029 ],
1030 # Set to 1 for detailed timer stats in your HTML as comments
1031 TIMER => 0,
1032 # This is your wrapper template located in the 'root/src'
1033 WRAPPER => 'wrapper.tt2',
1034 );
1035
1036
1037=head2 Create the Wrapper Template File and Stylesheet
1038
1039Next you need to set up your wrapper template. Basically, you'll want
1040to take the overall layout of your site and put it into this file.
1041For the tutorial, open C<root/src/wrapper.tt2> and input the following:
1042
1043 <?xml version="1.0" encoding="UTF-8"?>
1044 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
1045 <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
1046 <head>
1047 <title>[% template.title or "My Catalyst App!" %]</title>
1048 <link rel="stylesheet" href="[% c.uri_for('/static/css/main.css') %]" />
1049 </head>
1050
1051 <body>
1052 <div id="outer">
1053 <div id="header">
1054 [%# Your logo could go here -%]
1055 <img src="[% c.uri_for('/static/images/btn_88x31_powered.png') %]" />
1056 [%# Insert the page title -%]
1057 <h1>[% template.title or site.title %]</h1>
1058 </div>
1059
1060 <div id="bodyblock">
1061 <div id="menu">
1062 Navigation:
1063 <ul>
1064 <li><a href="[% c.uri_for('/books/list') %]">Home</a></li>
1065 <li><a href="[% c.uri_for('/') %]" title="Catalyst Welcome Page">Welcome</a></li>
1390ef0e 1066 </ul>
1067 </div><!-- end menu -->
1068
1069 <div id="content">
1070 [%# Status and error messages %]
1071 <span class="message">[% status_msg %]</span>
1072 <span class="error">[% error_msg %]</span>
1073 [%# This is where TT will stick all of your template's contents. -%]
1074 [% content %]
1075 </div><!-- end content -->
1076 </div><!-- end bodyblock -->
1077
1078 <div id="footer">Copyright (c) your name goes here</div>
c2dfb562 1079 </div><!-- end outer -->
1390ef0e 1080
1081 </body>
1082 </html>
1083
1084Notice the status and error message sections in the code above:
1085
1086 <span class="status">[% status_msg %]</span>
1087 <span class="error">[% error_msg %]</span>
1088
1089If we set either message in the Catalyst stash (e.g.,
1090C<$c-E<gt>stash-E<gt>{status_msg} = 'Request was successful!'>) it
1091will be displayed whenever any view used by that request is rendered.
1092The C<message> and C<error> CSS styles can be customized to suit your
1093needs in the C<root/static/css/main.css> file we create below.
1094
1095B<Notes:>
1096
1097=over 4
1098
1099=item *
1100
1101The Catalyst stash only lasts for a single HTTP request. If
1102you need to retain information across requests you can use
1103L<Catalyst::Plugin::Session|Catalyst::Plugin::Session> (we will use
4b4d3884 1104Catalyst sessions in the Authentication chapter of the tutorial).
1390ef0e 1105
1106=item *
1107
1108Although it is beyond the scope of this tutorial, you may wish to use
1109a JavaScript or AJAX tool such as jQuery (L<http://www.jquery.com>) or
1110Dojo (L<http://www.dojotoolkit.org>).
1111
1112=back
1113
1114
1115=head3 Create A Basic Stylesheet
1116
1117First create a central location for stylesheets under the static
1118directory:
1119
1120 $ mkdir root/static/css
1121
1122Then open the file C<root/static/css/main.css> (the file referenced in
1123the stylesheet href link of our wrapper above) and add the following
1124content:
1125
1126 #header {
1127 text-align: center;
1128 }
1129 #header h1 {
1130 margin: 0;
1131 }
1132 #header img {
1133 float: right;
1134 }
1135 #footer {
1136 text-align: center;
1137 font-style: italic;
1138 padding-top: 20px;
1139 }
1140 #menu {
1141 font-weight: bold;
1142 background-color: #ddd;
1143 }
1144 #menu ul {
1145 list-style: none;
1146 float: left;
1147 margin: 0;
1148 padding: 0 0 50% 5px;
1149 font-weight: normal;
1150 background-color: #ddd;
1151 width: 100px;
1152 }
1153 #content {
1154 margin-left: 120px;
1155 }
1156 .message {
1157 color: #390;
1158 }
1159 .error {
1160 color: #f00;
1161 }
1162
1163You may wish to check out a "CSS Framework" like Emastic
1164(L<http://code.google.com/p/emastic/>) as a way to quickly
1165provide lots of high-quality CSS functionality.
1166
1167
1168=head2 Test Run The Application
1169
1170Restart the development server and hit "Reload" in your web browser
1171and you should now see a formatted version of our basic book list.
1172Although our wrapper and stylesheet are obviously very simple, you
1173should see how it allows us to control the overall look of an entire
1174website from two central files. To add new pages to the site, just
1175provide a template that fills in the C<content> section of our wrapper
1176template -- the wrapper will provide the overall feel of the page.
1177
1178
a46b474e 1179=head2 Updating the Generated DBIx::Class Result Class Files
3533daff 1180
acbd7bdd 1181Let's manually add some relationship information to the auto-generated
1182Result Class files. (Note: if you are using a database other than
1183SQLite, such as PostgreSQL, then the relationship could have been
1184automatically placed in the Result Class files. If so, you can skip
4ab6212d 1185this step.) First edit C<lib/MyApp/Schema/Result/Books.pm> and add the
acbd7bdd 1186following text below the C<# You can replace this text...> comment:
3533daff 1187
1188 #
1189 # Set relationships:
1390ef0e 1190 #
3533daff 1191
1192 # has_many():
1193 # args:
1194 # 1) Name of relationship, DBIC will create accessor with this name
1195 # 2) Name of the model class referenced by this relationship
1435672d 1196 # 3) Column name in *foreign* table (aka, foreign key in peer table)
4ab6212d 1197 __PACKAGE__->has_many(book_authors => 'MyApp::Schema::Result::BookAuthors', 'book_id');
3533daff 1198
1199 # many_to_many():
1200 # args:
1201 # 1) Name of relationship, DBIC will create accessor with this name
1390ef0e 1202 # 2) Name of has_many() relationship this many_to_many() is shortcut for
1203 # 3) Name of belongs_to() relationship in model class of has_many() above
3533daff 1204 # You must already have the has_many() defined to use a many_to_many().
1205 __PACKAGE__->many_to_many(authors => 'book_authors', 'author');
1206
1207
1208B<Note:> Be careful to put this code I<above> the C<1;> at the end of the
1209file. As with any Perl package, we need to end the last line with
1210a statement that evaluates to C<true>. This is customarily done with
1211C<1;> on a line by itself.
1212
acbd7bdd 1213C<Important Note:> Although this tutorial uses plural names for both
1214the names of the SQL tables and therefore the Result Classes (after
1215all, C<Schema::Loader> automatically named the Result Classes from the
a46b474e 1216names of the SQL tables it found), DBIx::Class users prefer singular
1217names for these items. B<Please try to use singular table and DBIC
acbd7bdd 1218model/Result Class names in your applications.> This tutorial will
1219migrate to singular names as soon as possible (patches welcomed).
1220B<Note that while singular is preferred for the DBIC model, plural is
1221perfectly acceptable for the names of the controller classes.> After
1222all, the C<Books.pm> controller operates on multiple books.
1223
a46b474e 1224This code defines both a C<has_many> and a C<many_to_many>
1225relationship. The C<many_to_many> relationship is optional, but it
1226makes it easier to map a book to its collection of authors. Without
1227it, we would have to "walk" though the C<book_authors> table as in
1228C<$book-E<gt>book_authors-E<gt>first-E<gt>author-E<gt>last_name> (we
1229will see examples on how to use DBIx::Class objects in your code soon,
1390ef0e 1230but note that because C<$book-E<gt>book_authors> can return multiple
1231authors, we have to use C<first> to display a single author).
a46b474e 1232C<many_to_many> allows us to use the shorter C<$book-E<gt>authors-
1233E<gt>first-E<gt>last_name>. Note that you cannot define a
1234C<many_to_many> relationship without also having the C<has_many>
1235relationship in place.
3533daff 1236
4ab6212d 1237Then edit C<lib/MyApp/Schema/Result/Authors.pm> and add relationship
3533daff 1238information as follows (again, be careful to put in above the C<1;> but
1239below the C<# DO NOT MODIFY THIS OR ANYTHING ABOVE!> comment):
1240
1241 #
1242 # Set relationships:
1243 #
1244
1245 # has_many():
1246 # args:
4d63a0d5 1247 # 1) Name of relationship, DBIC will create an accessor with this name
3533daff 1248 # 2) Name of the model class referenced by this relationship
1435672d 1249 # 3) Column name in *foreign* table (aka, foreign key in peer table)
4ab6212d 1250 __PACKAGE__->has_many(book_author => 'MyApp::Schema::Result::BookAuthors', 'author_id');
3533daff 1251
1252 # many_to_many():
1253 # args:
1254 # 1) Name of relationship, DBIC will create accessor with this name
1255 # 2) Name of has_many() relationship this many_to_many() is shortcut for
1390ef0e 1256 # 3) Name of belongs_to() relationship in model class of has_many() above
3533daff 1257 # You must already have the has_many() defined to use a many_to_many().
1258 __PACKAGE__->many_to_many(books => 'book_author', 'book');
1259
1390ef0e 1260Finally, do the same for the "join table,"
4ab6212d 1261C<lib/MyApp/Schema/Result/BookAuthors.pm>:
3533daff 1262
1263 #
1264 # Set relationships:
1265 #
1266
1267 # belongs_to():
1268 # args:
1269 # 1) Name of relationship, DBIC will create accessor with this name
1270 # 2) Name of the model class referenced by this relationship
1271 # 3) Column name in *this* table
4ab6212d 1272 __PACKAGE__->belongs_to(book => 'MyApp::Schema::Result::Books', 'book_id');
3533daff 1273
1274 # belongs_to():
1275 # args:
1276 # 1) Name of relationship, DBIC will create accessor with this name
1277 # 2) Name of the model class referenced by this relationship
1278 # 3) Column name in *this* table
4ab6212d 1279 __PACKAGE__->belongs_to(author => 'MyApp::Schema::Result::Authors', 'author_id');
3533daff 1280
1281
1390ef0e 1282=head2 Run The Application
3533daff 1283
4d63a0d5 1284Run the Catalyst development server script with the C<DBIC_TRACE> option
1285(it might still be enabled from earlier in the tutorial, but here is an
1286alternate way to specify the option just in case):
3533daff 1287
1288 $ DBIC_TRACE=1 script/myapp_server.pl
1289
1390ef0e 1290Make sure that the application loads correctly and that you see the
1291three dynamically created model class (one for each of the
4ab6212d 1292Result Classes we created).
3533daff 1293
acbd7bdd 1294Then hit the URL L<http://localhost:3000/books/list> with your browser
1295and be sure that the book list is displayed via the relationships
1296established above. You can leave the development server running for
1297the next step if you wish.
3533daff 1298
c2dfb562 1299B<Note:> You will not see the authors yet because the view does not yet
1300use the new relations. Read on to the next section where we update the
1301template to do that.
3533daff 1302
1303
1304=head1 UPDATING THE VIEW
1305
acbd7bdd 1306Let's add a new column to our book list page that takes advantage of
1307the relationship information we manually added to our schema files in
a46b474e 1308the previous section. Edit C<root/src/books/list.tt2> and replace
1309the "empty" tabase cell with the following:
3533daff 1310
acbd7bdd 1311 ...
3533daff 1312 <td>
1313 [% # First initialize a TT variable to hold a list. Then use a TT FOREACH -%]
1314 [% # loop in 'side effect notation' to load just the last names of the -%]
a0c5188a 1315 [% # authors into the list. Note that the 'push' TT vmethod does not print -%]
3533daff 1316 [% # a value, so nothing will be printed here. But, if you have something -%]
1317 [% # in TT that does return a method and you don't want it printed, you -%]
1318 [% # can: 1) assign it to a bogus value, or 2) use the CALL keyword to -%]
1319 [% # call it and discard the return value. -%]
1320 [% tt_authors = [ ];
1321 tt_authors.push(author.last_name) FOREACH author = book.authors %]
1322 [% # Now use a TT 'virtual method' to display the author count in parens -%]
1323 [% # Note the use of the TT filter "| html" to escape dangerous characters -%]
1324 ([% tt_authors.size | html %])
1325 [% # Use another TT vmethod to join & print the names & comma separators -%]
1326 [% tt_authors.join(', ') | html %]
1327 </td>
acbd7bdd 1328 ...
3533daff 1329
1390ef0e 1330Then hit "Reload" in your browser (note that you don't need to reload
3533daff 1331the development server or use the C<-r> option when updating TT
1390ef0e 1332templates) and you should now see the number of authors each book has
1333along with a comma-separated list of the authors' last names. (If you
1334didn't leave the development server running from the previous step,
1335you will obviously need to start it before you can refresh your
1336browser window.)
1337
1338If you are still running the development server with C<DBIC_TRACE>
1339enabled, you should also now see five more C<SELECT> statements in the
1340debug output (one for each book as the authors are being retrieved by
a46b474e 1341DBIx::Class):
3533daff 1342
c2dfb562 1343 SELECT me.id, me.title, me.rating FROM books me:
acbd7bdd 1344 SELECT author.id, author.first_name, author.last_name FROM book_authors me
1345 JOIN authors author ON ( author.id = me.author_id ) WHERE ( me.book_id = ? ): '1'
1346 SELECT author.id, author.first_name, author.last_name FROM book_authors me
1347 JOIN authors author ON ( author.id = me.author_id ) WHERE ( me.book_id = ? ): '2'
1348 SELECT author.id, author.first_name, author.last_name FROM book_authors me
1349 JOIN authors author ON ( author.id = me.author_id ) WHERE ( me.book_id = ? ): '3'
1350 SELECT author.id, author.first_name, author.last_name FROM book_authors me
1351 JOIN authors author ON ( author.id = me.author_id ) WHERE ( me.book_id = ? ): '4'
1352 SELECT author.id, author.first_name, author.last_name FROM book_authors me
1353 JOIN authors author ON ( author.id = me.author_id ) WHERE ( me.book_id = ? ): '5'
c2dfb562 1354
1355Also note in C<root/src/books/list.tt2> that we are using "| html", a
1356type of TT filter, to escape characters such as E<lt> and E<gt> to &lt;
1357and &gt; and avoid various types of dangerous hacks against your
1358application. In a real application, you would probably want to put
1359"| html" at the end of every field where a user has control over the
1360information that can appear in that field (and can therefore inject
1361markup or code if you don't "neutralize" those fields). In addition to
1362"| html", Template Toolkit has a variety of other useful filters that
1363can found in the documentation for
1364L<Template::Filters|Template::Filters>.
3533daff 1365
1366
1390ef0e 1367=head1 RUNNING THE APPLICATION FROM THE COMMAND LINE
1368
1369In some situations, it can be useful to run your application and
1370display a page without using a browser. Catalyst lets you do this
1371using the C<scripts/myapp_test.pl> script. Just supply the URL you
1372wish to display and it will run that request through the normal
1373controller dispatch logic and use the appropriate view to render the
1374output (obviously, complex pages may dump a lot of text to your
1375terminal window). For example, if you type:
1376
1377 $ script/myapp_test.pl "/books/list"
1378
1379You should get the same text as if you visited
1380L<http://localhost:3000/books/list> with the normal development server
1381and asked your browser to view the page source.
3533daff 1382
1390ef0e 1383
1384=head1 OPTIONAL INFORMATION
1385
4b4d3884 1386B<NOTE: The rest of this chapter of the tutorial is optional. You can
1387skip to Chapter 4, L<Basic CRUD|Catalyst::Manual::Tutorial::BasicCRUD>,
3533daff 1388if you wish.>
1389
acbd7bdd 1390
8a472b34 1391=head2 Using 'RenderView' for the Default View
1390ef0e 1392
1393Once your controller logic has processed the request from a user, it
1394forwards processing to your view in order to generate the appropriate
3533daff 1395response output. Catalyst uses
1390ef0e 1396L<Catalyst::Action::RenderView|Catalyst::Action::RenderView> by
4d63a0d5 1397default to automatically perform this operation. If you look in
1390ef0e 1398C<lib/MyApp/Controller/Root.pm>, you should see the empty
3533daff 1399definition for the C<sub end> method:
1400
1401 sub end : ActionClass('RenderView') {}
1402
1390ef0e 1403The following bullet points provide a quick overview of the
3533daff 1404C<RenderView> process:
1405
1406=over 4
1407
1408=item *
1409
1410C<Root.pm> is designed to hold application-wide logic.
1411
1412=item *
1413
1390ef0e 1414At the end of a given user request, Catalyst will call the most specific
1415C<end> method that's appropriate. For example, if the controller for a
1416request has an C<end> method defined, it will be called. However, if
1417the controller does not define a controller-specific C<end> method, the
3533daff 1418"global" C<end> method in C<Root.pm> will be called.
1419
1420=item *
1421
1422Because the definition includes an C<ActionClass> attribute, the
1423L<Catalyst::Action::RenderView|Catalyst::Action::RenderView> logic
1424will be executed B<after> any code inside the definition of C<sub end>
1425is run. See L<Catalyst::Manual::Actions|Catalyst::Manual::Actions>
1426for more information on C<ActionClass>.
1427
1428=item *
1429
1390ef0e 1430Because C<sub end> is empty, this effectively just runs the default
1431logic in C<RenderView>. However, you can easily extend the
1432C<RenderView> logic by adding your own code inside the empty method body
1433(C<{}>) created by the Catalyst Helpers when we first ran the
1434C<catalyst.pl> to initialize our application. See
1435L<Catalyst::Action::RenderView|Catalyst::Action::RenderView> for more
4d63a0d5 1436detailed information on how to extend C<RenderView> in C<sub end>.
3533daff 1437
1438=back
1439
1440
1441=head2 Using The Default Template Name
1442
1390ef0e 1443By default, C<Catalyst::View::TT> will look for a template that uses the
1444same name as your controller action, allowing you to save the step of
1445manually specifying the template name in each action. For example, this
1446would allow us to remove the
1447C<$c-E<gt>stash-E<gt>{template} = 'books/list.tt2';> line of our
1448C<list> action in the Books controller. Open
3533daff 1449C<lib/MyApp/Controller/Books.pm> in your editor and comment out this line
1450to match the following (only the C<$c-E<gt>stash-E<gt>{template}> line
1451has changed):
1452
1453 =head2 list
1454
1455 Fetch all book objects and pass to books/list.tt2 in stash to be displayed
1456
1457 =cut
1458
1459 sub list : Local {
1460 # Retrieve the usual Perl OO '$self' for this object. $c is the Catalyst
1461 # 'Context' that's used to 'glue together' the various components
1462 # that make up the application
1463 my ($self, $c) = @_;
1464
1465 # Retrieve all of the book records as book model objects and store in the
1466 # stash where they can be accessed by the TT template
d0496197 1467 $c->stash->{books} = [$c->model('DB::Books')->all];
3533daff 1468
1469 # Set the TT template to use. You will almost always want to do this
1470 # in your action methods (actions methods respond to user input in
1471 # your controllers).
1472 #$c->stash->{template} = 'books/list.tt2';
1473 }
1474
3533daff 1475
1390ef0e 1476You should now be able to restart the development server as per the
3533daff 1477previous section and access the L<http://localhost:3000/books/list>
1478as before.
1479
1480B<NOTE:> Please note that if you use the default template technique,
1481you will B<not> be able to use either the C<$c-E<gt>forward> or
4b4d3884 1482the C<$c-E<gt>detach> mechanisms (these are discussed in Chapter 2 and
1483Chapter 9 of the Tutorial).
3533daff 1484
1485
4d63a0d5 1486=head2 Return To A Manually Specified Template
3533daff 1487
1488In order to be able to use C<$c-E<gt>forward> and C<$c-E<gt>detach>
1489later in the tutorial, you should remove the comment from the
1490statement in C<sub list> in C<lib/MyApp/Controller/Books.pm>:
1491
1492 $c->stash->{template} = 'books/list.tt2';
1493
1390ef0e 1494Then delete the C<TEMPLATE_EXTENSION> line in
3533daff 1495C<lib/MyApp/View/TT.pm>.
1496
1390ef0e 1497You should then be able to restart the development server and
3533daff 1498access L<http://localhost:3000/books/list> in the same manner as
1499with earlier sections.
1500
1501
1502=head1 AUTHOR
1503
1504Kennedy Clark, C<hkclark@gmail.com>
1505
1506Please report any errors, issues or suggestions to the author. The
1507most recent version of the Catalyst Tutorial can be found at
82ab4bbf 1508L<http://dev.catalyst.perl.org/repos/Catalyst/Catalyst-Manual/5.70/trunk/lib/Catalyst/Manual/Tutorial/>.
3533daff 1509
45c7830f 1510Copyright 2006-2008, Kennedy Clark, under Creative Commons License
8482d557 1511(L<http://creativecommons.org/licenses/by-sa/3.0/us/>).