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