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