torched C::M::FAQ
[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
653f4595 190cutting and pasting example code from POD 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
256flag options (of these, C<-Debug> is the most common).
4d583dd8 257
64ccd8a8 258If you prefer, you can use the C<$c-E<gt>debug> method to enable debug
259messages.
4d583dd8 260
261=item *
262
263L<Catalyst::Plugin::ConfigLoader|Catalyst::Plugin::ConfigLoader>
264
653f4595 265C<ConfigLoader> provides an automatic way to load configurable
64ccd8a8 266parameters for your application from a central YAML file (versus having
267the values hard-coded inside your Perl modules). If you have not been
268exposed to YAML before, it is a human-readable data serialization format
269that can be used to read (and write) values to/from text files. We will
270see how to use this feature of Catalyst during the authentication and
271authorization sections (Part 4 and Part 5).
4d583dd8 272
4d583dd8 273=item *
274
653f4595 275L<Catalyst::Plugin::Static::Simple>
4d583dd8 276
64ccd8a8 277C<Static::Simple> provides an easy method of serving static content such
278as images and CSS files under the development server.
4d583dd8 279
280=back
281
64ccd8a8 282To modify the list of plugins, edit C<lib/MyApp.pm> (this file is
283generally referred to as your I<application class>) and delete the line
284with:
4d583dd8 285
286 use Catalyst qw/-Debug ConfigLoader Static::Simple/;
287
288Replace it with:
289
290 use Catalyst qw/
291 -Debug
292 ConfigLoader
293 Static::Simple
294
295 Dumper
296 StackTrace
297 DefaultEnd
298 /;
299
300This tells Catalyst to start using three new plugins:
301
302=over 4
303
304=item *
305
653f4595 306L<Catalyst::Plugin::Dumper>
4d583dd8 307
653f4595 308Allows you to easily use L<Data::Dumper> to dump variables
64ccd8a8 309to the logs, for example:
4d583dd8 310
311 $c->log->dumper($myvar);
312
64ccd8a8 313When running your application under the development server, the logs
314will be printed to your screen along with the other debug information
315generated by the C<-Debug> flag.
4d583dd8 316
317=item *
318
319L<Catalyst::Plugin::StackTrace|Catalyst::Plugin::StackTrace>
320
64ccd8a8 321Adds a stack trace to the standard Catalyst "debug screen" (this is the
322screen Catalyst sends to your browser when an error occurs).
4d583dd8 323
653f4595 324Note: L<Dumper|Catalyst::Plugin::Dumper> output appears on the console
325window where you issue the C<script/myapp_server.pl> command.
326L<StackTrace|Catalyst::Plugin::StackTrace> output appears in your
327browser.
4d583dd8 328
329=item *
330
331L<Catalyst::Plugin::DefaultEnd|Catalyst::Plugin::DefaultEnd>
332
64ccd8a8 333Automatically provides a Catalyst "end action" that invokes your view at
334the end of each request. Also allows you to add "dump_info=1" (precede
335with "?" or "&" depending on where it is in the URL) to I<force> the
336debug screen at the end of the Catalyst request processing cycle.
4d583dd8 337
653f4595 338B<TIP>: Many Catalyst-related documents predate
64ccd8a8 339L<DefaultEnd|Catalyst::Plugin::DefaultEnd> and suggest that you add an
340C<end> action to your application class (C<MyApp.pm>) or Root.pm
341(C<MyApp/Controller/Root.pm>). In most of these cases, you can convert
342to L<DefaultEnd|Catalyst::Plugin::DefaultEnd> by deleting the C<end>
71dedf57 343action and using the plugin instead. There are certainly cases when
344you'd want to write your own custom C<end> action, but for most
345circumstances, DefaultEnd will be exactly what you want.
4d583dd8 346
347=back
348
64ccd8a8 349Note that when specifying plugins on the C<use Catalyst> line, you can
71dedf57 350omit C<Catalyst::Plugin::> from the name. Additionally, you can spread
64ccd8a8 351the plugin names across multiple lines as shown here, or place them all
352on one (or more) lines as with the default configuration.
4d583dd8 353
4d583dd8 354=head1 DATABASE ACCESS WITH C<DBIx::Class>
355
64ccd8a8 356Catalyst can be used with virtually any form of persistent datastore
71dedf57 357available via Perl. For example, L<Catalyst::Model::DBI> can be used to
358easily access databases through the traditional Perl L<DBI> interface.
359However, most Catalyst applications use some form of ORM technology to
64ccd8a8 360automatically create and save model objects as they are used. Although
71dedf57 361Tony Bowden's L<Class::DBI> has been the traditional Perl ORM engine,
362Matt Trout's L<DBIx::Class> (abbreviated as "DBIC") has rapidly emerged
363as the Perl-based ORM technology of choice. Most new Catalyst
364applications rely on DBIC, as will this tutorial.
4d583dd8 365
71dedf57 366Note: See L<Catalyst:: Model::CDBI > for more information on using
367Catalyst with L<Class::DBI>.
4d583dd8 368
369=head2 Create a DBIC Schema File
370
64ccd8a8 371DBIx::Class uses a schema file to load other classes that represent the
372tables in your database (DBIC refers to these "table objects" as "result
71dedf57 373sources"; see L<DBIx::Class::ResultSource>). In this case, we want to
374load the model object for the C<books>, C<book_authors>, and C<authors>
375tables created in the previous step.
4d583dd8 376
377Open C<lib/MyAppDB.pm> in your editor and insert:
378
379 package MyAppDB;
380
381 =head1 NAME
382
71dedf57 383 MyAppDB - DBIC Schema Class
4d583dd8 384
385 =cut
386
387 # Our schema needs to inherit from 'DBIx::Class::Schema'
388 use base qw/DBIx::Class::Schema/;
389
390 # Need to load the DB Model classes here.
391 # You can use this syntax if you want:
392 # __PACKAGE__->load_classes(qw/Book BookAuthor Author/);
393 # Also, if you simply want to load all of the classes in a directory
394 # of the same name as your schema class (as we do here) you can use:
395 # __PACKAGE__->load_classes(qw//);
396 # But the variation below is more flexible in that it can be used to
397 # load from multiple namespaces.
398 __PACKAGE__->load_classes({
399 MyAppDB => [qw/Book BookAuthor Author/]
400 });
401
402 1;
403
64ccd8a8 404B<Note:> C<__PACKAGE__> is just a shorthand way of referencing the name
405of the package where it is used. Therefore, in C<MyAppDB.pm>,
71dedf57 406C<__PACKAGE__> is equivalent to C<MyAppDB>
4d583dd8 407
408
409=head2 Create the DBIC "Result Source" Files
410
64ccd8a8 411In this step, we create "table classes" (again, these are called a
71dedf57 412"result source" classes in DBIC) that act as model objects for the
64ccd8a8 413C<books>, C<book_authors>, and C<authors> tables in our database.
4d583dd8 414
415First, create a directory to hold the class:
416
417 $ mkdir lib/MyAppDB
418
419Then open C<lib/MyAppDB/Book.pm> in your editor and enter:
420
421 package MyAppDB::Book;
422
423 use base qw/DBIx::Class/;
424
425 # Load required DBIC stuff
426 __PACKAGE__->load_components(qw/PK::Auto Core/);
427 # Set the table name
428 __PACKAGE__->table('books');
429 # Set columns in table
430 __PACKAGE__->add_columns(qw/id title rating/);
431 # Set the primary key for the table
432 __PACKAGE__->set_primary_key(qw/id/);
433
434 #
435 # Set relationships:
436 #
437
438 # has_many():
439 # args:
440 # 1) Name of relationship, DBIC will create accessor with this name
441 # 2) Name of the model class referenced by this relationship
442 # 3) Column name in *foreign* table
443 __PACKAGE__->has_many(book_authors => 'MyAppDB::BookAuthor', 'book_id');
444
445 # many_to_many():
446 # args:
447 # 1) Name of relationship, DBIC will create accessor with this name
448 # 2) Name of has_many() relationship this many_to_many() is shortcut for
449 # 3) Name of belongs_to() relationship in model class of has_many() above
450 # You must already have the has_many() defined to use a many_to_many().
451 __PACKAGE__->many_to_many(authors => 'book_authors', 'author');
452
453
454 =head1 NAME
455
456 MyAppDB::Book - A model object representing a book.
457
458 =head1 DESCRIPTION
459
460 This is an object that represents a row in the 'books' table of your application
461 database. It uses DBIx::Class (aka, DBIC) to do ORM.
462
463 For Catalyst, this is designed to be used through MyApp::Model::MyAppDB.
464 Offline utilities may wish to use this class directly.
465
466 =cut
467
468 1;
469
64ccd8a8 470This defines both a C<has_many> and a C<many_to_many> relationship. The
471C<many_to_many> relationship is optional, but it makes it easier to map
472a book to its collection of authors. Without it, we would have to
473"walk" though the C<book_authors> table as in
474C<$book-E<gt>book_authors-E<gt>first-E<gt>author-E<gt>last_name> (we
475will see examples on how to use DBIC objects in your code soon, but note
476that because C<$book-E<gt>book_authors> can return multiple authors, we
71dedf57 477have to use C<first> to display a single author). C<many_to_many> allows
478us to use the shorter C<$book-E<gt>authors-E<gt>first-E<gt>last_name>.
479Note that you cannot define a C<many_to_many> relationship without also
480having the C<has_many> relationship in place.
4d583dd8 481
482Next, open C<lib/MyAppDB/Author.pm> in your editor and enter:
483
484 package MyAppDB::Author;
485
486 use base qw/DBIx::Class/;
487
488 # Load required DBIC stuff
489 __PACKAGE__->load_components(qw/PK::Auto Core/);
490 # Set the table name
491 __PACKAGE__->table('authors');
492 # Set columns in table
493 __PACKAGE__->add_columns(qw/id first_name last_name/);
494 # Set the primary key for the table
495 __PACKAGE__->set_primary_key(qw/id/);
496
497 #
498 # Set relationships:
499 #
500
501 # has_many():
502 # args:
503 # 1) Name of relationship, DBIC will create accessor with this name
504 # 2) Name of the model class referenced by this relationship
505 # 3) Column name in *foreign* table
506 __PACKAGE__->has_many(book_author => 'MyAppDB::BookAuthor', 'author_id');
507
508 # many_to_many():
509 # args:
510 # 1) Name of relationship, DBIC will create accessor with this name
511 # 2) Name of has_many() relationship this many_to_many() is shortcut for
512 # 3) Name of belongs_to() relationship in model class of has_many() above
513 # You must already have the has_many() defined to use a many_to_many().
514 __PACKAGE__->many_to_many(books => 'book_author', 'book');
515
516
517 =head1 NAME
518
519 MyAppDB::Author - A model object representing an author of a book (if a book has
520 multiple authors, each will be represented be separate Author object).
521
522 =head1 DESCRIPTION
523
524 This is an object that represents a row in the 'authors' table of your application
525 database. It uses DBIx::Class (aka, DBIC) to do ORM.
526
527 For Catalyst, this is designed to be used through MyApp::Model::MyAppDB.
528 Offline utilities may wish to use this class directly.
529
530 =cut
531
532 1;
533
534Finally, open C<lib/MyAppDB/BookAuthor.pm> in your editor and enter:
535
536 package MyAppDB::BookAuthor;
537
538 use base qw/DBIx::Class/;
539
540 # Load required DBIC stuff
541 __PACKAGE__->load_components(qw/PK::Auto Core/);
542 # Set the table name
543 __PACKAGE__->table('book_authors');
544 # Set columns in table
545 __PACKAGE__->add_columns(qw/book_id author_id/);
546 # Set the primary key for the table
547 __PACKAGE__->set_primary_key(qw/book_id author_id/);
548
549 #
550 # Set relationships:
551 #
552
553 # belongs_to():
554 # args:
555 # 1) Name of relationship, DBIC will create accessor with this name
556 # 2) Name of the model class referenced by this relationship
557 # 3) Column name in *this* table
558 __PACKAGE__->belongs_to(book => 'MyAppDB::Book', 'book_id');
559
560 # belongs_to():
561 # args:
562 # 1) Name of relationship, DBIC will create accessor with this name
563 # 2) Name of the model class referenced by this relationship
564 # 3) Column name in *this* table
565 __PACKAGE__->belongs_to(author => 'MyAppDB::Author', 'author_id');
566
567
568 =head1 NAME
569
570 MyAppDB::BookAuthor - A model object representing the JOIN between an author and
571 a book.
572
573 =head1 DESCRIPTION
574
575 This is an object that represents a row in the 'book_authors' table of your
576 application database. It uses DBIx::Class (aka, DBIC) to do ORM.
577
578 You probably won't need to use this class directly -- it will be automatically
579 used by DBIC where joins are needed.
580
581 For Catalyst, this is designed to be used through MyApp::Model::MyAppDB.
582 Offline utilities may wish to use this class directly.
583
584 =cut
585
586 1;
587
64ccd8a8 588B<Note:> This sample application uses a plural form for the database
589tables (e.g., C<books> and C<authors>) and a singular form for the model
590objects (e.g., C<Book> and C<Author>); however, Catalyst places no
591restrictions on the naming conventions you wish to use.
4d583dd8 592
4d583dd8 593=head2 Use C<Catalyst::Model::DBIC::Schema> To Load The Model Class
594
71dedf57 595When L<Catalyst::Model::DBIC::Schema> is
64ccd8a8 596in use, Catalyst essentially reads an existing copy of your database
597model and creates a new set of objects under C<MyApp::Model> for use
598inside of Catalyst.
4d583dd8 599
71dedf57 600B<Note:> With L<Catalyst::Model::DBIC::Schema> you essentially end up
601with two sets of model classes (only one of which you write... the other
602set is created automatically in memory when your Catalyst application
603initializes). For this tutorial application, the important points to
604remember are: you write the I<result source> files in C<MyAppDB>, but
605I<within Catalyst> you use the I<automatically created model classes> in
606C<MyApp::Model>.
4d583dd8 607
71dedf57 608Use the L<Catalyst::Helper::Model::DBIC::Schema > helper script to
609create the model class that loads up the model we created in the
610previous step:
4d583dd8 611
612 $ script/myapp_create.pl model MyAppDB DBIC::Schema MyAppDB dbi:SQLite:myapp.db '' '' '{ AutoCommit => 1 }'
613
64ccd8a8 614Where the first C<MyAppDB> is the name of the class to be created by the
615helper in C<lib/MyApp/Model> and the second C<MyAppDB> is the name of
616existing schema file we created (in C<lib/MyAppDB.pm>). You can see
617that the helper creates a model file under C<lib/MyApp/Model> (Catalyst
618has a separate directory under C<lib/MyApp> for each of the three parts
619of MVC: C<Model>, C<View>, and C<Controller> [although older Catalyst
620applications often use the directories C<M>, C<V>, and C<C>]).
4d583dd8 621
622
4d583dd8 623=head1 CREATE A CATALYST CONTROLLER
624
71dedf57 625Controllers are where you write methods that interact with user
626input--typically, controller methods respond to C<GET> and C<POST>
627messages from the user's web browser.
4d583dd8 628
71dedf57 629Use the Catalyst C<create> script to add a controller for book-related
630actions:
4d583dd8 631
632 $ script/myapp_create.pl controller Books
633
64ccd8a8 634Then edit C<lib/MyApp/Controller/Books.pm> and add the following method
635to the controller:
4d583dd8 636
637 =head2 list
638
639 Fetch all book objects and pass to books/list.tt2 in stash to be displayed
640
641 =cut
642
643 sub list : Local {
644 # Retrieve the usual perl OO '$self' for this object. $c is the Catalyst
645 # 'Context' that's used to 'glue together' the various components
646 # that make up the application
647 my ($self, $c) = @_;
648
649 # Retrieve all of the book records as book model objects and store in the
650 # stash where they can be accessed by the TT template
651 $c->stash->{books} = [$c->model('MyAppDB::Book')->all];
652
653 # Set the TT template to use. You will almost always want to do this
654 # in your action methods.
655 $c->stash->{template} = 'books/list.tt2';
656 }
657
64ccd8a8 658B<Note:> Programmers experienced with object-oriented Perl should
659recognize C<$self> as a reference to the object where this method was
660called. On the other hand, C<$c> will be new to many Perl programmers
661who have not used Catalyst before (it's sometimes written as
662C<$context>). The Context object is automatically passed to all
663Catalyst components. It is used to pass information between components
664and provide access to Catalyst and plugin functionality.
4d583dd8 665
64ccd8a8 666B<TIP>: You may see the C<$c-E<gt>model('MyAppDB::Book')> used above
667written as C<$c-E<gt>model('MyAppDB')-E<gt>resultset('Book)>. The two
668are equivalent.
4d583dd8 669
64ccd8a8 670B<Note:> Catalyst actions are regular Perl methods, but they make use of
671Nicholas Clark's C<attributes> module to provide additional information
672to the Catalyst dispatcher logic.
4d583dd8 673
4d583dd8 674=head1 CATALYST VIEWS
675
71dedf57 676Views are where you render output, typically for display in the user's
677web browser, but also possibly using other display our output-generation
678systems. As with virtually every aspect of Catalyst, options abound
679when it comes to the specific view technology you adopt inside your
680application. However, most Catalyst applications use the Template
681Toolkit, known as TT (for more information on TT, see
682L<http://www.template-toolkit.org>). Other popular View technologies
683include Mason (L<http://www.masonhq.com> and
684L<http://www.masonbook.com>) and L<HTML::Template>
64ccd8a8 685(L<http://html-template.sourceforge.net>).
4d583dd8 686
4d583dd8 687=head2 Create a Catalyst View Using C<TTSITE>
688
689When using TT for the Catalyst view, there are two main helper scripts:
690
691=over 4
692
693=item *
694
71dedf57 695L<Catalyst::Helper::View::TT>
4d583dd8 696
697=item *
698
71dedf57 699L<Catalyst::Helper::View::TTSite>
4d583dd8 700
701=back
702
64ccd8a8 703Both are similar, but C<TT> merely creates the C<lib/MyApp/View/TT.pm>
704file and leaves the creation of any hierarchical template organization
71dedf57 705entirely up to you. (It also creates a C<t/view_TT.t> file for testing;
706test cases will be discussed in Part 7). The C<TTSite> helper creates a
707modular and hierarchical view layout with separate Template Toolkit (TT)
708files for common header and footer information, configuration values, a
709CSS stylesheet, and more.
4d583dd8 710
64ccd8a8 711Enter the following command to enable the C<TTSite> style of view
71dedf57 712rendering for this tutorial:
4d583dd8 713
714 $ script/myapp_create.pl view TT TTSite
715
64ccd8a8 716This puts a number of files in the C<root/lib> and C<root/src>
717directories that can be used to customize the look and feel of your
718application. Also take a look at C<lib/MyApp/View/TT.pm> for config
719values set by the C<TTSite> helper.
720
721B<TIP>: Note that TTSite does one thing that could confuse people who
722are used to the normal C<TT> Catalyst View: it redefines the Catalyst
71dedf57 723context object in templates from its usual C<c> to C<Catalyst>. When
724looking at other Catalyst examples, remember that they almost always use
725C<c>. Note that Catalyst and TT I<do not complain> when you use the
726wrong name to access the context object...TT simply outputs blanks for
64ccd8a8 727that bogus logic. Finally, be aware that this change in name I<only>
71dedf57 728applies to how the context object is accessed inside your TT templates;
64ccd8a8 729your controllers will continue to use C<$c> (or whatever name you use
71dedf57 730when fetching the reference from C<@_> inside your methods). (You can
64ccd8a8 731change back to the "default" behavior be removing the C<CATALYST_VAR>
732line from C<lib/MyApp/View/TT.pm>, but you will also have to edit
733C<root/lib/config/main> and C<root/lib/config/url>. If you do this, be
734careful not to have a collision between your own C<c> variable and the
735Catalyst C<c> variable.)
4d583dd8 736
4d583dd8 737=head2 Globally Customize Every View
738
64ccd8a8 739When using TTSite, files in the subdirectories of C<root/lib> can be
740used to make changes that will appear in every view. For example, to
741display optional status and error messages in every view, edit
71dedf57 742C<root/lib/site/layout>, updating it to match the following (the two HTML
64ccd8a8 743C<span> elements are new):
4d583dd8 744
745 <div id="header">[% PROCESS site/header %]</div>
746
747 <div id="content">
748 <span class="message">[% status_msg %]</span>
749 <span class="error">[% error_msg %]</span>
750 [% content %]
751 </div>
752
753 <div id="footer">[% PROCESS site/footer %]</div>
754
64ccd8a8 755If we set either message in the Catalyst stash (e.g.,
71dedf57 756C<$c-E<gt>stash-E<gt>{status_msg} = 'Request was successful!'>) it will
757be displayed whenever any view used by that request is rendered. The
758C<message> and C<error> CSS styles are automatically defined in
759C<root/src/ttsite.css> and can be customized to suit your needs.
4d583dd8 760
64ccd8a8 761B<Note:> The Catalyst stash only lasts for a single HTTP request. If
762you need to retain information across requests you can use
71dedf57 763L<Catalyst::Plugin::Session> (we will use
64ccd8a8 764Catalyst sessions in the Authentication part).
4d583dd8 765
766
767=head2 Create a TT Template Page
768
64ccd8a8 769To add a new page of content to the TTSite view hierarchy, just create a
770new C<.tt2> file in C<root/src>. Only include HTML markup that goes
771inside the HTML <body> and </body> tags, TTSite will use the contents of
772C<root/lib/site> to add the top and bottom.
4d583dd8 773
774First create a directory for book-related TT templates:
775
776 $ mkdir root/src/books
777
778Then open C<root/src/books/list.tt2> in your editor and enter:
779
780 [% # This is a TT comment. The '-' at the end "chomps" the newline. You won't -%]
781 [% # see this "chomping" in your browser because HTML ignores blank lines, but -%]
782 [% # it WILL eliminate a blank line if you view the HTML source. It's purely -%]
783 [%- # optional, but both the beginning and the ending TT tags support chomping. -%]
784
785 [% # Provide a title to root/lib/site/header -%]
786 [% META title = 'Book List' -%]
787
788 <table>
789 <tr><th>Title</th><th>Rating</th><th>Author(s)</th></tr>
790 [% # Display each book in a table row %]
791 [% FOREACH book IN books -%]
792 <tr>
793 <td>[% book.title %]</td>
794 <td>[% book.rating %]</td>
795 <td>
796 [% # Print author count in parens. 'book.authors' uses the 'many_to_many' -%]
797 [% # relationship to retrieve all of the authors of a book. 'size' is a -%]
798 [% # TT VMethod to get the number of elements in a list. -%]
799 ([% book.authors.size %])
800 [% # Use an alternate form of a FOREACH loop to display authors. -%]
801 [% # _ below is the TT string concatenation operator. -%]
802 [% author.last_name _' ' FOREACH author = book.authors %]
803 [% # Note: if many_to_many relationship not used in Authors.pm, you could -%]
804 [% # have used the following to 'walk' through the 'join table objects' -%]
805 [% # bk_author.author.last_name _' ' FOREACH bk_author = book.book_authors %]
806 </td>
807 </tr>
808 [% END -%]
809 </table>
810
64ccd8a8 811As indicated by the inline comments above, the C<META title> line uses
812TT's META feature to provide a title to C<root/lib/site/header>.
813Meanwhile, the outer C<FOREACH> loop iterates through each C<book> model
814object and prints the C<title> and C<rating> fields. An inner
815C<FOREACH> loop prints the last name of each author in a single table
816cell (a simple space is used between the names; in reality you would
817probably want to modify the code to use a comma as a separator).
818
71dedf57 819If you are new to TT, the C<[%> and C<%]> tags are used to delimit TT
820code. TT supports a wide variety of directives for "calling" other
64ccd8a8 821files, looping, conditional logic, etc. In general, TT simplifies the
822usual range of Perl operators down to the single dot (C<.>) operator.
823This applies to operations as diverse as method calls, hash lookups, and
824list index values (see
825L<http://www.template-toolkit.org/docs/default/Manual/Variables.html>
826for details and examples). In addition to the usual C<Template> module
827Pod documentation, you can access the TT manual at
828L<http://www.template-toolkit.org/docs/default/>.
829
830B<NOTE>: The C<TTSite> helper creates several TT files using an
831extension of C<.tt2>. Most other Catalyst and TT examples use an
832extension of C<.tt>. You can use either extension (or no extension at
833all) with TTSite and TT, just be sure to use the appropriate extension
834for both the file itself I<and> the C<$c-E<gt>stash-E<gt>{template} =
835...> line in your controller. This document will use C<.tt2> for
836consistency with the files already created by the C<TTSite> helper.
4d583dd8 837
838
4d583dd8 839=head1 RUN THE APPLICATION
840
64ccd8a8 841First, let's enable an environment variable option that causes
842DBIx::Class to dump the SQL statements it's using to access the database
843(this option can provide extremely helpful troubleshooting information):
4d583dd8 844
845 $ export DBIX_CLASS_STORAGE_DBI_DEBUG=1
846
64ccd8a8 847B<NOTE>: You can also set this in your code using
848C<$class-E<gt>storage-E<gt>debug(1);>. See
71dedf57 849L<DBIx::Class::Manual::Troubleshooting> for details (including options
850to log to file instead of displaying to the Catalyst development server
851log).
4d583dd8 852
853Then run the Catalyst "demo server" script:
854
855 $ script/myapp_server.pl
856
857You should get something like this:
858
859 $ script/myapp_server.pl
860 [Tue May 16 12:51:33 2006] [catalyst] [debug] Debug messages enabled
861 [Tue May 16 12:51:33 2006] [catalyst] [debug] Loaded plugins:
862 .------------------------------------------------------------------------------.
863 | Catalyst::Plugin::ConfigLoader 0.07 |
864 | Catalyst::Plugin::Static::Simple 0.14 |
865 | Catalyst::Plugin::Dumper 0.000002 |
866 | Catalyst::Plugin::StackTrace 0.04 |
867 | Catalyst::Plugin::DefaultEnd 0.06 |
868 '------------------------------------------------------------------------------'
869
870 [Tue May 16 12:51:33 2006] [catalyst] [debug] Loaded dispatcher "Catalyst::Dispatcher"
871 [Tue May 16 12:51:33 2006] [catalyst] [debug] Loaded engine "Catalyst::Engine::HTTP"
872 [Tue May 16 12:51:33 2006] [catalyst] [debug] Found home "/home/me/MyApp"
873 [Tue May 16 12:51:37 2006] [catalyst] [debug] Loaded components:
874 .-------------------------------------------------------------------+----------.
875 | Class | Type |
876 +-------------------------------------------------------------------+----------+
877 | MyApp::Controller::Books | instance |
878 | MyApp::Controller::Root | instance |
879 | MyApp::Model::MyAppDB | instance |
880 | MyApp::Model::MyAppDB::Author | class |
881 | MyApp::Model::MyAppDB::Book | class |
882 | MyApp::Model::MyAppDB::BookAuthor | class |
883 | MyApp::View::TT | instance |
884 '-------------------------------------------------------------------+----------'
885
886 [Tue May 16 12:51:37 2006] [catalyst] [debug] Loaded Private actions:
887 .----------------------+----------------------------------------+--------------.
888 | Private | Class | Method |
889 +----------------------+----------------------------------------+--------------+
890 | /default | MyApp::Controller::Root | default |
891 | /end | MyApp | end |
892 | /books/list | MyApp::Controller::Books | list |
893 '----------------------+----------------------------------------+--------------'
894
895 [Tue May 16 12:51:37 2006] [catalyst] [debug] Loaded Path actions:
896 .--------------------------------------+---------------------------------------.
897 | Path | Private |
898 +--------------------------------------+---------------------------------------+
899 | /books/list | /books/list |
900 '--------------------------------------+---------------------------------------'
901
902 [Tue May 16 12:51:37 2006] [catalyst] [info] MyApp powered by Catalyst 5.6902
903 You can connect to your server at http://localhost:3000
904
905Some things you should note in the output above:
906
907=over 4
908
909=item *
910
64ccd8a8 911Catalyst::Model::DBIC::Schema took our C<MyAppDB::Book> and made it
912C<MyApp::Model::MyAppDB::Book> (and similar actions were performed on
913C<MyAppDB::Author> and C<MyAppDB::BookAuthor>).
4d583dd8 914
915=item *
916
64ccd8a8 917The "list" action in our Books controller showed up with a path of
918C</books/list>.
4d583dd8 919
920=back
921
64ccd8a8 922Point your browser to L<http://localhost:3000> and you should still get
923the Catalyst welcome page.
4d583dd8 924
64ccd8a8 925Next, to view the book list, change the URL in your browser to
926L<http://localhost:3000/books/list>. You should get a list of the five
927books loaded by the C<myapp01.sql> script above, with TTSite providing
928the formatting for the very simple output we generated in our template.
929The count and space-separated list of author last names appear on the
930end of each row.
4d583dd8 931
64ccd8a8 932Also notice in the output of the C<script/myapp_server.pl> that DBIC
933used the following SQL to retrieve the data:
4d583dd8 934
935 SELECT me.id, me.title, me.rating FROM books me
936
64ccd8a8 937Along with a list of the following commands to retrieve the authors for
938each book (the lines have been "word wrapped" here to improve
939legibility):
4d583dd8 940
941 SELECT author.id, author.first_name, author.last_name
942 FROM book_authors me
943 JOIN authors author ON ( author.id = me.author_id )
944 WHERE ( me.book_id = ? ): `1'
945
64ccd8a8 946You should see 10 such lines of debug output, two for each of the five
947author_id values (it pulls the data once for the count logic and another
948time to actually display the list).
4d583dd8 949
950
951=head1 AUTHOR
952
953Kennedy Clark, C<hkclark@gmail.com>
954
955Please report any errors, issues or suggestions to the author.
956
71dedf57 957Copyright 2006, Kennedy Clark, under Creative Commons License
958(L<http://creativecommons.org/licenses/by-nc-sa/2.5/>).
4d583dd8 959
960Version: .94
961