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