Fix some typos and clarifications.
[catagits/Catalyst-Runtime.git] / lib / Catalyst / Manual / Tutorial / CatalystBasics.pod
CommitLineData
4d583dd8 1=head1 NAME
2
64ccd8a8 3Catalyst::Manual::Tutorial::CatalystBasics - Catalyst Tutorial - Part 2: Catalyst Application Development Basics
4d583dd8 4
5
4d583dd8 6=head1 OVERVIEW
7
8This is B<Part 2 of 9> for the Catalyst tutorial.
9
64ccd8a8 10L<Tutorial Overview|Catalyst::Manual::Tutorial>
4d583dd8 11
12=over 4
13
14=item 1
15
16L<Introduction|Catalyst::Manual::Tutorial::Intro>
17
18=item 2
19
20B<Catalyst Basics>
21
22=item 3
23
653f4595 24L<Basic CRUD|Catalyst::Manual::Tutorial::BasicCRUD>
4d583dd8 25
26=item 4
27
28L<Authentication|Catalyst::Manual::Tutorial::Authentication>
29
30=item 5
31
32L<Authorization|Catalyst::Manual::Tutorial::Authorization>
33
34=item 6
35
36L<Debugging|Catalyst::Manual::Tutorial::Debugging>
37
38=item 7
39
40L<Testing|Catalyst::Manual::Tutorial::Testing>
41
42=item 8
43
653f4595 44L<Advanced CRUD|Catalyst::Manual::Tutorial::AdvancedCRUD>
4d583dd8 45
46=item 9
47
7d310f12 48L<Appendices|Catalyst::Manual::Tutorial::Appendices>
4d583dd8 49
50=back
51
208513f1 52
4d583dd8 53=head1 DESCRIPTION
54
64ccd8a8 55In this part of the tutorial, we will create a very basic Catalyst web
56application. Though simple in many respects, this section will already
57demonstrate a number of powerful capabilities such as:
4d583dd8 58
59=over 4
60
61=item * Helper Scripts
62
64ccd8a8 63Catalyst helper scripts that can be used to rapidly bootstrap the
64skeletal structure of an application.
4d583dd8 65
66=item * MVC
67
64ccd8a8 68Model/View/Controller (MVC) provides an architecture that facilitates a
69clean "separation of control" between the different portions of your
653f4595 70application. Given that many other documents cover this subject in
64ccd8a8 71detail, MVC will not be discussed in depth here (for an excellent
72introduction to MVC and general Catalyst concepts, please see
653f4595 73L<Catalyst::Manual::About>. In short:
4d583dd8 74
75=over 4
76
77=item * Model
78
653f4595 79The model usually represents a data store. In most applications, the
80model equates to the objects that are created from and saved to your SQL
81database.
4d583dd8 82
83=item * View
84
64ccd8a8 85The view takes model objects and renders them into something for the end
653f4595 86user to look at. Normally this involves a template-generation tool that
64ccd8a8 87creates HTML for the user's web browser, but it could easily be code
653f4595 88that generates other forms such as PDF documents, e-mails, or Excel
89spreadsheets.
4d583dd8 90
91=item * Controller
92
64ccd8a8 93As suggested by its name, the controller takes user requests and routes
94them to the necessary model and view.
4d583dd8 95
96=back
97
98=item * ORM
99
653f4595 100The use of Object-Relational Mapping (ORM) technology for database
101access. Specifically, ORM provides an automated and standardized means
102to persist and restore objects to/from a relational database.
4d583dd8 103
104=back
105
64ccd8a8 106B<TIP>: Note that all of the code for this part of the tutorial can be
107pulled from the Catalyst Subversion repository in one step with the
108following command:
4d583dd8 109
7d310f12 110 svn co http://dev.catalyst.perl.org/repos/Catalyst/tags/examples/Tutorial/MyApp/5.7/CatalystBasics MyApp
4d583dd8 111
112
4d583dd8 113=head1 CREATE A CATALYST PROJECT
114
64ccd8a8 115Catalyst provides a number of helper scripts that can be used to quickly
653f4595 116flesh out the basic structure of your application. All Catalyst projects
8112f931 117begin with the C<catalyst.pl> helper (see L<Catalyst::Helper|Catalyst::Helper>
118for more information on helpers). Also note that as of Catalyst 5.7000,
119you will not have the helper scripts unless you install both
120L<Catalyst::Runtime|Catalyst::Runtime> and L<Catalyst::Devel|Catalyst::Devel>.
4d583dd8 121
64ccd8a8 122In the case of this tutorial, use the Catalyst C<catalyst.pl> script to
123initialize the framework for an application called C<MyApp>:
4d583dd8 124
125 $ catalyst.pl MyApp
208513f1 126 created "MyApp"
127 created "MyApp/script"
128 created "MyApp/lib"
129 created "MyApp/root"
130 ...
131 created "MyApp/script/myapp_create.pl"
4d583dd8 132 $ cd MyApp
133
64ccd8a8 134The C<catalyst.pl> helper script will display the names of the
135directories and files it creates.
4d583dd8 136
653f4595 137Though it's too early for any significant celebration, we already have a
138functioning application. Run the following command to run this
139application with the built-in development web server:
4d583dd8 140
208513f1 141 $ script/myapp_server.pl
142 [debug] Debug messages enabled
143 [debug] Loaded plugins:
144 .----------------------------------------------------------------------------.
145 | Catalyst::Plugin::ConfigLoader 0.06 |
146 | Catalyst::Plugin::Static::Simple 0.14 |
147 '----------------------------------------------------------------------------'
148
149 [debug] Loaded dispatcher "Catalyst::Dispatcher"
150 [debug] Loaded engine "Catalyst::Engine::HTTP"
151 [debug] Found home "/root/dev/MyApp"
152 [debug] Loaded components:
153 .-----------------------------------------------------------------+----------.
154 | Class | Type |
155 +-----------------------------------------------------------------+----------+
156 | MyApp::Controller::Root | instance |
157 '-----------------------------------------------------------------+----------'
158
159 [debug] Loaded Private actions:
160 .----------------------+--------------------------------------+--------------.
161 | Private | Class | Method |
162 +----------------------+--------------------------------------+--------------+
163 | /default | MyApp::Controller::Root | default |
164 | /end | MyApp::Controller::Root | end |
165 '----------------------+--------------------------------------+--------------'
166
8e956464 167 [info] MyApp powered by Catalyst 5.7000
208513f1 168 You can connect to your server at http://localhost.localdomain:3000
169
170Point your web browser to L<http://localhost:3000> (substituting a
171different hostname or IP address as appropriate) and you should be
172greeted by the Catalyst welcome screen. Information similar to the
173following should be appended to the logging output of the development
174server:
175
7d310f12 176 [info] *** Request 1 (0.043/s) [6003] [Fri Jul 7 13:32:53 2006] ***
208513f1 177 [debug] "GET" request for "/" from "127.0.0.1"
7d310f12 178 [info] Request took 0.067675s (14.777/s)
208513f1 179 .----------------------------------------------------------------+-----------.
180 | Action | Time |
181 +----------------------------------------------------------------+-----------+
7d310f12 182 | /default | 0.002844s |
183 | /end | 0.000207s |
208513f1 184 '----------------------------------------------------------------+-----------'
185
186Press Ctrl-C to break out of the development server.
4d583dd8 187
4d583dd8 188
4d583dd8 189=head1 CREATE A SQLITE DATABASE
190
64ccd8a8 191In this step, we make a text file with the required SQL commands to
192create a database table and load some sample data. Open C<myapp01.sql>
193in your editor and enter:
4d583dd8 194
195 --
196 -- Create a very simple database to hold book and author information
197 --
198 CREATE TABLE books (
199 id INTEGER PRIMARY KEY,
200 title TEXT ,
201 rating INTEGER
202 );
203 -- 'book_authors' is a many-to-many join table between books & authors
204 CREATE TABLE book_authors (
205 book_id INTEGER,
206 author_id INTEGER,
207 PRIMARY KEY (book_id, author_id)
208 );
209 CREATE TABLE authors (
210 id INTEGER PRIMARY KEY,
211 first_name TEXT,
212 last_name TEXT
213 );
214 ---
215 --- Load some sample data
216 ---
217 INSERT INTO books VALUES (1, 'CCSP SNRS Exam Certification Guide', 5);
218 INSERT INTO books VALUES (2, 'TCP/IP Illustrated, Volume 1', 5);
219 INSERT INTO books VALUES (3, 'Internetworking with TCP/IP Vol.1', 4);
220 INSERT INTO books VALUES (4, 'Perl Cookbook', 5);
221 INSERT INTO books VALUES (5, 'Designing with Web Standards', 5);
222 INSERT INTO authors VALUES (1, 'Greg', 'Bastien');
223 INSERT INTO authors VALUES (2, 'Sara', 'Nasseh');
224 INSERT INTO authors VALUES (3, 'Christian', 'Degu');
225 INSERT INTO authors VALUES (4, 'Richard', 'Stevens');
226 INSERT INTO authors VALUES (5, 'Douglas', 'Comer');
227 INSERT INTO authors VALUES (6, 'Tom', 'Christiansen');
228 INSERT INTO authors VALUES (7, ' Nathan', 'Torkington');
229 INSERT INTO authors VALUES (8, 'Jeffrey', 'Zeldman');
230 INSERT INTO book_authors VALUES (1, 1);
231 INSERT INTO book_authors VALUES (1, 2);
232 INSERT INTO book_authors VALUES (1, 3);
233 INSERT INTO book_authors VALUES (2, 4);
234 INSERT INTO book_authors VALUES (3, 5);
235 INSERT INTO book_authors VALUES (4, 6);
236 INSERT INTO book_authors VALUES (4, 7);
237 INSERT INTO book_authors VALUES (5, 8);
238
64ccd8a8 239B<TIP>: See Appendix 1 for tips on removing the leading spaces when
c608fae5 240cutting and pasting example code from POD-based documents.
4d583dd8 241
242Then use the following command to build a C<myapp.db> SQLite database:
243
244 $ sqlite3 myapp.db < myapp01.sql
245
64ccd8a8 246If you need to create the database more than once, you probably want to
247issue the C<rm myapp.db> command to delete the database before you use
248the C<sqlite3 myapp.db < myapp01.sql> command.
4d583dd8 249
64ccd8a8 250Once the C<myapp.db> database file has been created and initialized, you
251can use the SQLite command line environment to do a quick dump of the
252database contents:
4d583dd8 253
254 $ sqlite3 myapp.db
255 SQLite version 3.2.2
256 Enter ".help" for instructions
257 sqlite> select * from books;
258 1|CCSP SNRS Exam Certification Guide|5
259 2|TCP/IP Illustrated, Volume 1|5
260 3|Internetworking with TCP/IP Vol.1|4
261 4|Perl Cookbook|5
262 5|Designing with Web Standards|5
263 sqlite> .q
264 $
265
266Or:
267
268 $ sqlite3 myapp.db "select * from books"
269 1|CCSP SNRS Exam Certification Guide|5
270 2|TCP/IP Illustrated, Volume 1|5
271 3|Internetworking with TCP/IP Vol.1|4
272 4|Perl Cookbook|5
273 5|Designing with Web Standards|5
274
64ccd8a8 275As with most other SQL tools, if you are using the full "interactive"
276environment you need to terminate your SQL commands with a ";" (it's not
277required if you do a single SQL statement on the command line). Use
278".q" to exit from SQLite from the SQLite interactive mode and return to
279your OS command prompt.
4d583dd8 280
281
4d583dd8 282=head1 EDIT THE LIST OF CATALYST PLUGINS
283
64ccd8a8 284One of the greatest benefits of Catalyst is that it has such a large
285library of plugins available. Plugins are used to seamlessly integrate
286existing Perl modules into the overall Catalyst framework. In general,
287they do this by adding additional methods to the C<context> object
288(generally written as C<$c>) that Catalyst passes to every component
289throughout the framework.
4d583dd8 290
291By default, Catalyst enables three plugins/flags:
292
293=over 4
294
295=item *
296
297C<-Debug> Flag
298
64ccd8a8 299Enables the Catalyst debug output you saw when we started the
300C<script/myapp_server.pl> development server earlier. You can remove
301this plugin when you place your application into production.
4d583dd8 302
64ccd8a8 303As you may have noticed, C<-Debug> is not a plugin, but a I<flag>.
304Although most of the items specified on the C<use Catalyst> line of your
305application class will be plugins, Catalyst supports a limited number of
14e6feb0 306flag options (of these, C<-Debug> is the most common). See the
307documentation for C<Catalyst.pm> to get details on other flags
308(currently C<-Engine>, C<-Home>, and C<-Log>).
4d583dd8 309
64ccd8a8 310If you prefer, you can use the C<$c-E<gt>debug> method to enable debug
311messages.
4d583dd8 312
313=item *
314
315L<Catalyst::Plugin::ConfigLoader|Catalyst::Plugin::ConfigLoader>
316
653f4595 317C<ConfigLoader> provides an automatic way to load configurable
64ccd8a8 318parameters for your application from a central YAML file (versus having
319the values hard-coded inside your Perl modules). If you have not been
320exposed to YAML before, it is a human-readable data serialization format
321that can be used to read (and write) values to/from text files. We will
322see how to use this feature of Catalyst during the authentication and
323authorization sections (Part 4 and Part 5).
4d583dd8 324
4d583dd8 325=item *
326
14e6feb0 327L<Catalyst::Plugin::Static::Simple|Catalyst::Plugin::Static::Simple>
4d583dd8 328
64ccd8a8 329C<Static::Simple> provides an easy method of serving static content such
330as images and CSS files under the development server.
4d583dd8 331
332=back
333
64ccd8a8 334To modify the list of plugins, edit C<lib/MyApp.pm> (this file is
335generally referred to as your I<application class>) and delete the line
336with:
4d583dd8 337
338 use Catalyst qw/-Debug ConfigLoader Static::Simple/;
339
340Replace it with:
341
342 use Catalyst qw/
343 -Debug
344 ConfigLoader
345 Static::Simple
346
4d583dd8 347 StackTrace
4d583dd8 348 /;
349
c608fae5 350This tells Catalyst to start using one new plugin:
4d583dd8 351
352=over 4
353
354=item *
355
4d583dd8 356L<Catalyst::Plugin::StackTrace|Catalyst::Plugin::StackTrace>
357
64ccd8a8 358Adds a stack trace to the standard Catalyst "debug screen" (this is the
359screen Catalyst sends to your browser when an error occurs).
4d583dd8 360
c19d127e 361Note: L<StackTrace|Catalyst::Plugin::StackTrace> output appears in your
362browser, not in the console window from which you're running your
363application, which is where logging output usually goes.
4d583dd8 364
4d583dd8 365=back
366
64ccd8a8 367Note that when specifying plugins on the C<use Catalyst> line, you can
71dedf57 368omit C<Catalyst::Plugin::> from the name. Additionally, you can spread
64ccd8a8 369the plugin names across multiple lines as shown here, or place them all
370on one (or more) lines as with the default configuration.
4d583dd8 371
c608fae5 372B<TIP:> You may see examples that include the
373L<Catalyst::Plugin::DefaultEnd|Catalyst::Plugin::DefaultEnd>
8e956464 374plugins. As of Catalyst 5.7000, C<DefaultEnd> has been
c608fae5 375deprecated in favor of
376L<Catalyst::Action::RenderView|Catalyst::Action::RenderView>
377(as the name of the package suggests, C<RenderView> is not
378a plugin, but an action). The purpose of both is essentially the same:
208513f1 379forward processing to the view to be rendered. Applications generated
8e956464 380under 5.7000 should automatically use C<RenderView> and "just work"
208513f1 381for most applications. For more information on C<RenderView> and
382the various options for forwarding to your view logic, please refer
383to the "Using RenderView for the Default View" section under
384"CATALYST VIEWS" below.
c608fae5 385
386
4d583dd8 387=head1 DATABASE ACCESS WITH C<DBIx::Class>
388
64ccd8a8 389Catalyst can be used with virtually any form of persistent datastore
14e6feb0 390available via Perl. For example,
391L<Catalyst::Model::DBI|Catalyst::Model::DBI> can be used to
392easily access databases through the traditional Perl C<DBI> interface.
71dedf57 393However, most Catalyst applications use some form of ORM technology to
64ccd8a8 394automatically create and save model objects as they are used. Although
14e6feb0 395Tony Bowden's L<Class::DBI|Class::DBI> has been the traditional
396Perl ORM engine, Matt Trout's L<DBIx::Class|DBIx::Class> (abbreviated
397as "DBIC") has rapidly emerged as the Perl-based ORM technology of choice.
398Most new Catalyst applications rely on DBIC, as will this tutorial.
4d583dd8 399
14e6feb0 400Note: See L<Catalyst:: Model::CDBI> for more information on using
401Catalyst with L<Class::DBI|Class::DBI>.
4d583dd8 402
403=head2 Create a DBIC Schema File
404
64ccd8a8 405DBIx::Class uses a schema file to load other classes that represent the
406tables in your database (DBIC refers to these "table objects" as "result
71dedf57 407sources"; see L<DBIx::Class::ResultSource>). In this case, we want to
408load the model object for the C<books>, C<book_authors>, and C<authors>
409tables created in the previous step.
4d583dd8 410
411Open C<lib/MyAppDB.pm> in your editor and insert:
412
413 package MyAppDB;
414
415 =head1 NAME
416
71dedf57 417 MyAppDB - DBIC Schema Class
4d583dd8 418
419 =cut
420
421 # Our schema needs to inherit from 'DBIx::Class::Schema'
422 use base qw/DBIx::Class::Schema/;
423
424 # Need to load the DB Model classes here.
425 # You can use this syntax if you want:
426 # __PACKAGE__->load_classes(qw/Book BookAuthor Author/);
427 # Also, if you simply want to load all of the classes in a directory
428 # of the same name as your schema class (as we do here) you can use:
429 # __PACKAGE__->load_classes(qw//);
430 # But the variation below is more flexible in that it can be used to
431 # load from multiple namespaces.
432 __PACKAGE__->load_classes({
433 MyAppDB => [qw/Book BookAuthor Author/]
434 });
435
436 1;
437
64ccd8a8 438B<Note:> C<__PACKAGE__> is just a shorthand way of referencing the name
439of the package where it is used. Therefore, in C<MyAppDB.pm>,
14e6feb0 440C<__PACKAGE__> is equivalent to C<MyAppDB>.
4d583dd8 441
442
443=head2 Create the DBIC "Result Source" Files
444
64ccd8a8 445In this step, we create "table classes" (again, these are called a
71dedf57 446"result source" classes in DBIC) that act as model objects for the
64ccd8a8 447C<books>, C<book_authors>, and C<authors> tables in our database.
4d583dd8 448
449First, create a directory to hold the class:
450
451 $ mkdir lib/MyAppDB
452
453Then open C<lib/MyAppDB/Book.pm> in your editor and enter:
454
455 package MyAppDB::Book;
456
457 use base qw/DBIx::Class/;
458
459 # Load required DBIC stuff
460 __PACKAGE__->load_components(qw/PK::Auto Core/);
461 # Set the table name
462 __PACKAGE__->table('books');
463 # Set columns in table
464 __PACKAGE__->add_columns(qw/id title rating/);
465 # Set the primary key for the table
466 __PACKAGE__->set_primary_key(qw/id/);
467
468 #
469 # Set relationships:
470 #
471
472 # has_many():
473 # args:
474 # 1) Name of relationship, DBIC will create accessor with this name
475 # 2) Name of the model class referenced by this relationship
476 # 3) Column name in *foreign* table
477 __PACKAGE__->has_many(book_authors => 'MyAppDB::BookAuthor', 'book_id');
478
479 # many_to_many():
480 # args:
481 # 1) Name of relationship, DBIC will create accessor with this name
482 # 2) Name of has_many() relationship this many_to_many() is shortcut for
483 # 3) Name of belongs_to() relationship in model class of has_many() above
484 # You must already have the has_many() defined to use a many_to_many().
485 __PACKAGE__->many_to_many(authors => 'book_authors', 'author');
486
487
488 =head1 NAME
489
490 MyAppDB::Book - A model object representing a book.
491
492 =head1 DESCRIPTION
493
494 This is an object that represents a row in the 'books' table of your application
495 database. It uses DBIx::Class (aka, DBIC) to do ORM.
496
497 For Catalyst, this is designed to be used through MyApp::Model::MyAppDB.
498 Offline utilities may wish to use this class directly.
499
500 =cut
501
502 1;
503
64ccd8a8 504This defines both a C<has_many> and a C<many_to_many> relationship. The
505C<many_to_many> relationship is optional, but it makes it easier to map
506a book to its collection of authors. Without it, we would have to
507"walk" though the C<book_authors> table as in
508C<$book-E<gt>book_authors-E<gt>first-E<gt>author-E<gt>last_name> (we
509will see examples on how to use DBIC objects in your code soon, but note
510that because C<$book-E<gt>book_authors> can return multiple authors, we
71dedf57 511have to use C<first> to display a single author). C<many_to_many> allows
512us to use the shorter C<$book-E<gt>authors-E<gt>first-E<gt>last_name>.
513Note that you cannot define a C<many_to_many> relationship without also
514having the C<has_many> relationship in place.
4d583dd8 515
516Next, open C<lib/MyAppDB/Author.pm> in your editor and enter:
517
518 package MyAppDB::Author;
519
520 use base qw/DBIx::Class/;
521
522 # Load required DBIC stuff
523 __PACKAGE__->load_components(qw/PK::Auto Core/);
524 # Set the table name
525 __PACKAGE__->table('authors');
526 # Set columns in table
527 __PACKAGE__->add_columns(qw/id first_name last_name/);
528 # Set the primary key for the table
529 __PACKAGE__->set_primary_key(qw/id/);
208513f1 530
4d583dd8 531 #
532 # Set relationships:
533 #
534
535 # has_many():
536 # args:
537 # 1) Name of relationship, DBIC will create accessor with this name
538 # 2) Name of the model class referenced by this relationship
539 # 3) Column name in *foreign* table
540 __PACKAGE__->has_many(book_author => 'MyAppDB::BookAuthor', 'author_id');
541
542 # many_to_many():
543 # args:
544 # 1) Name of relationship, DBIC will create accessor with this name
545 # 2) Name of has_many() relationship this many_to_many() is shortcut for
546 # 3) Name of belongs_to() relationship in model class of has_many() above
547 # You must already have the has_many() defined to use a many_to_many().
548 __PACKAGE__->many_to_many(books => 'book_author', 'book');
549
550
551 =head1 NAME
552
553 MyAppDB::Author - A model object representing an author of a book (if a book has
554 multiple authors, each will be represented be separate Author object).
555
556 =head1 DESCRIPTION
557
558 This is an object that represents a row in the 'authors' table of your application
559 database. It uses DBIx::Class (aka, DBIC) to do ORM.
560
561 For Catalyst, this is designed to be used through MyApp::Model::MyAppDB.
562 Offline utilities may wish to use this class directly.
563
564 =cut
565
566 1;
567
568Finally, open C<lib/MyAppDB/BookAuthor.pm> in your editor and enter:
569
570 package MyAppDB::BookAuthor;
571
572 use base qw/DBIx::Class/;
573
574 # Load required DBIC stuff
575 __PACKAGE__->load_components(qw/PK::Auto Core/);
576 # Set the table name
577 __PACKAGE__->table('book_authors');
578 # Set columns in table
579 __PACKAGE__->add_columns(qw/book_id author_id/);
580 # Set the primary key for the table
581 __PACKAGE__->set_primary_key(qw/book_id author_id/);
582
583 #
584 # Set relationships:
585 #
586
587 # belongs_to():
588 # args:
589 # 1) Name of relationship, DBIC will create accessor with this name
590 # 2) Name of the model class referenced by this relationship
591 # 3) Column name in *this* table
592 __PACKAGE__->belongs_to(book => 'MyAppDB::Book', 'book_id');
208513f1 593
4d583dd8 594 # belongs_to():
595 # args:
596 # 1) Name of relationship, DBIC will create accessor with this name
597 # 2) Name of the model class referenced by this relationship
598 # 3) Column name in *this* table
599 __PACKAGE__->belongs_to(author => 'MyAppDB::Author', 'author_id');
600
601
602 =head1 NAME
603
604 MyAppDB::BookAuthor - A model object representing the JOIN between an author and
605 a book.
606
607 =head1 DESCRIPTION
608
609 This is an object that represents a row in the 'book_authors' table of your
610 application database. It uses DBIx::Class (aka, DBIC) to do ORM.
208513f1 611
4d583dd8 612 You probably won't need to use this class directly -- it will be automatically
613 used by DBIC where joins are needed.
614
615 For Catalyst, this is designed to be used through MyApp::Model::MyAppDB.
616 Offline utilities may wish to use this class directly.
617
618 =cut
619
620 1;
621
64ccd8a8 622B<Note:> This sample application uses a plural form for the database
623tables (e.g., C<books> and C<authors>) and a singular form for the model
624objects (e.g., C<Book> and C<Author>); however, Catalyst places no
625restrictions on the naming conventions you wish to use.
4d583dd8 626
4d583dd8 627=head2 Use C<Catalyst::Model::DBIC::Schema> To Load The Model Class
628
14e6feb0 629When L<Catalyst::Model::DBIC::Schema|Catalyst::Model::DBIC::Schema> is
64ccd8a8 630in use, Catalyst essentially reads an existing copy of your database
631model and creates a new set of objects under C<MyApp::Model> for use
632inside of Catalyst.
4d583dd8 633
14e6feb0 634B<Note:> With
635L<Catalyst::Model::DBIC::Schema|Catalyst::Model::DBIC::Schema> you
636essentially end up with two sets of model classes (only one of which
637you write... the other set is created automatically in memory when
638your Catalyst application initializes). For this tutorial application,
639the important points to remember are: you write the I<result source>
640files in C<MyAppDB>, but I<within Catalyst> you use the I<automatically
641created model classes> in C<MyApp::Model>.
4d583dd8 642
14e6feb0 643Use the
644L<Catalyst::Helper::Model::DBIC::Schema|Catalyst::Helper::Model::DBIC::Schema>
645helper script to create the model class that loads up the model we
646created in the previous step:
4d583dd8 647
648 $ script/myapp_create.pl model MyAppDB DBIC::Schema MyAppDB dbi:SQLite:myapp.db '' '' '{ AutoCommit => 1 }'
208513f1 649 exists "/root/dev/MyApp/script/../lib/MyApp/Model"
650 exists "/root/dev/MyApp/script/../t"
651 created "/root/dev/MyApp/script/../lib/MyApp/Model/MyAppDB.pm"
652 created "/root/dev/MyApp/script/../t/model_MyAppDB.t"
653
4d583dd8 654
64ccd8a8 655Where the first C<MyAppDB> is the name of the class to be created by the
656helper in C<lib/MyApp/Model> and the second C<MyAppDB> is the name of
657existing schema file we created (in C<lib/MyAppDB.pm>). You can see
658that the helper creates a model file under C<lib/MyApp/Model> (Catalyst
659has a separate directory under C<lib/MyApp> for each of the three parts
660of MVC: C<Model>, C<View>, and C<Controller> [although older Catalyst
661applications often use the directories C<M>, C<V>, and C<C>]).
4d583dd8 662
663
4d583dd8 664=head1 CREATE A CATALYST CONTROLLER
665
71dedf57 666Controllers are where you write methods that interact with user
667input--typically, controller methods respond to C<GET> and C<POST>
668messages from the user's web browser.
4d583dd8 669
71dedf57 670Use the Catalyst C<create> script to add a controller for book-related
671actions:
4d583dd8 672
673 $ script/myapp_create.pl controller Books
208513f1 674 exists "/root/dev/MyApp/script/../lib/MyApp/Controller"
675 exists "/root/dev/MyApp/script/../t"
676 created "/root/dev/MyApp/script/../lib/MyApp/Controller/Books.pm"
677 created "/root/dev/MyApp/script/../t/controller_Books.t"
4d583dd8 678
64ccd8a8 679Then edit C<lib/MyApp/Controller/Books.pm> and add the following method
680to the controller:
4d583dd8 681
682 =head2 list
683
684 Fetch all book objects and pass to books/list.tt2 in stash to be displayed
685
686 =cut
687
688 sub list : Local {
689 # Retrieve the usual perl OO '$self' for this object. $c is the Catalyst
690 # 'Context' that's used to 'glue together' the various components
691 # that make up the application
692 my ($self, $c) = @_;
693
694 # Retrieve all of the book records as book model objects and store in the
695 # stash where they can be accessed by the TT template
696 $c->stash->{books} = [$c->model('MyAppDB::Book')->all];
697
698 # Set the TT template to use. You will almost always want to do this
8112f931 699 # in your action methods (actions methods respond to user input in
700 # your controllers).
4d583dd8 701 $c->stash->{template} = 'books/list.tt2';
702 }
703
64ccd8a8 704B<Note:> Programmers experienced with object-oriented Perl should
705recognize C<$self> as a reference to the object where this method was
706called. On the other hand, C<$c> will be new to many Perl programmers
707who have not used Catalyst before (it's sometimes written as
708C<$context>). The Context object is automatically passed to all
709Catalyst components. It is used to pass information between components
710and provide access to Catalyst and plugin functionality.
4d583dd8 711
64ccd8a8 712B<TIP>: You may see the C<$c-E<gt>model('MyAppDB::Book')> used above
713written as C<$c-E<gt>model('MyAppDB')-E<gt>resultset('Book)>. The two
714are equivalent.
4d583dd8 715
64ccd8a8 716B<Note:> Catalyst actions are regular Perl methods, but they make use of
14e6feb0 717Nicholas Clark's C<attributes> module (that's the C<: Local> next to the
718C<sub list> in the code above) to provide additional information to the
719Catalyst dispatcher logic.
4d583dd8 720
208513f1 721
4d583dd8 722=head1 CATALYST VIEWS
723
71dedf57 724Views are where you render output, typically for display in the user's
14e6feb0 725web browser, but also possibly using other display output-generation
71dedf57 726systems. As with virtually every aspect of Catalyst, options abound
727when it comes to the specific view technology you adopt inside your
728application. However, most Catalyst applications use the Template
729Toolkit, known as TT (for more information on TT, see
208513f1 730L<http://www.template-toolkit.org>). Other popular view technologies
71dedf57 731include Mason (L<http://www.masonhq.com> and
14e6feb0 732L<http://www.masonbook.com>) and L<HTML::Template|HTML::Template>
64ccd8a8 733(L<http://html-template.sourceforge.net>).
4d583dd8 734
4d583dd8 735=head2 Create a Catalyst View Using C<TTSITE>
736
737When using TT for the Catalyst view, there are two main helper scripts:
738
739=over 4
740
741=item *
742
14e6feb0 743L<Catalyst::Helper::View::TT|Catalyst::Helper::View::TT>
4d583dd8 744
745=item *
746
14e6feb0 747L<Catalyst::Helper::View::TTSite|Catalyst::Helper::View::TTSite>
4d583dd8 748
749=back
750
64ccd8a8 751Both are similar, but C<TT> merely creates the C<lib/MyApp/View/TT.pm>
752file and leaves the creation of any hierarchical template organization
71dedf57 753entirely up to you. (It also creates a C<t/view_TT.t> file for testing;
754test cases will be discussed in Part 7). The C<TTSite> helper creates a
755modular and hierarchical view layout with separate Template Toolkit (TT)
756files for common header and footer information, configuration values, a
757CSS stylesheet, and more.
4d583dd8 758
64ccd8a8 759Enter the following command to enable the C<TTSite> style of view
71dedf57 760rendering for this tutorial:
4d583dd8 761
762 $ script/myapp_create.pl view TT TTSite
208513f1 763 exists "/root/dev/MyApp/script/../lib/MyApp/View"
764 exists "/root/dev/MyApp/script/../t"
765 created "/root/dev/MyApp/script/../lib/MyApp/View/TT.pm"
766 created "/root/dev/MyApp/script/../root/lib"
767 ...
768 created "/root/dev/MyApp/script/../root/src/ttsite.css"
4d583dd8 769
64ccd8a8 770This puts a number of files in the C<root/lib> and C<root/src>
771directories that can be used to customize the look and feel of your
772application. Also take a look at C<lib/MyApp/View/TT.pm> for config
773values set by the C<TTSite> helper.
774
775B<TIP>: Note that TTSite does one thing that could confuse people who
208513f1 776are used to the normal C<TT> Catalyst view: it redefines the Catalyst
71dedf57 777context object in templates from its usual C<c> to C<Catalyst>. When
778looking at other Catalyst examples, remember that they almost always use
779C<c>. Note that Catalyst and TT I<do not complain> when you use the
780wrong name to access the context object...TT simply outputs blanks for
5c1f2a06 781that bogus logic (see next tip to change this behavior with TT C<DEBUG>
782options). Finally, be aware that this change in name I<only>
71dedf57 783applies to how the context object is accessed inside your TT templates;
64ccd8a8 784your controllers will continue to use C<$c> (or whatever name you use
71dedf57 785when fetching the reference from C<@_> inside your methods). (You can
64ccd8a8 786change back to the "default" behavior be removing the C<CATALYST_VAR>
787line from C<lib/MyApp/View/TT.pm>, but you will also have to edit
788C<root/lib/config/main> and C<root/lib/config/url>. If you do this, be
789careful not to have a collision between your own C<c> variable and the
790Catalyst C<c> variable.)
4d583dd8 791
5c1f2a06 792B<TIP>: When troubleshooting TT it can be helpful to enable variable
793C<DEBUG> options. You can do this in a Catalyst environment by adding
794a C<DEBUG> line to the C<__PACKAGE__->config> declaration in
8112f931 795C<lib/MyApp/View/TT.pm>:
5c1f2a06 796
797 __PACKAGE__->config({
798 CATALYST_VAR => 'Catalyst',
799 ...
800 DEBUG => 'undef',
801 ...
802 });
208513f1 803
5c1f2a06 804There are a variety of options you can use, such as 'undef', 'all',
805'service', 'context', 'parser', 'provider', and 'service'. See
806L<Template::Constants> for more information (remove the C<DEBUG_>
807portion of the name shown in the TT docs and convert to lower case
808for use inside Catalyst).
809
810
208513f1 811=head2 Using C<RenderView> for the Default View
812
813Once your controller logic has processed the request from a user, it
814forwards processing to your view in order to generate the appropriate
8e956464 815response output. Catalyst v5.7000 ships with a new mechanism,
208513f1 816L<Catalyst::Action::RenderView|Catalyst::Action::RenderView>, that
817automatically performs this operation. If you look in
818C<lib/MyApp/Controller/Root.pm>, you should see the this empty
819definition for the C<sub end> method:
820
821 sub end : ActionClass('RenderView') {}
822
823The following bullet points provide a quick overview of the
824C<RenderView> process:
825
826=over 4
827
828=item *
829
830C<Root.pm> is designed to hold application-wide logic.
831
832=item *
833
834At the end of a given user request, Catalyst will call the most specific
835C<end> method that's appropriate. For example, if the controller for a
836request has an C<end> method defined, it will be called. However, if
837the controller does not define a controller-specific C<end> method, the
838"global" C<end> method in C<Root.pm> will be called.
c608fae5 839
208513f1 840=item *
841
842Because the definition includes an C<ActionClass> attribute, the
843L<Catalyst::Action::RenderView|Catalyst::Action::RenderView> logic
565d379b 844will be executed B<after> any code inside the definition of C<sub end>
208513f1 845is run. See L<Catalyst::Manual::Actions|Catalyst::Manual::Actions>
846for more information on C<ActionClass>.
847
848=item *
849
850Because C<sub end> is empty, this effectively just runs the default
851logic in C<RenderView>. However, you can easily extend the
852C<RenderView> logic by adding your own code inside the empty method body
853(C<{}>) created by the Catalyst Helpers when we first ran the
854C<catalyst.pl> to initialize our application. See
855L<Catalyst::Action::RenderView|Catalyst::Action::RenderView> for more
856detailed information on how to extended C<RenderView> in C<sub end>.
857
858=back
859
860
861=head3 The History Leading Up To C<RenderView>
862
863Although C<RenderView> strikes a nice balance between default
864behavior and easy extensibility, it is a new feature that won't
865appear in most existing Catalyst examples. This section provides
866some brief background on the evolution of default view rendering
867logic with an eye to how they can be migrated to C<RenderView>:
c608fae5 868
869=over 4
870
871=item *
872
873Private C<end> Action in Application Class
874
875Older Catalyst-related documents often suggest that you add a "private
876end action" to your application class (C<MyApp.pm>) or Root.pm
877(C<MyApp/Controller/Root.pm>). These examples should be easily
208513f1 878converted to L<RenderView|Catalyst::Action::RenderView> by simply adding
8112f931 879the attribute C<:ActionClass('RenderView')> to the C<sub end>
880definition. If end sub is defined in your application class
881(C<MyApp.pm>), you should also migrate it to
882C<MyApp/Controller/Root.pm>.
c608fae5 883
884=item *
885
886L<Catalyst::Plugin::DefaultEnd|Catalyst::Plugin::DefaultEnd>
887
208513f1 888C<DefaultEnd> represented the "next step" in passing processing from
889your controller to your view. It has the advantage of only requiring
890that C<DefaultEnd> be added to the list of plugins in C<lib/MyApp.pm>.
891It also allowed you to add "dump_info=1" (precede with "?" or "&"
892depending on where it is in the URL) to I<force> the debug screen at the
893end of the Catalyst request processing cycle. However, it was more
c9b77c06 894difficult to extend than the C<RenderView> mechanism, and is now
895deprecated.
c608fae5 896
897=item *
898
899L<Catalyst::Action::RenderView|Catalyst::Action::RenderView>
900
208513f1 901As discussed above, the current recommended approach to handling your
902view logic relies on
c608fae5 903L<Catalyst::Action::RenderView|Catalyst::Action::RenderView>. Although
208513f1 904similar in first appearance to the "private end action" approach, it
905utilizes Catalyst's "ActionClass" mechanism to provide both automatic
906default behavior (you don't have to include a plugin as with
907C<DefaultEnd>) and easy extensibility. As with C<DefaultEnd>, it allows
908you to add "dump_info=1" (precede with "?" or "&" depending on where it
909is in the URL) to I<force> the debug screen at the end of the Catalyst
910request processing cycle.
c608fae5 911
912=back
913
208513f1 914It is recommended that all Catalyst applications use or migrate to
915the C<RenderView> approach.
c608fae5 916
917
4d583dd8 918=head2 Globally Customize Every View
919
64ccd8a8 920When using TTSite, files in the subdirectories of C<root/lib> can be
921used to make changes that will appear in every view. For example, to
922display optional status and error messages in every view, edit
71dedf57 923C<root/lib/site/layout>, updating it to match the following (the two HTML
64ccd8a8 924C<span> elements are new):
4d583dd8 925
926 <div id="header">[% PROCESS site/header %]</div>
927
928 <div id="content">
929 <span class="message">[% status_msg %]</span>
930 <span class="error">[% error_msg %]</span>
931 [% content %]
932 </div>
933
934 <div id="footer">[% PROCESS site/footer %]</div>
935
64ccd8a8 936If we set either message in the Catalyst stash (e.g.,
71dedf57 937C<$c-E<gt>stash-E<gt>{status_msg} = 'Request was successful!'>) it will
938be displayed whenever any view used by that request is rendered. The
939C<message> and C<error> CSS styles are automatically defined in
940C<root/src/ttsite.css> and can be customized to suit your needs.
4d583dd8 941
64ccd8a8 942B<Note:> The Catalyst stash only lasts for a single HTTP request. If
943you need to retain information across requests you can use
14e6feb0 944L<Catalyst::Plugin::Session|Catalyst::Plugin::Session> (we will use
945Catalyst sessions in the Authentication part of the tutorial).
4d583dd8 946
947
948=head2 Create a TT Template Page
949
64ccd8a8 950To add a new page of content to the TTSite view hierarchy, just create a
951new C<.tt2> file in C<root/src>. Only include HTML markup that goes
952inside the HTML <body> and </body> tags, TTSite will use the contents of
953C<root/lib/site> to add the top and bottom.
4d583dd8 954
955First create a directory for book-related TT templates:
956
957 $ mkdir root/src/books
958
959Then open C<root/src/books/list.tt2> in your editor and enter:
960
961 [% # This is a TT comment. The '-' at the end "chomps" the newline. You won't -%]
962 [% # see this "chomping" in your browser because HTML ignores blank lines, but -%]
963 [% # it WILL eliminate a blank line if you view the HTML source. It's purely -%]
964 [%- # optional, but both the beginning and the ending TT tags support chomping. -%]
965
966 [% # Provide a title to root/lib/site/header -%]
967 [% META title = 'Book List' -%]
968
969 <table>
970 <tr><th>Title</th><th>Rating</th><th>Author(s)</th></tr>
971 [% # Display each book in a table row %]
972 [% FOREACH book IN books -%]
973 <tr>
974 <td>[% book.title %]</td>
975 <td>[% book.rating %]</td>
976 <td>
14e6feb0 977 [% # First initialize a TT variable to hold a list. Then use a TT FOREACH -%]
978 [% # loop in 'side effect notation' to load just the last names of the -%]
c9b77c06 979 [% # authors into the list. Note that the 'push' TT vmethod does not -%]
980 [% # a value, so nothing will be printed here. But, if you have something -%]
981 [% # in TT that does return a method and you don't want it printed, you -%]
982 [% # can: 1) assign it to a bogus value, or 2) use the CALL keyword to -%]
983 [% # call it and discard the return value. -%]
14e6feb0 984 [% tt_authors = [ ];
c9b77c06 985 tt_authors.push(author.last_name) FOREACH author = book.authors %]
14e6feb0 986 [% # Now use a TT 'virtual method' to display the author count in parens -%]
987 ([% tt_authors.size %])
c9b77c06 988 [% # Use another TT vmethod to join & print the names & comma separators -%]
14e6feb0 989 [% tt_authors.join(', ') %]
4d583dd8 990 </td>
991 </tr>
992 [% END -%]
993 </table>
994
64ccd8a8 995As indicated by the inline comments above, the C<META title> line uses
996TT's META feature to provide a title to C<root/lib/site/header>.
997Meanwhile, the outer C<FOREACH> loop iterates through each C<book> model
998object and prints the C<title> and C<rating> fields. An inner
14e6feb0 999C<FOREACH> loop prints the last name of each author in a comma-separated
1000list within a single table cell.
64ccd8a8 1001
71dedf57 1002If you are new to TT, the C<[%> and C<%]> tags are used to delimit TT
1003code. TT supports a wide variety of directives for "calling" other
64ccd8a8 1004files, looping, conditional logic, etc. In general, TT simplifies the
1005usual range of Perl operators down to the single dot (C<.>) operator.
1006This applies to operations as diverse as method calls, hash lookups, and
1007list index values (see
1008L<http://www.template-toolkit.org/docs/default/Manual/Variables.html>
1009for details and examples). In addition to the usual C<Template> module
1010Pod documentation, you can access the TT manual at
1011L<http://www.template-toolkit.org/docs/default/>.
1012
1013B<NOTE>: The C<TTSite> helper creates several TT files using an
1014extension of C<.tt2>. Most other Catalyst and TT examples use an
1015extension of C<.tt>. You can use either extension (or no extension at
1016all) with TTSite and TT, just be sure to use the appropriate extension
1017for both the file itself I<and> the C<$c-E<gt>stash-E<gt>{template} =
1018...> line in your controller. This document will use C<.tt2> for
1019consistency with the files already created by the C<TTSite> helper.
4d583dd8 1020
1021
4d583dd8 1022=head1 RUN THE APPLICATION
1023
64ccd8a8 1024First, let's enable an environment variable option that causes
1025DBIx::Class to dump the SQL statements it's using to access the database
1026(this option can provide extremely helpful troubleshooting information):
4d583dd8 1027
1028 $ export DBIX_CLASS_STORAGE_DBI_DEBUG=1
1029
cc548726 1030This assumes you are using BASH as your shell -- adjust accordingly if
1031you are using a different shell (for example, under tcsh, use
1032C<setenv DBIX_CLASS_STORAGE_DBI_DEBUG 1>).
1033
64ccd8a8 1034B<NOTE>: You can also set this in your code using
1035C<$class-E<gt>storage-E<gt>debug(1);>. See
71dedf57 1036L<DBIx::Class::Manual::Troubleshooting> for details (including options
1037to log to file instead of displaying to the Catalyst development server
1038log).
4d583dd8 1039
1040Then run the Catalyst "demo server" script:
1041
1042 $ script/myapp_server.pl
1043
208513f1 1044Your development server log output should display something like:
4d583dd8 1045
1046 $ script/myapp_server.pl
208513f1 1047 [debug] Debug messages enabled
1048 [debug] Loaded plugins:
1049 .----------------------------------------------------------------------------.
1050 | Catalyst::Plugin::ConfigLoader 0.06 |
1051 | Catalyst::Plugin::StackTrace 0.04 |
1052 | Catalyst::Plugin::Static::Simple 0.14 |
1053 '----------------------------------------------------------------------------'
4d583dd8 1054
208513f1 1055 [debug] Loaded dispatcher "Catalyst::Dispatcher"
1056 [debug] Loaded engine "Catalyst::Engine::HTTP"
1057 [debug] Found home "/home/me/MyApp"
1058 [debug] Loaded components:
1059 .-----------------------------------------------------------------+----------.
1060 | Class | Type |
1061 +-----------------------------------------------------------------+----------+
1062 | MyApp::Controller::Books | instance |
1063 | MyApp::Controller::Root | instance |
1064 | MyApp::Model::MyAppDB | instance |
1065 | MyApp::Model::MyAppDB::Author | class |
1066 | MyApp::Model::MyAppDB::Book | class |
1067 | MyApp::Model::MyAppDB::BookAuthor | class |
1068 | MyApp::View::TT | instance |
1069 '-----------------------------------------------------------------+----------'
4d583dd8 1070
208513f1 1071 [debug] Loaded Private actions:
1072 .----------------------+--------------------------------------+--------------.
1073 | Private | Class | Method |
1074 +----------------------+--------------------------------------+--------------+
1075 | /default | MyApp::Controller::Root | default |
1076 | /end | MyApp::Controller::Root | end |
1077 | /books/index | MyApp::Controller::Books | index |
1078 | /books/list | MyApp::Controller::Books | list |
1079 '----------------------+--------------------------------------+--------------'
4d583dd8 1080
208513f1 1081 [debug] Loaded Path actions:
1082 .-------------------------------------+--------------------------------------.
1083 | Path | Private |
1084 +-------------------------------------+--------------------------------------+
1085 | /books/list | /books/list |
1086 '-------------------------------------+--------------------------------------'
4d583dd8 1087
8e956464 1088 [info] MyApp powered by Catalyst 5.7000
208513f1 1089 You can connect to your server at http://localhost.localdomain:3000
4d583dd8 1090
1091Some things you should note in the output above:
1092
1093=over 4
1094
1095=item *
1096
64ccd8a8 1097Catalyst::Model::DBIC::Schema took our C<MyAppDB::Book> and made it
1098C<MyApp::Model::MyAppDB::Book> (and similar actions were performed on
1099C<MyAppDB::Author> and C<MyAppDB::BookAuthor>).
4d583dd8 1100
1101=item *
1102
64ccd8a8 1103The "list" action in our Books controller showed up with a path of
1104C</books/list>.
4d583dd8 1105
1106=back
1107
64ccd8a8 1108Point your browser to L<http://localhost:3000> and you should still get
1109the Catalyst welcome page.
4d583dd8 1110
64ccd8a8 1111Next, to view the book list, change the URL in your browser to
1112L<http://localhost:3000/books/list>. You should get a list of the five
1113books loaded by the C<myapp01.sql> script above, with TTSite providing
1114the formatting for the very simple output we generated in our template.
1115The count and space-separated list of author last names appear on the
1116end of each row.
4d583dd8 1117
64ccd8a8 1118Also notice in the output of the C<script/myapp_server.pl> that DBIC
1119used the following SQL to retrieve the data:
4d583dd8 1120
1121 SELECT me.id, me.title, me.rating FROM books me
1122
64ccd8a8 1123Along with a list of the following commands to retrieve the authors for
1124each book (the lines have been "word wrapped" here to improve
1125legibility):
4d583dd8 1126
1127 SELECT author.id, author.first_name, author.last_name
1128 FROM book_authors me
1129 JOIN authors author ON ( author.id = me.author_id )
1130 WHERE ( me.book_id = ? ): `1'
1131
208513f1 1132You should see 5 such lines of debug output as DBIC fetches the author
1133information for each book.
4d583dd8 1134
1135
1136=head1 AUTHOR
1137
1138Kennedy Clark, C<hkclark@gmail.com>
1139
c608fae5 1140Please report any errors, issues or suggestions to the author. The
7d310f12 1141most recent version of the Catalyst Tutorial can be found at
c608fae5 1142L<http://dev.catalyst.perl.org/repos/Catalyst/trunk/Catalyst-Runtime/lib/Catalyst/Manual/Tutorial/>.
4d583dd8 1143
71dedf57 1144Copyright 2006, Kennedy Clark, under Creative Commons License
1145(L<http://creativecommons.org/licenses/by-nc-sa/2.5/>).
4d583dd8 1146