3 Catalyst::Manual::Tutorial::04_BasicCRUD - Catalyst Tutorial - Chapter 4: Basic CRUD
8 This is B<Chapter 4 of 10> for the Catalyst tutorial.
10 L<Tutorial Overview|Catalyst::Manual::Tutorial>
16 L<Introduction|Catalyst::Manual::Tutorial::01_Intro>
20 L<Catalyst Basics|Catalyst::Manual::Tutorial::02_CatalystBasics>
24 L<More Catalyst Basics|Catalyst::Manual::Tutorial::03_MoreCatalystBasics>
32 L<Authentication|Catalyst::Manual::Tutorial::05_Authentication>
36 L<Authorization|Catalyst::Manual::Tutorial::06_Authorization>
40 L<Debugging|Catalyst::Manual::Tutorial::07_Debugging>
44 L<Testing|Catalyst::Manual::Tutorial::08_Testing>
48 L<Advanced CRUD|Catalyst::Manual::Tutorial::09_AdvancedCRUD>
52 L<Appendices|Catalyst::Manual::Tutorial::10_Appendices>
59 This chapter of the tutorial builds on the fairly primitive
60 application created in Chapter 3 to add basic support for Create,
61 Read, Update, and Delete (CRUD) of C<Book> objects. Note that the
62 'list' function in Chapter 2 already implements the Read portion of
63 CRUD (although Read normally refers to reading a single object; you
64 could implement full Read functionality using the techniques
65 introduced below). This section will focus on the Create and Delete
66 aspects of CRUD. More advanced capabilities, including full Update
67 functionality, will be addressed in Chapter 9.
69 Although this chapter of the tutorial will show you how to build CRUD
70 functionality yourself, another option is to use a "CRUD builder" type
71 of tool to automate the process. You get less control, but it can be
72 quick and easy. For example, see
73 L<Catalyst::Plugin::AutoCRUD|Catalyst::Plugin::AutoCRUD>,
74 L<CatalystX::CRUD|CatalystX::CRUD>, and
75 L<CatalystX::CRUD::YUI|CatalystX::CRUD::YUI>.
77 You can check out the source code for this example from the Catalyst
78 Subversion repository as per the instructions in
79 L<Catalyst::Manual::Tutorial::01_Intro|Catalyst::Manual::Tutorial::01_Intro>.
82 =head1 FORMLESS SUBMISSION
84 Our initial attempt at object creation will utilize the "URL
85 arguments" feature of Catalyst (we will employ the more common form-
86 based submission in the sections that follow).
89 =head2 Include a Create Action in the Books Controller
91 Edit C<lib/MyApp/Controller/Books.pm> and enter the following method:
95 Create a book with the supplied title, rating, and author
99 sub url_create :Local {
100 # In addition to self & context, get the title, rating, &
101 # author_id args from the URL. Note that Catalyst automatically
102 # puts extra information after the "/<controller_name>/<action_name/"
103 # into @_. The args are separated by the '/' char on the URL.
104 my ($self, $c, $title, $rating, $author_id) = @_;
106 # Call create() on the book model object. Pass the table
107 # columns/field values we want to set as hash values
108 my $book = $c->model('DB::Book')->create({
113 # Add a record to the join table for this book, mapping to
115 $book->add_to_book_authors({author_id => $author_id});
116 # Note: Above is a shortcut for this:
117 # $book->create_related('book_authors', {author_id => $author_id});
119 # Assign the Book object to the stash for display and set template
120 $c->stash(book => $book,
121 template => 'books/create_done.tt2');
124 Notice that Catalyst takes "extra slash-separated information" from the
125 URL and passes it as arguments in C<@_>. The C<url_create> action then
126 uses a simple call to the DBIC C<create> method to add the requested
127 information to the database (with a separate call to
128 C<add_to_book_authors> to update the join table). As do virtually all
129 controller methods (at least the ones that directly handle user input),
130 it then sets the template that should handle this request.
133 =head2 Include a Template for the 'url_create' Action:
135 Edit C<root/src/books/create_done.tt2> and then enter:
137 [% # Use the TT Dumper plugin to Data::Dumper variables to the browser -%]
138 [% # Not a good idea for production use, though. :-) 'Indent=1' is -%]
139 [% # optional, but prevents "massive indenting" of deeply nested objects -%]
140 [% USE Dumper(Indent=1) -%]
142 [% # Set the page title. META can 'go back' and set values in templates -%]
143 [% # that have been processed 'before' this template (here it's for -%]
144 [% # root/lib/site/html and root/lib/site/header). Note that META only -%]
145 [% # works on simple/static strings (i.e. there is no variable -%]
146 [% # interpolation). -%]
147 [% META title = 'Book Created' %]
149 [% # Output information about the record that was added. First title. -%]
150 <p>Added book '[% book.title %]'
152 [% # Output the last name of the first author. -%]
153 by '[% book.authors.first.last_name %]'
155 [% # Output the rating for the book that was added -%]
156 with a rating of [% book.rating %].</p>
158 [% # Provide a link back to the list page -%]
159 [% # 'uri_for()' builds a full URI; e.g., 'http://localhost:3000/books/list' -%]
160 <p><a href="[% c.uri_for('/books/list') %]">Return to list</a></p>
162 [% # Try out the TT Dumper (for development only!) -%]
164 Dump of the 'book' variable:
165 [% Dumper.dump(book) %]
168 The TT C<USE> directive allows access to a variety of plugin modules
169 (TT plugins, that is, not Catalyst plugins) to add extra functionality
170 to the base TT capabilities. Here, the plugin allows
171 L<Data::Dumper|Data::Dumper> "pretty printing" of objects and
172 variables. Other than that, the rest of the code should be familiar
173 from the examples in Chapter 3.
175 Note: If you are using TT v2.15 you will need to change the code that
176 outputs the "last name for the first author" above to match this:
178 [% authors = book.authors %]
179 by '[% authors.first.last_name IF authors.first;
180 authors.list.first.value.last_name IF ! authors.first %]'
182 to get around an issue in TT v2.15 where blessed hash objects were not
183 handled correctly. But, if you are still using v2.15, it's probably
184 time to upgrade (v2.15 is almost 4 years old). If you are following
185 along in Debian, then you should be on at least v2.20. You can test
186 your version of Template Toolkit with the following:
188 perl -MTemplate -e 'print "$Template::VERSION\n"'
191 =head2 Try the 'url_create' Feature
193 Make sure the development server is running with the "-r" restart
196 $ DBIC_TRACE=1 script/myapp_server.pl -r
198 Note that new path for C</books/url_create> appears in the startup debug
201 Next, use your browser to enter the following URL:
203 http://localhost:3000/books/url_create/TCPIP_Illustrated_Vol-2/5/4
205 Your browser should display "Added book 'TCPIP_Illustrated_Vol-2' by
206 'Stevens' with a rating of 5." along with a dump of the new book model
207 object as it was returned by DBIC. You should also see the following
208 DBIC debug messages displayed in the development server log messages
209 if you have DBIC_TRACE set:
211 INSERT INTO book (rating, title) VALUES (?, ?): `5', `TCPIP_Illustrated_Vol-2'
212 INSERT INTO book_author (author_id, book_id) VALUES (?, ?): `4', `6'
214 The C<INSERT> statements are obviously adding the book and linking it to
215 the existing record for Richard Stevens. The C<SELECT> statement results
216 from DBIC automatically fetching the book for the C<Dumper.dump(book)>.
218 If you then click the "Return to list" link, you should find that
219 there are now six books shown (if necessary, Shift+Reload or
220 Ctrl+Reload your browser at the C</books/list> page). You should now
221 see the six DBIC debug messages similar to the following (where
224 SELECT author.id, author.first_name, author.last_name
225 FROM book_author me JOIN author author
226 ON author.id = me.author_id WHERE ( me.book_id = ? ): 'N'
229 =head1 CONVERT TO A CHAINED ACTION
231 Although the example above uses the same C<Local> action type for the
232 method that we saw in the previous chapter of the tutorial, there is an
233 alternate approach that allows us to be more specific while also
234 paving the way for more advanced capabilities. Change the method
235 declaration for C<url_create> in C<lib/MyApp/Controller/Books.pm> you
236 entered above to match the following:
238 sub url_create :Chained('/') :PathPart('books/url_create') :Args(3) {
239 # In addition to self & context, get the title, rating, &
240 # author_id args from the URL. Note that Catalyst automatically
241 # puts the first 3 arguments worth of extra information after the
242 # "/<controller_name>/<action_name/" into @_ because we specified
243 # "Args(3)". The args are separated by the '/' char on the URL.
244 my ($self, $c, $title, $rating, $author_id) = @_;
248 This converts the method to take advantage of the Chained
249 action/dispatch type. Chaining lets you have a single URL
250 automatically dispatch to several controller methods, each of which
251 can have precise control over the number of arguments that it will
252 receive. A chain can essentially be thought of having three parts --
253 a beginning, a middle, and an end. The bullets below summarize the key
254 points behind each of these parts of a chain:
268 B<Use "C<:Chained('/')>" to start a chain>
272 Get arguments through C<CaptureArgs()>
276 Specify the path to match with C<PathPart()>
289 Link to previous part of the chain with C<:Chained('_name_')>
293 Get arguments through C<CaptureArgs()>
297 Specify the path to match with C<PathPart()>
310 Link to previous part of the chain with C<:Chained('_name_')>
314 B<Do NOT get arguments through "C<CaptureArgs()>," use "C<Args()>" instead to end a chain>
318 Specify the path to match with C<PathPart()>
325 In our C<url_create> method above, we have combined all three parts into
326 a single method: C<:Chained('/')> to start the chain,
327 C<:PathPart('books/url_create')> to specify the base URL to match, and
328 C<:Args(3)> to capture exactly three arguments and to end the chain.
330 As we will see shortly, a chain can consist of as many "links" as you
331 wish, with each part capturing some arguments and doing some work
332 along the way. We will continue to use the Chained action type in this
333 chapter of the tutorial and explore slightly more advanced capabilities
334 with the base method and delete feature below. But Chained dispatch
335 is capable of far more. For additional information, see
336 L<Catalyst::Manual::Intro/Action types>,
337 L<Catalyst::DispatchType::Chained|Catalyst::DispatchType::Chained>,
338 and the 2006 Advent calendar entry on the subject:
339 L<http://www.catalystframework.org/calendar/2006/10>.
342 =head2 Try the Chained Action
344 If you look back at the development server startup logs from your
345 initial version of the C<url_create> method (the one using the
346 C<:Local> attribute), you will notice that it produced output similar
349 [debug] Loaded Path actions:
350 .-------------------------------------+--------------------------------------.
352 +-------------------------------------+--------------------------------------+
355 | /books | /books/index |
356 | /books/list | /books/list |
357 | /books/url_create | /books/url_create |
358 '-------------------------------------+--------------------------------------'
360 When the development server restarts, the debug output should change
361 to something along the lines of the following:
363 [debug] Loaded Path actions:
364 .-------------------------------------+--------------------------------------.
366 +-------------------------------------+--------------------------------------+
369 | /books | /books/index |
370 | /books/list | /books/list |
371 '-------------------------------------+--------------------------------------'
373 [debug] Loaded Chained actions:
374 .-------------------------------------+--------------------------------------.
375 | Path Spec | Private |
376 +-------------------------------------+--------------------------------------+
377 | /books/url_create/*/*/* | /books/url_create |
378 '-------------------------------------+--------------------------------------'
380 C<url_create> has disappeared form the "Loaded Path actions" section
381 but it now shows up under the newly created "Loaded Chained actions"
382 section. And the "/*/*/*" portion clearly shows our requirement for
385 As with our non-chained version of C<url_create>, use your browser to
386 enter the following URL:
388 http://localhost:3000/books/url_create/TCPIP_Illustrated_Vol-2/5/4
390 You should see the same "Added book 'TCPIP_Illustrated_Vol-2' by
391 'Stevens' with a rating of 5." along with a dump of the new book model
392 object. Click the "Return to list" link, and you should find that there
393 are now seven books shown (two copies of I<TCPIP_Illustrated_Vol-2>).
396 =head2 Refactor to Use a 'base' Method to Start the Chains
398 Let's make a quick update to our initial Chained action to show a
399 little more of the power of chaining. First, open
400 C<lib/MyApp/Controller/Books.pm> in your editor and add the following
405 Can place common logic to start chained dispatch here
409 sub base :Chained('/') :PathPart('books') :CaptureArgs(0) {
412 # Store the ResultSet in stash so it's available for other methods
413 $c->stash(resultset => $c->model('DB::Book'));
415 # Print a message to the debug log
416 $c->log->debug('*** INSIDE BASE METHOD ***');
419 Here we print a log message and store the DBIC ResultSet in
420 C<$c-E<gt>stash-E<gt>{resultset}> so that it's automatically available
421 for other actions that chain off C<base>. If your controller always
422 needs a book ID as its first argument, you could have the base method
423 capture that argument (with C<:CaptureArgs(1)>) and use it to pull the
424 book object with C<-E<gt>find($id)> and leave it in the stash for
425 later parts of your chains to then act upon. Because we have several
426 actions that don't need to retrieve a book (such as the C<url_create>
427 we are working with now), we will instead add that functionality
428 to a common C<object> action shortly.
430 As for C<url_create>, let's modify it to first dispatch to C<base>.
431 Open up C<lib/MyApp/Controller/Books.pm> and edit the declaration for
432 C<url_create> to match the following:
434 sub url_create :Chained('base') :PathPart('url_create') :Args(3) {
436 Once you save C<lib/MyApp/Controller/Books.pm>, notice that the
437 development server will restart and our "Loaded Chained actions" section
438 will changed slightly:
440 [debug] Loaded Chained actions:
441 .-------------------------------------+--------------------------------------.
442 | Path Spec | Private |
443 +-------------------------------------+--------------------------------------+
444 | /books/url_create/*/*/* | /books/base (0) |
445 | | => /books/url_create |
446 '-------------------------------------+--------------------------------------'
448 The "Path Spec" is the same, but now it maps to two Private actions as
449 we would expect. The C<base> method is being triggered by the
450 C</books> part of the URL. However, the processing then continues to
451 the C<url_create> method because this method "chained" off C<base> and
452 specified C<:PathPart('url_create')> (note that we could have omitted
453 the "PathPart" here because it matches the name of the method, but we
454 will include it to make the logic as explicit as possible).
456 Once again, enter the following URL into your browser:
458 http://localhost:3000/books/url_create/TCPIP_Illustrated_Vol-2/5/4
460 The same "Added book 'TCPIP_Illustrated_Vol-2' by 'Stevens' with a
461 rating of 5." message and a dump of the new book object should appear.
462 Also notice the extra "INSIDE BASE METHOD" debug message in the
463 development server output from the C<base> method. Click the "Return
464 to list" link, and you should find that there are now eight books
465 shown. (You may have a larger number of books if you repeated any of
466 the "create" actions more than once. Don't worry about it as long as
467 the number of books is appropriate for the number of times you added
468 new books... there should be the original five books added via
469 C<myapp01.sql> plus one additional book for each time you ran one
470 of the url_create variations above.)
473 =head1 MANUALLY BUILDING A CREATE FORM
475 Although the C<url_create> action in the previous step does begin to
476 reveal the power and flexibility of both Catalyst and DBIC, it's
477 obviously not a very realistic example of how users should be expected
478 to enter data. This section begins to address that concern.
481 =head2 Add Method to Display The Form
483 Edit C<lib/MyApp/Controller/Books.pm> and add the following method:
487 Display form to collect information for book to create
491 sub form_create :Chained('base') :PathPart('form_create') :Args(0) {
494 # Set the TT template to use
495 $c->stash(template => 'books/form_create.tt2');
498 This action simply invokes a view containing a form to create a book.
501 =head2 Add a Template for the Form
503 Open C<root/src/books/form_create.tt2> in your editor and enter:
505 [% META title = 'Manual Form Book Create' -%]
507 <form method="post" action="[% c.uri_for('form_create_do') %]">
509 <tr><td>Title:</td><td><input type="text" name="title"></td></tr>
510 <tr><td>Rating:</td><td><input type="text" name="rating"></td></tr>
511 <tr><td>Author ID:</td><td><input type="text" name="author_id"></td></tr>
513 <input type="submit" name="Submit" value="Submit">
516 Note that we have specified the target of the form data as
517 C<form_create_do>, the method created in the section that follows.
520 =head2 Add a Method to Process Form Values and Update Database
522 Edit C<lib/MyApp/Controller/Books.pm> and add the following method to
523 save the form information to the database:
525 =head2 form_create_do
527 Take information from form and add to database
531 sub form_create_do :Chained('base') :PathPart('form_create_do') :Args(0) {
534 # Retrieve the values from the form
535 my $title = $c->request->params->{title} || 'N/A';
536 my $rating = $c->request->params->{rating} || 'N/A';
537 my $author_id = $c->request->params->{author_id} || '1';
540 my $book = $c->model('DB::Book')->create({
544 # Handle relationship with author
545 $book->add_to_book_authors({author_id => $author_id});
546 # Note: Above is a shortcut for this:
547 # $book->create_related('book_authors', {author_id => $author_id});
549 # Avoid Data::Dumper issue mentioned earlier
550 # You can probably omit this
551 $Data::Dumper::Useperl = 1;
553 # Store new model object in stash and set template
554 $c->stash(book => $book,
555 template => 'books/create_done.tt2');
559 =head2 Test Out The Form
561 Notice that the server startup log reflects the two new chained
562 methods that we added:
564 [debug] Loaded Chained actions:
565 .-------------------------------------+--------------------------------------.
566 | Path Spec | Private |
567 +-------------------------------------+--------------------------------------+
568 | /books/form_create | /books/base (0) |
569 | | => /books/form_create |
570 | /books/form_create_do | /books/base (0) |
571 | | => /books/form_create_do |
572 | /books/url_create/*/*/* | /books/base (0) |
573 | | => /books/url_create |
574 '-------------------------------------+--------------------------------------'
576 Point your browser to L<http://localhost:3000/books/form_create> and
577 enter "TCP/IP Illustrated, Vol 3" for the title, a rating of 5, and an
578 author ID of 4. You should then see the output of the same
579 C<create_done.tt2> template seen in earlier examples. Finally, click
580 "Return to list" to view the full list of books.
582 B<Note:> Having the user enter the primary key ID for the author is
583 obviously crude; we will address this concern with a drop-down list and
584 add validation to our forms in Chapter 9.
587 =head1 A SIMPLE DELETE FEATURE
589 Turning our attention to the Delete portion of CRUD, this section
590 illustrates some basic techniques that can be used to remove information
594 =head2 Include a Delete Link in the List
596 Edit C<root/src/books/list.tt2> and update it to match the following (two
597 sections have changed: 1) the additional '<th>Links</th>' table header,
598 and 2) the four lines for the Delete link near the bottom):
600 [% # This is a TT comment. The '-' at the end "chomps" the newline. You won't -%]
601 [% # see this "chomping" in your browser because HTML ignores blank lines, but -%]
602 [% # it WILL eliminate a blank line if you view the HTML source. It's purely -%]
603 [%- # optional, but both the beginning and the ending TT tags support chomping. -%]
605 [% # Provide a title -%]
606 [% META title = 'Book List' -%]
609 <tr><th>Title</th><th>Rating</th><th>Author(s)</th><th>Links</th></tr>
610 [% # Display each book in a table row %]
611 [% FOREACH book IN books -%]
613 <td>[% book.title %]</td>
614 <td>[% book.rating %]</td>
616 [% # NOTE: See "Exploring The Power of DBIC" for a better way to do this! -%]
617 [% # First initialize a TT variable to hold a list. Then use a TT FOREACH -%]
618 [% # loop in 'side effect notation' to load just the last names of the -%]
619 [% # authors into the list. Note that the 'push' TT vmethod doesn't return -%]
620 [% # a value, so nothing will be printed here. But, if you have something -%]
621 [% # in TT that does return a value and you don't want it printed, you can -%]
622 [% # 1) assign it to a bogus value, or -%]
623 [% # 2) use the CALL keyword to call it and discard the return value. -%]
625 tt_authors.push(author.last_name) FOREACH author = book.authors %]
626 [% # Now use a TT 'virtual method' to display the author count in parens -%]
627 [% # Note the use of the TT filter "| html" to escape dangerous characters -%]
628 ([% tt_authors.size | html %])
629 [% # Use another TT vmethod to join & print the names & comma separators -%]
630 [% tt_authors.join(', ') | html %]
633 [% # Add a link to delete a book %]
634 <a href="[% c.uri_for(c.controller.action_for('delete'), [book.id]) %]">Delete</a>
640 The additional code is obviously designed to add a new column to the
641 right side of the table with a C<Delete> "button" (for simplicity, links
642 will be used instead of full HTML buttons; in practice, anything that
643 modifies data should be handled with a form sending a POST request).
645 Also notice that we are using a more advanced form of C<uri_for> than
646 we have seen before. Here we use
647 C<$c-E<gt>controller-E<gt>action_for> to automatically generate a URI
648 appropriate for that action based on the method we want to link to
649 while inserting the C<book.id> value into the appropriate place. Now,
650 if you ever change C<:PathPart('delete')> in your controller method to
651 C<:PathPart('kill')>, then your links will automatically update
652 without any changes to your .tt2 template file. As long as the name
653 of your method does not change (here, "delete"), then your links will
654 still be correct. There are a few shortcuts and options when using
661 If you are referring to a method in the current controller, you can
662 use C<$self-E<gt>action_for('_method_name_')>.
666 If you are referring to a method in a different controller, you need
667 to include that controller's name as an argument to C<controller()>, as in
668 C<$c-E<gt>controller('_controller_name_')-E<gt>action_for('_method_name_')>.
672 B<Note:> In practice you should B<never> use a GET request to delete a
673 record -- always use POST for actions that will modify data. We are
674 doing it here for illustrative and simplicity purposes only.
677 =head2 Add a Common Method to Retrieve a Book for the Chain
679 As mentioned earlier, since we have a mixture of actions that operate
680 on a single book ID and others that do not, we should not have C<base>
681 capture the book ID, find the corresponding book in the database and
682 save it in the stash for later links in the chain. However, just
683 because that logic does not belong in C<base> doesn't mean that we
684 can't create another location to centralize the book lookup code. In
685 our case, we will create a method called C<object> that will store the
686 specific book in the stash. Chains that always operate on a single
687 existing book can chain off this method, but methods such as
688 C<url_create> that don't operate on an existing book can chain
691 To add the C<object> method, edit C<lib/MyApp/Controller/Books.pm>
692 and add the following code:
696 Fetch the specified book object based on the book ID and store
701 sub object :Chained('base') :PathPart('id') :CaptureArgs(1) {
702 # $id = primary key of book to delete
703 my ($self, $c, $id) = @_;
705 # Find the book object and store it in the stash
706 $c->stash(object => $c->stash->{resultset}->find($id));
708 # Make sure the lookup was successful. You would probably
709 # want to do something like this in a real app:
710 # $c->detach('/error_404') if !$c->stash->{object};
711 die "Book $id not found!" if !$c->stash->{object};
713 # Print a message to the debug log
714 $c->log->debug("*** INSIDE OBJECT METHOD for obj id=$id ***");
717 Now, any other method that chains off C<object> will automatically
718 have the appropriate book waiting for it in
719 C<$c-E<gt>stash-E<gt>{object}>.
722 =head2 Add a Delete Action to the Controller
724 Open C<lib/MyApp/Controller/Books.pm> in your editor and add the
733 sub delete :Chained('object') :PathPart('delete') :Args(0) {
736 # Use the book object saved by 'object' and delete it along
737 # with related 'book_author' entries
738 $c->stash->{object}->delete;
740 # Set a status message to be displayed at the top of the view
741 $c->stash->{status_msg} = "Book deleted.";
743 # Forward to the list action/method in this controller
747 This method first deletes the book object saved by the C<object> method.
748 However, it also removes the corresponding entry from the
749 C<book_author> table with a cascading delete.
751 Then, rather than forwarding to a "delete done" page as we did with the
752 earlier create example, it simply sets the C<status_msg> to display a
753 notification to the user as the normal list view is rendered.
755 The C<delete> action uses the context C<forward> method to return the
756 user to the book list. The C<detach> method could have also been used.
757 Whereas C<forward> I<returns> to the original action once it is
758 completed, C<detach> does I<not> return. Other than that, the two are
762 =head2 Try the Delete Feature
764 One you save the Books controller, the server should automatically restart.
765 The C<delete> method should now appear in the "Loaded Chained actions" section
766 of the startup debug output:
768 [debug] Loaded Chained actions:
769 .-------------------------------------+--------------------------------------.
770 | Path Spec | Private |
771 +-------------------------------------+--------------------------------------+
772 | /books/id/*/delete | /books/base (0) |
773 | | -> /books/object (1) |
774 | | => /books/delete |
775 | /books/form_create | /books/base (0) |
776 | | => /books/form_create |
777 | /books/form_create_do | /books/base (0) |
778 | | => /books/form_create_do |
779 | /books/url_create/*/*/* | /books/base (0) |
780 | | => /books/url_create |
781 '-------------------------------------+--------------------------------------'
783 Then point your browser to L<http://localhost:3000/books/list> and click
784 the "Delete" link next to the first "TCPIP_Illustrated_Vol-2". A green
785 "Book deleted" status message should display at the top of the page,
786 along with a list of the eight remaining books. You will also see the
787 cascading delete operation via the DBIC_TRACE output:
789 SELECT me.id, me.title, me.rating FROM book me WHERE ( ( me.id = ? ) ): '6'
790 DELETE FROM book WHERE ( id = ? ): '6'
791 SELECT me.book_id, me.author_id FROM book_author me WHERE ( me.book_id = ? ): '6'
792 DELETE FROM book_author WHERE ( author_id = ? AND book_id = ? ): '4', '6'
795 =head2 Fixing a Dangerous URL
797 Note the URL in your browser once you have performed the deletion in the
798 prior step -- it is still referencing the delete action:
800 http://localhost:3000/books/id/6/delete
802 What if the user were to press reload with this URL still active? In
803 this case the redundant delete is harmless (although it does generate
804 an exception screen, it doesn't perform any undesirable actions on the
805 application or database), but in other cases this could clearly be
808 We can improve the logic by converting to a redirect. Unlike
809 C<$c-E<gt>forward('list'))> or C<$c-E<gt>detach('list'))> that perform
810 a server-side alteration in the flow of processing, a redirect is a
811 client-side mechanism that causes the browser to issue an entirely
812 new request. As a result, the URL in the browser is updated to match
813 the destination of the redirection URL.
815 To convert the forward used in the previous section to a redirect,
816 open C<lib/MyApp/Controller/Books.pm> and edit the existing
817 C<sub delete> method to match:
825 sub delete :Chained('object') :PathPart('delete') :Args(0) {
828 # Use the book object saved by 'object' and delete it along
829 # with related 'book_author' entries
830 $c->stash->{object}->delete;
832 # Set a status message to be displayed at the top of the view
833 $c->stash->{status_msg} = "Book deleted.";
835 # Redirect the user back to the list page. Note the use
836 # of $self->action_for as earlier in this section (BasicCRUD)
837 $c->response->redirect($c->uri_for($self->action_for('list')));
841 =head2 Try the Delete and Redirect Logic
843 Point your browser to L<http://localhost:3000/books/list> (don't just
844 hit "Refresh" in your browser since we left the URL in an invalid state
845 in the previous section!) and delete the first copy of the remaining two
846 "TCPIP_Illustrated_Vol-2" books. The URL in your browser should return
847 to the L<http://localhost:3000/books/list> URL, so that is an
848 improvement, but notice that I<no green "Book deleted" status message is
849 displayed>. Because the stash is reset on every request (and a redirect
850 involves a second request), the C<status_msg> is cleared before it can
854 =head2 Using 'uri_for' to Pass Query Parameters
856 There are several ways to pass information across a redirect. One
857 option is to use the C<flash> technique that we will see in Chapter 5
858 of this tutorial; however, here we will pass the information via query
859 parameters on the redirect itself. Open
860 C<lib/MyApp/Controller/Books.pm> and update the existing C<sub delete>
861 method to match the following:
869 sub delete :Chained('object') :PathPart('delete') :Args(0) {
872 # Use the book object saved by 'object' and delete it along
873 # with related 'book_author' entries
874 $c->stash->{object}->delete;
876 # Redirect the user back to the list page with status msg as an arg
877 $c->response->redirect($c->uri_for($self->action_for('list'),
878 {status_msg => "Book deleted."}));
881 This modification simply leverages the ability of C<uri_for> to include
882 an arbitrary number of name/value pairs in a hash reference. Next, we
883 need to update C<root/src/wrapper.tt2> to handle C<status_msg> as a
888 [%# Status and error messages %]
889 <span class="message">[% status_msg || c.request.params.status_msg %]</span>
890 <span class="error">[% error_msg %]</span>
891 [%# This is where TT will stick all of your template's contents. -%]
893 </div><!-- end content -->
896 Although the sample above only shows the C<content> div, leave the
897 rest of the file intact -- the only change we made to the C<wrapper.tt2>
898 was to add "C<|| c.request.params.status_msg>" to the
899 C<E<lt>span class="message"E<gt>> line.
902 =head2 Try the Delete and Redirect With Query Param Logic
904 Point your browser to L<http://localhost:3000/books/list> (you should
905 now be able to safely hit "refresh" in your browser). Then delete the
906 remaining copy of "TCPIP_Illustrated_Vol-2". The green "Book deleted"
907 status message should return. But notice that you can now hit the
908 "Reload" button in your browser and it just redisplays the book
909 list (and it correctly shows it without the "Book deleted" message
912 B<NOTE:> Another popular method for maintaining server-side
913 information across a redirect is to use the C<flash> technique we
914 discuss in the next chapter of the tutorial,
915 L<Authentication|Catalyst::Manual::Tutorial::05_Authentication>. While
916 C<flash> is a "slicker" mechanism in that it's all handled by the
917 server and doesn't "pollute" your URLs, B<it is important to note that
918 C<flash> can lead to situations where the wrong information shows up
919 in the wrong browser window if the user has multiple windows or
920 browser tabs open>. For example, Window A causes something to be
921 placed in the stash, but before that window performs a redirect,
922 Window B makes a request to the server and gets the status information
923 that should really go to Window A. For this reason, you may wish
924 to use the "query param" technique shown here in your applications.
927 =head1 EXPLORING THE POWER OF DBIC
929 In this section we will explore some additional capabilities offered
930 by DBIx::Class. Although these features have relatively little to do
931 with Catalyst per se, you will almost certainly want to take advantage
932 of them in your applications.
935 =head2 Add Datetime Columns to Our Existing Books Table
937 Let's add two columns to our existing C<books> table to track when
938 each book was added and when each book is updated:
941 sqlite> ALTER TABLE book ADD created TIMESTAMP;
942 sqlite> ALTER TABLE book ADD updated TIMESTAMP;
943 sqlite> UPDATE book SET created = DATETIME('NOW'), updated = DATETIME('NOW');
944 sqlite> SELECT * FROM book;
945 1|CCSP SNRS Exam Certification Guide|5|2010-02-16 04:15:45|2010-02-16 04:15:45
946 2|TCP/IP Illustrated, Volume 1|5|2010-02-16 04:15:45|2010-02-16 04:15:45
947 3|Internetworking with TCP/IP Vol.1|4|2010-02-16 04:15:45|2010-02-16 04:15:45
948 4|Perl Cookbook|5|2010-02-16 04:15:45|2010-02-16 04:15:45
949 5|Designing with Web Standards|5|2010-02-16 04:15:45|2010-02-16 04:15:45
950 9|TCP/IP Illustrated, Vol 3|5|2010-02-16 04:15:45|2010-02-16 04:15:45
954 This will modify the C<books> table to include the two new fields
955 and populate those fields with the current time.
958 =head2 Update DBIx::Class to Automatically Handle the Datetime Columns
960 Next, we should re-run the DBIC helper to update the Result Classes
963 $ script/myapp_create.pl model DB DBIC::Schema MyApp::Schema \
964 create=static components=TimeStamp dbi:SQLite:myapp.db \
965 on_connect_do="PRAGMA foreign_keys = ON"
966 exists "/root/dev/MyApp/script/../lib/MyApp/Model"
967 exists "/root/dev/MyApp/script/../t"
968 Dumping manual schema for MyApp::Schema to directory /root/dev/MyApp/script/../lib ...
969 Schema dump completed.
970 exists "/root/dev/MyApp/script/../lib/MyApp/Model/DB.pm"
972 Notice that we modified our use of the helper slightly: we told
973 it to include the L<DBIx::Class::TimeStamp|DBIx::Class::TimeStamp>
974 in the C<load_components> line of the Result Classes.
976 If you open C<lib/MyApp/Schema/Result/Book.pm> in your editor you should
977 see that the C<created> and C<updated> fields are now included in the
978 call to C<add_columns()>. However, also notice that the C<many_to_many>
979 relationships we manually added below the "C<# DO NOT MODIFY...>" line
980 were automatically preserved.
982 While we have this file open, let's update it with some additional
983 information to have DBIC automatically handle the updating of these
984 two fields for us. Insert the following code at the bottom of the
985 file (it B<must> be B<below> the "C<# DO NOT MODIFY...>" line and
986 B<above> the C<1;> on the last line):
989 # Enable automatic date handling
991 __PACKAGE__->add_columns(
993 { data_type => 'timestamp', set_on_create => 1 },
995 { data_type => 'timestamp', set_on_create => 1, set_on_update => 1 },
998 This will override the definition for these fields that Schema::Loader
999 placed at the top of the file. The C<set_on_create> and
1000 C<set_on_update> options will cause DBIx::Class to automatically
1001 update the timestamps in these columns whenever a row is created or
1004 Then enter the following URL into your web browser:
1006 http://localhost:3000/books/url_create/TCPIP_Illustrated_Vol-2/5/4
1008 You should get the same "Book Created" screen we saw above. However,
1009 if you now use the sqlite3 command-line tool to dump the C<books> table,
1010 you will see that the new book we added has an appropriate date and
1011 time entered for it (see the last line in the listing below):
1013 $ sqlite3 myapp.db "select * from book"
1014 1|CCSP SNRS Exam Certification Guide|5|2010-02-16 04:15:45|2010-02-16 04:15:45
1015 2|TCP/IP Illustrated, Volume 1|5|2010-02-16 04:15:45|2010-02-16 04:15:45
1016 3|Internetworking with TCP/IP Vol.1|4|2010-02-16 04:15:45|2010-02-16 04:15:45
1017 4|Perl Cookbook|5|2010-02-16 04:15:45|2010-02-16 04:15:45
1018 5|Designing with Web Standards|5|2010-02-16 04:15:45|2010-02-16 04:15:45
1019 9|TCP/IP Illustrated, Vol 3|5|2010-02-16 04:15:45|2010-02-16 04:15:45
1020 10|TCPIP_Illustrated_Vol-2|5|2010-02-16 04:18:42|2010-02-16 04:18:42
1023 Notice in the debug log that the SQL DBIC generated has changed to
1024 incorporate the datetime logic:
1026 INSERT INTO book ( created, rating, title, updated ) VALUES ( ?, ?, ?, ? ):
1027 '2010-02-16 04:18:42', '5', 'TCPIP_Illustrated_Vol-2', '2010-02-16 04:18:42'
1028 INSERT INTO book_author ( author_id, book_id ) VALUES ( ?, ? ): '4', '10'
1031 =head2 Create a ResultSet Class
1033 An often overlooked but extremely powerful features of DBIC is that it
1034 allows you to supply your own subclasses of C<DBIx::Class::ResultSet>.
1035 It allows you to pull complex and unsightly "query code" out of your
1036 controllers and encapsulate it in a method of your ResultSet Class.
1037 These "canned queries" in your ResultSet Class can then be invoked
1038 via a single call, resulting in much cleaner and easier to read
1041 To illustrate the concept with a fairly simple example, let's create a
1042 method that returns books added in the last 10 minutes. Start by
1043 making a directory where DBIx::Class will look for our ResultSet Class:
1045 $ mkdir lib/MyApp/Schema/ResultSet
1047 Then open C<lib/MyApp/Schema/ResultSet/Book.pm> and enter the following:
1049 package MyApp::Schema::ResultSet::Book;
1053 use base 'DBIx::Class::ResultSet';
1055 =head2 created_after
1057 A predefined search for recently added books
1062 my ($self, $datetime) = @_;
1064 my $date_str = $self->result_source->schema->storage
1065 ->datetime_parser->format_datetime($datetime);
1067 return $self->search({
1068 created => { '>' => $date_str }
1074 Then add the following method to the C<lib/MyApp/Controller/Books.pm>:
1078 List recently created books
1082 sub list_recent :Chained('base') :PathPart('list_recent') :Args(1) {
1083 my ($self, $c, $mins) = @_;
1085 # Retrieve all of the book records as book model objects and store in the
1086 # stash where they can be accessed by the TT template, but only
1087 # retrieve books created within the last $min number of minutes
1088 $c->stash(books => [$c->model('DB::Book')
1089 ->created_after(DateTime->now->subtract(minutes => $mins))]);
1091 # Set the TT template to use. You will almost always want to do this
1092 # in your action methods (action methods respond to user input in
1093 # your controllers).
1094 $c->stash(template => 'books/list.tt2');
1097 Now try different values for the "minutes" argument (the final number
1098 value) using the URL C<http://localhost:3000/books/list_recent/_#_> in
1099 your browser. For example, this would list all books added in the last
1102 http://localhost:3000/books/list_recent/15
1104 Depending on how recently you added books, you might want to
1105 try a higher or lower value for the minutes.
1108 =head2 Chaining ResultSets
1110 One of the most helpful and powerful features in DBIx::Class is that
1111 it allows you to "chain together" a series of queries (note that this
1112 has nothing to do with the "Chained Dispatch" for Catalyst that we
1113 were discussing above). Because each ResultSet returns another
1114 ResultSet, you can take an initial query and immediately feed that
1115 into a second query (and so on for as many queries you need). Note
1116 that no matter how many ResultSets you chain together, the database
1117 itself will not be hit until you use a method that attempts to access
1118 the data. And, because this technique carries over to the ResultSet
1119 Class feature we implemented in the previous section for our "canned
1120 search", we can combine the two capabilities. For example, let's add
1121 an action to our C<Books> controller that lists books that are both
1122 recent I<and> have "TCP" in the title. Open up
1123 C<lib/MyApp/Controller/Books.pm> and add the following method:
1125 =head2 list_recent_tcp
1127 List recently created books
1131 sub list_recent_tcp :Chained('base') :PathPart('list_recent_tcp') :Args(1) {
1132 my ($self, $c, $mins) = @_;
1134 # Retrieve all of the book records as book model objects and store in the
1135 # stash where they can be accessed by the TT template, but only
1136 # retrieve books created within the last $min number of minutes
1137 # AND that have 'TCP' in the title
1138 $c->stash(books => [$c->model('DB::Book')
1139 ->created_after(DateTime->now->subtract(minutes => $mins))
1140 ->search({title => {'like', '%TCP%'}})
1143 # Set the TT template to use. You will almost always want to do this
1144 # in your action methods (action methods respond to user input in
1145 # your controllers).
1146 $c->stash(template => 'books/list.tt2');
1149 To try this out, enter the following URL into your browser:
1151 http://localhost:3000/books/list_recent_tcp/100
1153 And you should get a list of books added in the last 100 minutes that
1154 contain the string "TCP" in the title. However, if you look at all
1155 books within the last 100 minutes, you should get a longer list
1156 (again, you might have to adjust the number of minutes depending on
1157 how recently you added books to your database):
1159 http://localhost:3000/books/list_recent/100
1161 Take a look at the DBIC_TRACE output in the development server log for
1162 the first URL and you should see something similar to the following:
1164 SELECT me.id, me.title, me.rating, me.created, me.updated FROM book me
1165 WHERE ( ( title LIKE ? AND created > ? ) ): '%TCP%', '2010-02-16 02:49:32'
1167 However, let's not pollute our controller code with this raw "TCP"
1168 query -- it would be cleaner to encapsulate that code in a method on
1169 our ResultSet Class. To do this, open
1170 C<lib/MyApp/Schema/ResultSet/Book.pm> and add the following method:
1174 A predefined search for books with a 'LIKE' search in the string
1179 my ($self, $title_str) = @_;
1181 return $self->search({
1182 title => { 'like' => "%$title_str%" }
1186 We defined the search string as C<$title_str> to make the method more
1187 flexible. Now update the C<list_recent_tcp> method in
1188 C<lib/MyApp/Controller/Books.pm> to match the following (we have
1189 replaced the C<-E<gt>search> line with the C<-E<gt>title_like> line
1190 shown here -- the rest of the method should be the same):
1192 =head2 list_recent_tcp
1194 List recently created books
1198 sub list_recent_tcp :Chained('base') :PathPart('list_recent_tcp') :Args(1) {
1199 my ($self, $c, $mins) = @_;
1201 # Retrieve all of the book records as book model objects and store in the
1202 # stash where they can be accessed by the TT template, but only
1203 # retrieve books created within the last $min number of minutes
1204 # AND that have 'TCP' in the title
1205 $c->stash(books => [$c->model('DB::Book')
1206 ->created_after(DateTime->now->subtract(minutes => $mins))
1210 # Set the TT template to use. You will almost always want to do this
1211 # in your action methods (action methods respond to user input in
1212 # your controllers).
1213 $c->stash(template => 'books/list.tt2');
1216 Try out the C<list_recent_tcp> and C<list_recent> URLs as we did above.
1217 They should work just the same, but our code is obviously cleaner and
1218 more modular, while also being more flexible at the same time.
1221 =head2 Adding Methods to Result Classes
1223 In the previous two sections we saw a good example of how we could use
1224 DBIx::Class ResultSet Classes to clean up our code for an entire query
1225 (for example, our "canned searches" that filtered the entire query).
1226 We can do a similar improvement when working with individual rows as
1227 well. Whereas the ResultSet construct is used in DBIC to correspond
1228 to an entire query, the Result Class construct is used to represent a
1229 row. Therefore, we can add row-specific "helper methods" to our Result
1230 Classes stored in C<lib/MyApp/Schema/Result/>. For example, open
1231 C<lib/MyApp/Schema/Result/Author.pm> and add the following method (as
1232 always, it must be above the closing "C<1;>"):
1235 # Row-level helper methods
1240 return $self->first_name . ' ' . $self->last_name;
1243 This will allow us to conveniently retrieve both the first and last
1244 name for an author in one shot. Now open C<root/src/books/list.tt2>
1245 and change the definition of C<tt_authors> from this:
1248 [% tt_authors = [ ];
1249 tt_authors.push(author.last_name) FOREACH author = book.authors %]
1255 [% tt_authors = [ ];
1256 tt_authors.push(author.full_name) FOREACH author = book.authors %]
1259 (Only C<author.last_name> was changed to C<author.full_name> -- the
1260 rest of the file should remain the same.)
1262 Now go to the standard book list URL:
1264 http://localhost:3000/books/list
1266 The "Author(s)" column will now contain both the first and last name.
1267 And, because the concatenation logic was encapsulated inside our
1268 Result Class, it keeps the code inside our TT template nice and clean
1269 (remember, we want the templates to be as close to pure HTML markup as
1270 possible). Obviously, this capability becomes even more useful as you
1271 use to to remove even more complicated row-specific logic from your
1275 =head2 Moving Complicated View Code to the Model
1277 The previous section illustrated how we could use a Result Class
1278 method to print the full names of the authors without adding any extra
1279 code to our view, but it still left us with a fairly ugly mess (see
1280 C<root/src/books/list.tt2>):
1284 [% # NOTE: See Chapter 4 for a better way to do this! -%]
1285 [% # First initialize a TT variable to hold a list. Then use a TT FOREACH -%]
1286 [% # loop in 'side effect notation' to load just the last names of the -%]
1287 [% # authors into the list. Note that the 'push' TT vmethod does not print -%]
1288 [% # a value, so nothing will be printed here. But, if you have something -%]
1289 [% # in TT that does return a method and you don't want it printed, you -%]
1290 [% # can: 1) assign it to a bogus value, or 2) use the CALL keyword to -%]
1291 [% # call it and discard the return value. -%]
1292 [% tt_authors = [ ];
1293 tt_authors.push(author.full_name) FOREACH author = book.authors %]
1294 [% # Now use a TT 'virtual method' to display the author count in parens -%]
1295 [% # Note the use of the TT filter "| html" to escape dangerous characters -%]
1296 ([% tt_authors.size | html %])
1297 [% # Use another TT vmethod to join & print the names & comma separators -%]
1298 [% tt_authors.join(', ') | html %]
1302 Let's combine some of the techniques used earlier in this section to
1303 clean this up. First, let's add a method to our Book Result Class to
1304 return the number of authors for a book. Open
1305 C<lib/MyApp/Schema/Result/Book.pm> and add the following method:
1309 Return the number of authors for the current book
1316 # Use the 'many_to_many' relationship to fetch all of the authors for the current
1317 # and the 'count' method in DBIx::Class::ResultSet to get a SQL COUNT
1318 return $self->authors->count;
1321 Next, let's add a method to return a list of authors for a book to the
1322 same C<lib/MyApp/Schema/Result/Book.pm> file:
1326 Return a comma-separated list of authors for the current book
1333 # Loop through all authors for the current book, calling all the 'full_name'
1334 # Result Class method for each
1336 foreach my $author ($self->authors) {
1337 push(@names, $author->full_name);
1340 return join(', ', @names);
1343 This method loops through each author, using the C<full_name> Result
1344 Class method we added to C<lib/MyApp/Schema/Result/Author.pm> in the
1347 Using these two methods, we can simplify our TT code. Open
1348 C<root/src/books/list.tt2> and update the "Author(s)" table cell to
1349 match the following:
1353 [% # Print count and author list using Result Class methods -%]
1354 ([% book.author_count | html %]) [% book.author_list | html %]
1358 Although most of the code we removed comprised comments, the overall
1359 effect is dramatic... because our view code is so simple, we don't need
1360 huge comments to clue people in to the gist of our code. The view code
1361 is now self-documenting and readable enough that you could probably get
1362 by with no comments at all. All of the "complex" work is being done in
1363 our Result Class methods (and, because we have broken the code into
1364 nice, modular chucks, the Result Class code is hardly something you
1365 would call complex).
1367 As we saw in this section, always strive to keep your view AND
1368 controller code as simple as possible by pulling code out into your
1369 model objects. Because DBIx::Class can be easily extended in so many
1370 ways, it's an excellent to way accomplish this objective. It will
1371 make your code cleaner, easier to write, less error-prone, and easier
1372 to debug and maintain.
1374 Before you conclude this section, hit Refresh in your browser... the
1375 output should be the same even though the backend code has been trimmed
1381 Kennedy Clark, C<hkclark@gmail.com>
1383 Please report any errors, issues or suggestions to the author. The
1384 most recent version of the Catalyst Tutorial can be found at
1385 L<http://dev.catalyst.perl.org/repos/Catalyst/Catalyst-Manual/5.80/trunk/lib/Catalyst/Manual/Tutorial/>.
1387 Copyright 2006-2008, Kennedy Clark, under Creative Commons License
1388 (L<http://creativecommons.org/licenses/by-sa/3.0/us/>).