1Catalyst::Manual::TutorUisaelr::C0o4n_tBraisbiuctCCeaRdtUaDPl(ey3rs)lt:D:oMcaunmueanlt:a:tTiuotnorial::04_BasicCRUD(3)
2
3
4

NAME

6       Catalyst::Manual::Tutorial::04_BasicCRUD - Catalyst Tutorial - Chapter
7       4: Basic CRUD
8

OVERVIEW

10       This is Chapter 4 of 10 for the Catalyst tutorial.
11
12       Tutorial Overview
13
14       1.  Introduction
15
16       2.  Catalyst Basics
17
18       3.  More Catalyst Basics
19
20       4.  04_Basic CRUD
21
22       5.  Authentication
23
24       6.  Authorization
25
26       7.  Debugging
27
28       8.  Testing
29
30       9.  Advanced CRUD
31
32       10. Appendices
33

DESCRIPTION

35       This chapter of the tutorial builds on the fairly primitive application
36       created in Chapter 3 to add basic support for Create, Read, Update, and
37       Delete (CRUD) of "Book" objects.  Note that the 'list' function in
38       Chapter 3 already implements the Read portion of CRUD (although Read
39       normally refers to reading a single object; you could implement full
40       Read functionality using the techniques introduced below).  This
41       section will focus on the Create and Delete aspects of CRUD.  More
42       advanced capabilities, including full Update functionality, will be
43       addressed in Chapter 9.
44
45       Although this chapter of the tutorial will show you how to build CRUD
46       functionality yourself, another option is to use a "CRUD builder" type
47       of tool to automate the process.  You get less control, but it can be
48       quick and easy.  For example, see Catalyst::Plugin::AutoCRUD,
49       CatalystX::CRUD, and CatalystX::CRUD::YUI.
50
51       Source code for the tutorial in included in the /home/catalyst/Final
52       directory of the Tutorial Virtual machine (one subdirectory per
53       chapter).  There are also instructions for downloading the code in
54       Catalyst::Manual::Tutorial::01_Intro.
55

FORMLESS SUBMISSION

57       Our initial attempt at object creation will utilize the "URL arguments"
58       feature of Catalyst (we will employ the more common form-based
59       submission in the sections that follow).
60
61   Include a Create Action in the Books Controller
62       Edit "lib/MyApp/Controller/Books.pm" and enter the following method:
63
64           =head2 url_create
65
66           Create a book with the supplied title, rating, and author
67
68           =cut
69
70           sub url_create :Local {
71               # In addition to self & context, get the title, rating, &
72               # author_id args from the URL.  Note that Catalyst automatically
73               # puts extra information after the "/<controller_name>/<action_name/"
74               # into @_.  The args are separated  by the '/' char on the URL.
75               my ($self, $c, $title, $rating, $author_id) = @_;
76
77               # Call create() on the book model object. Pass the table
78               # columns/field values we want to set as hash values
79               my $book = $c->model('DB::Book')->create({
80                       title  => $title,
81                       rating => $rating
82                   });
83
84               # Add a record to the join table for this book, mapping to
85               # appropriate author
86               $book->add_to_book_authors({author_id => $author_id});
87               # Note: Above is a shortcut for this:
88               # $book->create_related('book_authors', {author_id => $author_id});
89
90               # Assign the Book object to the stash for display and set template
91               $c->stash(book     => $book,
92                         template => 'books/create_done.tt2');
93
94               # Disable caching for this page
95               $c->response->header('Cache-Control' => 'no-cache');
96           }
97
98       Notice that Catalyst takes "extra slash-separated information" from the
99       URL and passes it as arguments in @_ (as long as the number of
100       arguments is not "fixed" using an attribute like :Args(0)).  The
101       "url_create" action then uses a simple call to the DBIC "create" method
102       to add the requested information to the database (with a separate call
103       to "add_to_book_authors" to update the join table).  As do virtually
104       all controller methods (at least the ones that directly handle user
105       input), it then sets the template that should handle this request.
106
107       Also note that we are explicitly setting a "no-cache" "Cache-Control"
108       header to force browsers using the page to get a fresh copy every time.
109       You could even move this to a "auto" method in
110       "lib/MyApp/Controller/Root.pm" and it would automatically get applied
111       to every page in the whole application via a single line of code
112       (remember from Chapter 3, that every "auto" method gets run in the
113       Controller hierarchy).
114
115   Include a Template for the 'url_create' Action:
116       Edit "root/src/books/create_done.tt2" and then enter:
117
118           [% # Use the TT Dumper plugin to Data::Dumper variables to the browser   -%]
119           [% # Not a good idea for production use, though. :-)  'Indent=1' is      -%]
120           [% # optional, but prevents "massive indenting" of deeply nested objects -%]
121           [% USE Dumper(Indent=1) -%]
122
123           [% # Set the page title.  META can 'go back' and set values in templates -%]
124           [% # that have been processed 'before' this template (here it's updating -%]
125           [% # the title in the root/src/wrapper.tt2 wrapper template).  Note that -%]
126           [% # META only works on simple/static strings (i.e. there is no variable -%]
127           [% # interpolation -- if you need dynamic/interpolated content in your   -%]
128           [% # title, set "$c->stash(title => $something)" in the controller).     -%]
129           [% META title = 'Book Created' %]
130
131           [% # Output information about the record that was added.  First title.   -%]
132           <p>Added book '[% book.title %]'
133
134           [% # Then, output the last name of the first author -%]
135           by '[% book.authors.first.last_name %]'
136
137           [% # Then, output the rating for the book that was added -%]
138           with a rating of [% book.rating %].</p>
139
140           [% # Provide a link back to the list page.  'c.uri_for' builds -%]
141           [% # a full URI; e.g., 'http://localhost:3000/books/list'      -%]
142           <p><a href="[% c.uri_for('/books/list') %]">Return to list</a></p>
143
144           [% # Try out the TT Dumper (for development only!) -%]
145           <pre>
146           Dump of the 'book' variable:
147           [% Dumper.dump(book) %]
148           </pre>
149
150       The TT "USE" directive allows access to a variety of plugin modules (TT
151       plugins, that is, not Catalyst plugins) to add extra functionality to
152       the base TT capabilities.  Here, the plugin allows Data::Dumper "pretty
153       printing" of objects and variables.  Other than that, the rest of the
154       code should be familiar from the examples in Chapter 3.
155
156   Try the 'url_create' Feature
157       Make sure the development server is running with the "-r" restart
158       option:
159
160           $ DBIC_TRACE=1 script/myapp_server.pl -r
161
162       Note that new path for "/books/url_create" appears in the startup debug
163       output.
164
165       Next, use your browser to enter the following URL:
166
167           http://localhost:3000/books/url_create/TCPIP_Illustrated_Vol-2/5/4
168
169       Your browser should display "Added book 'TCPIP_Illustrated_Vol-2' by
170       'Stevens' with a rating of 5." along with a dump of the new book model
171       object as it was returned by DBIC.  You should also see the following
172       DBIC debug messages displayed in the development server log messages if
173       you have DBIC_TRACE set:
174
175           INSERT INTO book (rating, title) VALUES (?, ?): `5', `TCPIP_Illustrated_Vol-2'
176           INSERT INTO book_author (author_id, book_id) VALUES (?, ?): `4', `6'
177
178       The "INSERT" statements are obviously adding the book and linking it to
179       the existing record for Richard Stevens.  The "SELECT" statement
180       results from DBIC automatically fetching the book for the
181       "Dumper.dump(book)".
182
183       If you then click the "Return to list" link, you should find that there
184       are now six books shown (if necessary, Shift+Reload or Ctrl+Reload your
185       browser at the "/books/list" page).  You should now see the six DBIC
186       debug messages similar to the following (where N=1-6):
187
188           SELECT author.id, author.first_name, author.last_name
189               FROM book_author me  JOIN author author
190               ON author.id = me.author_id WHERE ( me.book_id = ? ): 'N'
191

CONVERT TO A CHAINED ACTION

193       Although the example above uses the same "Local" action type for the
194       method that we saw in the previous chapter of the tutorial, there is an
195       alternate approach that allows us to be more specific while also paving
196       the way for more advanced capabilities.  Change the method declaration
197       for "url_create" in "lib/MyApp/Controller/Books.pm" you entered above
198       to match the following:
199
200           sub url_create :Chained('/') :PathPart('books/url_create') :Args(3) {
201               # In addition to self & context, get the title, rating, &
202               # author_id args from the URL.  Note that Catalyst automatically
203               # puts the first 3 arguments worth of extra information after the
204               # "/<controller_name>/<action_name/" into @_ because we specified
205               # "Args(3)".  The args are separated  by the '/' char on the URL.
206               my ($self, $c, $title, $rating, $author_id) = @_;
207
208               ...
209
210       This converts the method to take advantage of the Chained
211       action/dispatch type. Chaining lets you have a single URL automatically
212       dispatch to several controller methods, each of which can have precise
213       control over the number of arguments that it will receive.  A chain can
214       essentially be thought of having three parts -- a beginning, a middle,
215       and an end.  The bullets below summarize the key points behind each of
216       these parts of a chain:
217
218       ·   Beginning
219
220           ·   Use "":Chained('/')"" to start a chain
221
222           ·   Get arguments through "CaptureArgs()"
223
224           ·   Specify the path to match with "PathPart()"
225
226       ·   Middle
227
228           ·   Link to previous part of the chain with ":Chained('_name_')"
229
230           ·   Get arguments through "CaptureArgs()"
231
232           ·   Specify the path to match with "PathPart()"
233
234       ·   End
235
236           ·   Link to previous part of the chain with ":Chained('_name_')"
237
238           ·   Do NOT get arguments through ""CaptureArgs()"," use ""Args()""
239               instead to end a chain
240
241           ·   Specify the path to match with "PathPart()"
242
243       In our "url_create" method above, we have combined all three parts into
244       a single method: ":Chained('/')" to start the chain,
245       ":PathPart('books/url_create')" to specify the base URL to match, and
246       :Args(3) to capture exactly three arguments and to end the chain.
247
248       As we will see shortly, a chain can consist of as many "links" as you
249       wish, with each part capturing some arguments and doing some work along
250       the way.  We will continue to use the Chained action type in this
251       chapter of the tutorial and explore slightly more advanced capabilities
252       with the base method and delete feature below.  But Chained dispatch is
253       capable of far more.  For additional information, see "Action types" in
254       Catalyst::Manual::Intro, Catalyst::DispatchType::Chained, and the 2006
255       Advent calendar entry on the subject:
256       <http://www.catalystframework.org/calendar/2006/10>.
257
258   Try the Chained Action
259       If you look back at the development server startup logs from your
260       initial version of the "url_create" method (the one using the ":Local"
261       attribute), you will notice that it produced output similar to the
262       following:
263
264           [debug] Loaded Path actions:
265           .-------------------------------------+--------------------------------------.
266           | Path                                | Private                              |
267           +-------------------------------------+--------------------------------------+
268           | /                                   | /default                             |
269           | /                                   | /index                               |
270           | /books                              | /books/index                         |
271           | /books/list                         | /books/list                          |
272           | /books/url_create                   | /books/url_create                    |
273           '-------------------------------------+--------------------------------------'
274
275       When the development server restarts after our conversion to Chained
276       dispatch, the debug output should change to something along the lines
277       of the following:
278
279           [debug] Loaded Path actions:
280           .-------------------------------------+--------------------------------------.
281           | Path                                | Private                              |
282           +-------------------------------------+--------------------------------------+
283           | /                                   | /default                             |
284           | /                                   | /index                               |
285           | /books                              | /books/index                         |
286           | /books/list                         | /books/list                          |
287           '-------------------------------------+--------------------------------------'
288
289           [debug] Loaded Chained actions:
290           .-------------------------------------+--------------------------------------.
291           | Path Spec                           | Private                              |
292           +-------------------------------------+--------------------------------------+
293           | /books/url_create/*/*/*             | /books/url_create                    |
294           '-------------------------------------+--------------------------------------'
295
296       "url_create" has disappeared from the "Loaded Path actions" section but
297       it now shows up under the newly created "Loaded Chained actions"
298       section.  And the "/*/*/*" portion clearly shows our requirement for
299       three arguments.
300
301       As with our non-chained version of "url_create", use your browser to
302       enter the following URL:
303
304           http://localhost:3000/books/url_create/TCPIP_Illustrated_Vol-2/5/4
305
306       You should see the same "Added book 'TCPIP_Illustrated_Vol-2' by
307       'Stevens' with a rating of 5." along with a dump of the new book model
308       object.  Click the "Return to list" link, and you should find that
309       there are now seven books shown (two copies of
310       TCPIP_Illustrated_Vol-2).
311
312   Refactor to Use a 'base' Method to Start the Chains
313       Let's make a quick update to our initial Chained action to show a
314       little more of the power of chaining.  First, open
315       "lib/MyApp/Controller/Books.pm" in your editor and add the following
316       method:
317
318           =head2 base
319
320           Can place common logic to start chained dispatch here
321
322           =cut
323
324           sub base :Chained('/') :PathPart('books') :CaptureArgs(0) {
325               my ($self, $c) = @_;
326
327               # Store the ResultSet in stash so it's available for other methods
328               $c->stash(resultset => $c->model('DB::Book'));
329
330               # Print a message to the debug log
331               $c->log->debug('*** INSIDE BASE METHOD ***');
332           }
333
334       Here we print a log message and store the DBIC ResultSet in
335       "$c->stash->{resultset}" so that it's automatically available for other
336       actions that chain off "base".  If your controller always needs a book
337       ID as its first argument, you could have the base method capture that
338       argument (with :CaptureArgs(1)) and use it to pull the book object with
339       "->find($id)" and leave it in the stash for later parts of your chains
340       to then act upon. Because we have several actions that don't need to
341       retrieve a book (such as the "url_create" we are working with now), we
342       will instead add that functionality to a common "object" action
343       shortly.
344
345       As for "url_create", let's modify it to first dispatch to "base".  Open
346       up "lib/MyApp/Controller/Books.pm" and edit the declaration for
347       "url_create" to match the following:
348
349           sub url_create :Chained('base') :PathPart('url_create') :Args(3) {
350
351       Once you save "lib/MyApp/Controller/Books.pm", notice that the
352       development server will restart and our "Loaded Chained actions"
353       section will changed slightly:
354
355           [debug] Loaded Chained actions:
356           .-------------------------------------+--------------------------------------.
357           | Path Spec                           | Private                              |
358           +-------------------------------------+--------------------------------------+
359           | /books/url_create/*/*/*             | /books/base (0)                      |
360           |                                     | => /books/url_create                 |
361           '-------------------------------------+--------------------------------------'
362
363       The "Path Spec" is the same, but now it maps to two Private actions as
364       we would expect.  The "base" method is being triggered by the "/books"
365       part of the URL.  However, the processing then continues to the
366       "url_create" method because this method "chained" off "base" and
367       specified ":PathPart('url_create')" (note that we could have omitted
368       the "PathPart" here because it matches the name of the method, but we
369       will include it to make the logic as explicit as possible).
370
371       Once again, enter the following URL into your browser:
372
373           http://localhost:3000/books/url_create/TCPIP_Illustrated_Vol-2/5/4
374
375       The same "Added book 'TCPIP_Illustrated_Vol-2' by 'Stevens' with a
376       rating of 5." message and a dump of the new book object should appear.
377       Also notice the extra "INSIDE BASE METHOD" debug message in the
378       development server output from the "base" method.  Click the "Return to
379       list" link, and you should find that there are now eight books shown.
380       (You may have a larger number of books if you repeated any of the
381       "create" actions more than once.  Don't worry about it as long as the
382       number of books is appropriate for the number of times you added new
383       books... there should be the original five books added via
384       "myapp01.sql" plus one additional book for each time you ran one of the
385       url_create variations above.)
386

MANUALLY BUILDING A CREATE FORM

388       Although the "url_create" action in the previous step does begin to
389       reveal the power and flexibility of both Catalyst and DBIC, it's
390       obviously not a very realistic example of how users should be expected
391       to enter data.  This section begins to address that concern (but just
392       barely, see Chapter 9 for better options for handling web-based forms).
393
394   Add Method to Display The Form
395       Edit "lib/MyApp/Controller/Books.pm" and add the following method:
396
397           =head2 form_create
398
399           Display form to collect information for book to create
400
401           =cut
402
403           sub form_create :Chained('base') :PathPart('form_create') :Args(0) {
404               my ($self, $c) = @_;
405
406               # Set the TT template to use
407               $c->stash(template => 'books/form_create.tt2');
408           }
409
410       This action simply invokes a view containing a form to create a book.
411
412   Add a Template for the Form
413       Open "root/src/books/form_create.tt2" in your editor and enter:
414
415           [% META title = 'Manual Form Book Create' -%]
416
417           <form method="post" action="[% c.uri_for('form_create_do') %]">
418           <table>
419             <tr><td>Title:</td><td><input type="text" name="title"></td></tr>
420             <tr><td>Rating:</td><td><input type="text" name="rating"></td></tr>
421             <tr><td>Author ID:</td><td><input type="text" name="author_id"></td></tr>
422           </table>
423           <input type="submit" name="Submit" value="Submit">
424           </form>
425
426       Note that we have specified the target of the form data as
427       "form_create_do", the method created in the section that follows.
428
429   Add a Method to Process Form Values and Update Database
430       Edit "lib/MyApp/Controller/Books.pm" and add the following method to
431       save the form information to the database:
432
433           =head2 form_create_do
434
435           Take information from form and add to database
436
437           =cut
438
439           sub form_create_do :Chained('base') :PathPart('form_create_do') :Args(0) {
440               my ($self, $c) = @_;
441
442               # Retrieve the values from the form
443               my $title     = $c->request->params->{title}     || 'N/A';
444               my $rating    = $c->request->params->{rating}    || 'N/A';
445               my $author_id = $c->request->params->{author_id} || '1';
446
447               # Create the book
448               my $book = $c->model('DB::Book')->create({
449                       title   => $title,
450                       rating  => $rating,
451                   });
452               # Handle relationship with author
453               $book->add_to_book_authors({author_id => $author_id});
454               # Note: Above is a shortcut for this:
455               # $book->create_related('book_authors', {author_id => $author_id});
456
457               # Store new model object in stash and set template
458               $c->stash(book     => $book,
459                         template => 'books/create_done.tt2');
460           }
461
462   Test Out The Form
463       Notice that the server startup log reflects the two new chained methods
464       that we added:
465
466           [debug] Loaded Chained actions:
467           .-------------------------------------+--------------------------------------.
468           | Path Spec                           | Private                              |
469           +-------------------------------------+--------------------------------------+
470           | /books/form_create                  | /books/base (0)                      |
471           |                                     | => /books/form_create                |
472           | /books/form_create_do               | /books/base (0)                      |
473           |                                     | => /books/form_create_do             |
474           | /books/url_create/*/*/*             | /books/base (0)                      |
475           |                                     | => /books/url_create                 |
476           '-------------------------------------+--------------------------------------'
477
478       Point your browser to <http://localhost:3000/books/form_create> and
479       enter "TCP/IP Illustrated, Vol 3" for the title, a rating of 5, and an
480       author ID of 4.  You should then see the output of the same
481       "create_done.tt2" template seen in earlier examples.  Finally, click
482       "Return to list" to view the full list of books.
483
484       Note: Having the user enter the primary key ID for the author is
485       obviously crude; we will address this concern with a drop-down list and
486       add validation to our forms in Chapter 9.
487

A SIMPLE DELETE FEATURE

489       Turning our attention to the Delete portion of CRUD, this section
490       illustrates some basic techniques that can be used to remove
491       information from the database.
492
493   Include a Delete Link in the List
494       Edit "root/src/books/list.tt2" and update it to match the following
495       (two sections have changed: 1) the additional '<th>Links</th>' table
496       header, and 2) the five lines for the Delete link near the bottom):
497
498           [% # This is a TT comment. -%]
499
500           [%- # Provide a title -%]
501           [% META title = 'Book List' -%]
502
503           [% # Note That the '-' at the beginning or end of TT code  -%]
504           [% # "chomps" the whitespace/newline at that end of the    -%]
505           [% # output (use View Source in browser to see the effect) -%]
506
507           [% # Some basic HTML with a loop to display books -%]
508           <table>
509           <tr><th>Title</th><th>Rating</th><th>Author(s)</th><th>Links</th></tr>
510           [% # Display each book in a table row %]
511           [% FOREACH book IN books -%]
512             <tr>
513               <td>[% book.title %]</td>
514               <td>[% book.rating %]</td>
515               <td>
516                 [% # NOTE: See Chapter 4 for a better way to do this!                      -%]
517                 [% # First initialize a TT variable to hold a list.  Then use a TT FOREACH -%]
518                 [% # loop in 'side effect notation' to load just the last names of the     -%]
519                 [% # authors into the list. Note that the 'push' TT vmethod doesn't return -%]
520                 [% # a value, so nothing will be printed here.  But, if you have something -%]
521                 [% # in TT that does return a value and you don't want it printed, you     -%]
522                 [% # 1) assign it to a bogus value, or                                     -%]
523                 [% # 2) use the CALL keyword to call it and discard the return value.      -%]
524                 [% tt_authors = [ ];
525                    tt_authors.push(author.last_name) FOREACH author = book.authors %]
526                 [% # Now use a TT 'virtual method' to display the author count in parens   -%]
527                 [% # Note the use of the TT filter "| html" to escape dangerous characters -%]
528                 ([% tt_authors.size | html %])
529                 [% # Use another TT vmethod to join & print the names & comma separators   -%]
530                 [% tt_authors.join(', ') | html %]
531               </td>
532               <td>
533                 [% # Add a link to delete a book %]
534                 <a href="[%
535                   c.uri_for(c.controller.action_for('delete'), [book.id]) %]">Delete</a>
536               </td>
537             </tr>
538           [% END -%]
539           </table>
540
541       The additional code is obviously designed to add a new column to the
542       right side of the table with a "Delete" "button" (for simplicity, links
543       will be used instead of full HTML buttons; but, in practice, anything
544       that modifies data should be handled with a form sending a POST
545       request).
546
547       Also notice that we are using a more advanced form of "uri_for" than we
548       have seen before.  Here we use "$c->controller->action_for" to
549       automatically generate a URI appropriate for that action based on the
550       method we want to link to while inserting the "book.id" value into the
551       appropriate place.  Now, if you ever change ":PathPart('delete')" in
552       your controller method to something like ":PathPart('kill')", then your
553       links will automatically update without any changes to your .tt2
554       template file.  As long as the name of your method does not change
555       (here, "delete"), then your links will still be correct.  There are a
556       few shortcuts and options when using "action_for()":
557
558       ·   If you are referring to a method in the current controller, you can
559           use "$self->action_for('_method_name_')".
560
561       ·   If you are referring to a method in a different controller, you
562           need to include that controller's name as an argument to
563           "controller()", as in
564           "$c->controller('_controller_name_')->action_for('_method_name_')".
565
566       Note: In practice you should never use a GET request to delete a record
567       -- always use POST for actions that will modify data.  We are doing it
568       here for illustrative and simplicity purposes only.
569
570   Add a Common Method to Retrieve a Book for the Chain
571       As mentioned earlier, since we have a mixture of actions that operate
572       on a single book ID and others that do not, we should not have "base"
573       capture the book ID, find the corresponding book in the database and
574       save it in the stash for later links in the chain.  However, just
575       because that logic does not belong in "base" doesn't mean that we can't
576       create another location to centralize the book lookup code.  In our
577       case, we will create a method called "object" that will store the
578       specific book in the stash.  Chains that always operate on a single
579       existing book can chain off this method, but methods such as
580       "url_create" that don't operate on an existing book can chain directly
581       off base.
582
583       To add the "object" method, edit "lib/MyApp/Controller/Books.pm" and
584       add the following code:
585
586           =head2 object
587
588           Fetch the specified book object based on the book ID and store
589           it in the stash
590
591           =cut
592
593           sub object :Chained('base') :PathPart('id') :CaptureArgs(1) {
594               # $id = primary key of book to delete
595               my ($self, $c, $id) = @_;
596
597               # Find the book object and store it in the stash
598               $c->stash(object => $c->stash->{resultset}->find($id));
599
600               # Make sure the lookup was successful.  You would probably
601               # want to do something like this in a real app:
602               #   $c->detach('/error_404') if !$c->stash->{object};
603               die "Book $id not found!" if !$c->stash->{object};
604
605               # Print a message to the debug log
606               $c->log->debug("*** INSIDE OBJECT METHOD for obj id=$id ***");
607           }
608
609       Now, any other method that chains off "object" will automatically have
610       the appropriate book waiting for it in "$c->stash->{object}".
611
612   Add a Delete Action to the Controller
613       Open "lib/MyApp/Controller/Books.pm" in your editor and add the
614       following method:
615
616           =head2 delete
617
618           Delete a book
619
620           =cut
621
622           sub delete :Chained('object') :PathPart('delete') :Args(0) {
623               my ($self, $c) = @_;
624
625               # Use the book object saved by 'object' and delete it along
626               # with related 'book_author' entries
627               $c->stash->{object}->delete;
628
629               # Set a status message to be displayed at the top of the view
630               $c->stash->{status_msg} = "Book deleted.";
631
632               # Forward to the list action/method in this controller
633               $c->forward('list');
634           }
635
636       This method first deletes the book object saved by the "object" method.
637       However, it also removes the corresponding entry from the "book_author"
638       table with a cascading delete.
639
640       Then, rather than forwarding to a "delete done" page as we did with the
641       earlier create example, it simply sets the "status_msg" to display a
642       notification to the user as the normal list view is rendered.
643
644       The "delete" action uses the context "forward" method to return the
645       user to the book list.  The "detach" method could have also been used.
646       Whereas "forward" returns to the original action once it is completed,
647       "detach" does not return.  Other than that, the two are equivalent.
648
649   Try the Delete Feature
650       Once you save the Books controller, the server should automatically
651       restart.  The "delete" method should now appear in the "Loaded Chained
652       actions" section of the startup debug output:
653
654           [debug] Loaded Chained actions:
655           .-------------------------------------+--------------------------------------.
656           | Path Spec                           | Private                              |
657           +-------------------------------------+--------------------------------------+
658           | /books/id/*/delete                  | /books/base (0)                      |
659           |                                     | -> /books/object (1)                 |
660           |                                     | => /books/delete                     |
661           | /books/form_create                  | /books/base (0)                      |
662           |                                     | => /books/form_create                |
663           | /books/form_create_do               | /books/base (0)                      |
664           |                                     | => /books/form_create_do             |
665           | /books/url_create/*/*/*             | /books/base (0)                      |
666           |                                     | => /books/url_create                 |
667           '-------------------------------------+--------------------------------------'
668
669       Then point your browser to <http://localhost:3000/books/list> and click
670       the "Delete" link next to the first "TCPIP_Illustrated_Vol-2".  A green
671       "Book deleted" status message should display at the top of the page,
672       along with a list of the eight remaining books.  You will also see the
673       cascading delete operation via the DBIC_TRACE output:
674
675           SELECT me.id, me.title, me.rating FROM book me WHERE ( ( me.id = ? ) ): '6'
676           DELETE FROM book WHERE ( id = ? ): '6'
677
678       If you get the error "file error - books/delete.tt2: not found" then
679       you probably forgot to uncomment the template line in "sub list" at the
680       end of chapter 3.
681
682   Fixing a Dangerous URL
683       Note the URL in your browser once you have performed the deletion in
684       the prior step -- it is still referencing the delete action:
685
686           http://localhost:3000/books/id/6/delete
687
688       What if the user were to press reload with this URL still active?  In
689       this case the redundant delete is harmless (although it does generate
690       an exception screen, it doesn't perform any undesirable actions on the
691       application or database), but in other cases this could clearly lead to
692       trouble.
693
694       We can improve the logic by converting to a redirect.  Unlike
695       "$c->forward('list'))" or "$c->detach('list'))" that perform a server-
696       side alteration in the flow of processing, a redirect is a client-side
697       mechanism that causes the browser to issue an entirely new request.  As
698       a result, the URL in the browser is updated to match the destination of
699       the redirection URL.
700
701       To convert the forward used in the previous section to a redirect, open
702       "lib/MyApp/Controller/Books.pm" and edit the existing "sub delete"
703       method to match:
704
705           =head2 delete
706
707           Delete a book
708
709           =cut
710
711           sub delete :Chained('object') :PathPart('delete') :Args(0) {
712               my ($self, $c) = @_;
713
714               # Use the book object saved by 'object' and delete it along
715               # with related 'book_author' entries
716               $c->stash->{object}->delete;
717
718               # Set a status message to be displayed at the top of the view
719               $c->stash->{status_msg} = "Book deleted.";
720
721               # Redirect the user back to the list page.  Note the use
722               # of $self->action_for as earlier in this section (BasicCRUD)
723               $c->response->redirect($c->uri_for($self->action_for('list')));
724           }
725
726   Try the Delete and Redirect Logic
727       Point your browser to <http://localhost:3000/books/list> (don't just
728       hit "Refresh" in your browser since we left the URL in an invalid state
729       in the previous section!) and delete the first copy of the remaining
730       two "TCPIP_Illustrated_Vol-2" books. The URL in your browser should
731       return to the <http://localhost:3000/books/list> URL, so that is an
732       improvement, but notice that no green "Book deleted" status message is
733       displayed. Because the stash is reset on every request (and a redirect
734       involves a second request), the "status_msg" is cleared before it can
735       be displayed.
736
737   Using 'uri_for' to Pass Query Parameters
738       There are several ways to pass information across a redirect. One
739       option is to use the "flash" technique that we will see in Chapter 5 of
740       this tutorial; however, here we will pass the information via query
741       parameters on the redirect itself.  Open
742       "lib/MyApp/Controller/Books.pm" and update the existing "sub delete"
743       method to match the following:
744
745           =head2 delete
746
747           Delete a book
748
749           =cut
750
751           sub delete :Chained('object') :PathPart('delete') :Args(0) {
752               my ($self, $c) = @_;
753
754               # Use the book object saved by 'object' and delete it along
755               # with related 'book_author' entries
756               $c->stash->{object}->delete;
757
758               # Redirect the user back to the list page with status msg as an arg
759               $c->response->redirect($c->uri_for($self->action_for('list'),
760                   {status_msg => "Book deleted."}));
761           }
762
763       This modification simply leverages the ability of "uri_for" to include
764       an arbitrary number of name/value pairs in a hash reference.  Next, we
765       need to update "root/src/wrapper.tt2" to handle "status_msg" as a query
766       parameter:
767
768           ...
769           <div id="content">
770               [%# Status and error messages %]
771               <span class="message">[%
772                   status_msg || c.request.params.status_msg | html %]</span>
773               <span class="error">[% error_msg %]</span>
774               [%# This is where TT will stick all of your template's contents. -%]
775               [% content %]
776           </div><!-- end content -->
777           ...
778
779       Although the sample above only shows the "content" div, leave the rest
780       of the file intact -- the only change we made to the "wrapper.tt2" was
781       to add ""|| c.request.params.status_msg"" to the "<span
782       class="message">" line.  Note that we definitely want the ""| html"" TT
783       filter here since it would be easy for users to modify the message on
784       the URL and possibly inject harmful code into the application if we
785       left that off.
786
787   Try the Delete and Redirect With Query Param Logic
788       Point your browser to <http://localhost:3000/books/list> (you should
789       now be able to safely hit "refresh" in your browser). Then delete the
790       remaining copy of "TCPIP_Illustrated_Vol-2". The green "Book deleted"
791       status message should return.  But notice that you can now hit the
792       "Reload" button in your browser and it just redisplays the book list
793       (and it correctly shows it without the "Book deleted" message on
794       redisplay).
795
796       NOTE: Be sure to check out Authentication where we use an improved
797       technique that is better suited to your real world applications.
798

EXPLORING THE POWER OF DBIC

800       In this section we will explore some additional capabilities offered by
801       DBIx::Class.  Although these features have relatively little to do with
802       Catalyst per se, you will almost certainly want to take advantage of
803       them in your applications.
804
805   Add Datetime Columns to Our Existing Books Table
806       Let's add two columns to our existing "books" table to track when each
807       book was added and when each book is updated:
808
809           $ sqlite3 myapp.db
810           sqlite> ALTER TABLE book ADD created TIMESTAMP;
811           sqlite> ALTER TABLE book ADD updated TIMESTAMP;
812           sqlite> UPDATE book SET created = DATETIME('NOW'), updated = DATETIME('NOW');
813           sqlite> SELECT * FROM book;
814           1|CCSP SNRS Exam Certification Guide|5|2010-02-16 04:15:45|2010-02-16 04:15:45
815           2|TCP/IP Illustrated, Volume 1|5|2010-02-16 04:15:45|2010-02-16 04:15:45
816           3|Internetworking with TCP/IP Vol.1|4|2010-02-16 04:15:45|2010-02-16 04:15:45
817           4|Perl Cookbook|5|2010-02-16 04:15:45|2010-02-16 04:15:45
818           5|Designing with Web Standards|5|2010-02-16 04:15:45|2010-02-16 04:15:45
819           9|TCP/IP Illustrated, Vol 3|5|2010-02-16 04:15:45|2010-02-16 04:15:45
820           sqlite> .quit
821           $
822
823       Here are the commands without the surrounding sqlite3 prompt and output
824       in case you want to cut and paste them as a single block (but still
825       start sqlite3 before you paste these in):
826
827           ALTER TABLE book ADD created TIMESTAMP;
828           ALTER TABLE book ADD updated TIMESTAMP;
829           UPDATE book SET created = DATETIME('NOW'), updated = DATETIME('NOW');
830           SELECT * FROM book;
831
832       This will modify the "books" table to include the two new fields and
833       populate those fields with the current time.
834
835   Update DBIx::Class to Automatically Handle the Datetime Columns
836       Next, we should re-run the DBIC helper to update the Result Classes
837       with the new fields:
838
839           $ script/myapp_create.pl model DB DBIC::Schema MyApp::Schema \
840               create=static components=TimeStamp dbi:SQLite:myapp.db \
841               on_connect_do="PRAGMA foreign_keys = ON"
842            exists "/home/catalyst/dev/MyApp/script/../lib/MyApp/Model"
843            exists "/home/catalyst/dev/MyApp/script/../t"
844           Dumping manual schema for MyApp::Schema to directory /home/catalyst/dev/MyApp/script/../lib ...
845           Schema dump completed.
846            exists "/home/catalyst/dev/MyApp/script/../lib/MyApp/Model/DB.pm"
847
848       Notice that we modified our use of the helper slightly: we told it to
849       include the DBIx::Class::TimeStamp in the "load_components" line of the
850       Result Classes.
851
852       If you open "lib/MyApp/Schema/Result/Book.pm" in your editor you should
853       see that the "created" and "updated" fields are now included in the
854       call to "add_columns()". However, also notice that the "many_to_many"
855       relationships we manually added below the ""# DO NOT MODIFY..."" line
856       were automatically preserved.
857
858       While we "lib/MyApp/Schema/Result/Book.pm" open, let's update it with
859       some additional information to have DBIC automatically handle the
860       updating of these two fields for us.  Insert the following code at the
861       bottom of the file (it must be below the ""# DO NOT MODIFY...""  line
862       and above the "1;" on the last line):
863
864           #
865           # Enable automatic date handling
866           #
867           __PACKAGE__->add_columns(
868               "created",
869               { data_type => 'timestamp', set_on_create => 1 },
870               "updated",
871               { data_type => 'timestamp', set_on_create => 1, set_on_update => 1 },
872           );
873
874       This will override the definition for these fields that Schema::Loader
875       placed at the top of the file.  The "set_on_create" and "set_on_update"
876       options will cause DBIx::Class to automatically update the timestamps
877       in these columns whenever a row is created or modified.
878
879       Note that adding the lines above will cause the development server to
880       automatically restart if you are running it with the "-r" option.  In
881       other words, the development server is smart enough to restart not only
882       for code under the "MyApp/Controller/", "MyApp/Model/", and
883       "MyApp/View/" directories, but also under other directions such as our
884       "external DBIC model" in "MyApp/Schema/".  However, also note that it's
885       smart enough to not restart when you edit your ".tt2" files under
886       "root/".
887
888       Then enter the following URL into your web browser:
889
890           http://localhost:3000/books/url_create/TCPIP_Illustrated_Vol-2/5/4
891
892       You should get the same "Book Created" screen we saw earlier.  However,
893       if you now use the sqlite3 command-line tool to dump the "books" table,
894       you will see that the new book we added has an appropriate date and
895       time entered for it (see the last line in the listing below):
896
897           $ sqlite3 myapp.db "select * from book"
898           1|CCSP SNRS Exam Certification Guide|5|2010-02-16 04:15:45|2010-02-16 04:15:45
899           2|TCP/IP Illustrated, Volume 1|5|2010-02-16 04:15:45|2010-02-16 04:15:45
900           3|Internetworking with TCP/IP Vol.1|4|2010-02-16 04:15:45|2010-02-16 04:15:45
901           4|Perl Cookbook|5|2010-02-16 04:15:45|2010-02-16 04:15:45
902           5|Designing with Web Standards|5|2010-02-16 04:15:45|2010-02-16 04:15:45
903           9|TCP/IP Illustrated, Vol 3|5|2010-02-16 04:15:45|2010-02-16 04:15:45
904           10|TCPIP_Illustrated_Vol-2|5|2010-02-16 04:18:42|2010-02-16 04:18:42
905
906       Notice in the debug log that the SQL DBIC generated has changed to
907       incorporate the datetime logic:
908
909           INSERT INTO book ( created, rating, title, updated ) VALUES ( ?, ?, ?, ? ):
910           '2010-02-16 04:18:42', '5', 'TCPIP_Illustrated_Vol-2', '2010-02-16 04:18:42'
911           INSERT INTO book_author ( author_id, book_id ) VALUES ( ?, ? ): '4', '10'
912
913   Create a ResultSet Class
914       An often overlooked but extremely powerful features of DBIC is that it
915       allows you to supply your own subclasses of "DBIx::Class::ResultSet".
916       This can be used to pull complex and unsightly "query code" out of your
917       controllers and encapsulate it in a method of your ResultSet Class.
918       These "canned queries" in your ResultSet Class can then be invoked via
919       a single call, resulting in much cleaner and easier to read controller
920       code (or View code, if that's where you want to call it).
921
922       To illustrate the concept with a fairly simple example, let's create a
923       method that returns books added in the last 10 minutes.  Start by
924       making a directory where DBIx::Class will look for our ResultSet Class:
925
926           $ mkdir lib/MyApp/Schema/ResultSet
927
928       Then open "lib/MyApp/Schema/ResultSet/Book.pm" and enter the following:
929
930           package MyApp::Schema::ResultSet::Book;
931
932           use strict;
933           use warnings;
934           use base 'DBIx::Class::ResultSet';
935
936           =head2 created_after
937
938           A predefined search for recently added books
939
940           =cut
941
942           sub created_after {
943               my ($self, $datetime) = @_;
944
945               my $date_str = $self->result_source->schema->storage
946                                     ->datetime_parser->format_datetime($datetime);
947
948               return $self->search({
949                   created => { '>' => $date_str }
950               });
951           }
952
953           1;
954
955       Then add the following method to the "lib/MyApp/Controller/Books.pm":
956
957           =head2 list_recent
958
959           List recently created books
960
961           =cut
962
963           sub list_recent :Chained('base') :PathPart('list_recent') :Args(1) {
964               my ($self, $c, $mins) = @_;
965
966               # Retrieve all of the book records as book model objects and store in the
967               # stash where they can be accessed by the TT template, but only
968               # retrieve books created within the last $min number of minutes
969               $c->stash(books => [$c->model('DB::Book')
970                                       ->created_after(DateTime->now->subtract(minutes => $mins))]);
971
972               # Set the TT template to use.  You will almost always want to do this
973               # in your action methods (action methods respond to user input in
974               # your controllers).
975               $c->stash(template => 'books/list.tt2');
976           }
977
978       Now try different values for the "minutes" argument (the final number
979       value) using the URL "http://localhost:3000/books/list_recent/_#_" in
980       your browser. For example, this would list all books added in the last
981       fifteen minutes:
982
983           http://localhost:3000/books/list_recent/15
984
985       Depending on how recently you added books, you might want to try a
986       higher or lower value for the minutes.
987
988   Chaining ResultSets
989       One of the most helpful and powerful features in "DBIx::Class" is that
990       it allows you to "chain together" a series of queries (note that this
991       has nothing to do with the "Chained Dispatch" for Catalyst that we were
992       discussing earlier).  Because each ResultSet method returns another
993       ResultSet, you can take an initial query and immediately feed that into
994       a second query (and so on for as many queries you need).  Note that no
995       matter how many ResultSets you chain together, the database itself will
996       not be hit until you use a method that attempts to access the data.
997       And, because this technique carries over to the ResultSet Class feature
998       we implemented in the previous section for our "canned search", we can
999       combine the two capabilities.  For example, let's add an action to our
1000       "Books" controller that lists books that are both recent and have "TCP"
1001       in the title.  Open up "lib/MyApp/Controller/Books.pm" and add the
1002       following method:
1003
1004           =head2 list_recent_tcp
1005
1006           List recently created books
1007
1008           =cut
1009
1010           sub list_recent_tcp :Chained('base') :PathPart('list_recent_tcp') :Args(1) {
1011               my ($self, $c, $mins) = @_;
1012
1013               # Retrieve all of the book records as book model objects and store in the
1014               # stash where they can be accessed by the TT template, but only
1015               # retrieve books created within the last $min number of minutes
1016               # AND that have 'TCP' in the title
1017               $c->stash(books => [
1018                       $c->model('DB::Book')
1019                           ->created_after(DateTime->now->subtract(minutes => $mins))
1020                           ->search({title => {'like', '%TCP%'}})
1021                   ]);
1022
1023               # Set the TT template to use.  You will almost always want to do this
1024               # in your action methods (action methods respond to user input in
1025               # your controllers).
1026               $c->stash(template => 'books/list.tt2');
1027           }
1028
1029       To try this out, enter the following URL into your browser:
1030
1031           http://localhost:3000/books/list_recent_tcp/100
1032
1033       And you should get a list of books added in the last 100 minutes that
1034       contain the string "TCP" in the title.  However, if you look at all
1035       books within the last 100 minutes, you should get a longer list (again,
1036       you might have to adjust the number of minutes depending on how
1037       recently you added books to your database):
1038
1039           http://localhost:3000/books/list_recent/100
1040
1041       Take a look at the DBIC_TRACE output in the development server log for
1042       the first URL and you should see something similar to the following:
1043
1044           SELECT me.id, me.title, me.rating, me.created, me.updated FROM book me
1045           WHERE ( ( title LIKE ? AND created > ? ) ): '%TCP%', '2010-02-16 02:49:32'
1046
1047       However, let's not pollute our controller code with this raw "TCP"
1048       query -- it would be cleaner to encapsulate that code in a method on
1049       our ResultSet Class.  To do this, open
1050       "lib/MyApp/Schema/ResultSet/Book.pm" and add the following method:
1051
1052           =head2 title_like
1053
1054           A predefined search for books with a 'LIKE' search in the string
1055
1056           =cut
1057
1058           sub title_like {
1059               my ($self, $title_str) = @_;
1060
1061               return $self->search({
1062                   title => { 'like' => "%$title_str%" }
1063               });
1064           }
1065
1066       We defined the search string as $title_str to make the method more
1067       flexible.  Now update the "list_recent_tcp" method in
1068       "lib/MyApp/Controller/Books.pm" to match the following (we have
1069       replaced the "->search" line with the "->title_like" line shown here --
1070       the rest of the method should be the same):
1071
1072           =head2 list_recent_tcp
1073
1074           List recently created books
1075
1076           =cut
1077
1078           sub list_recent_tcp :Chained('base') :PathPart('list_recent_tcp') :Args(1) {
1079               my ($self, $c, $mins) = @_;
1080
1081               # Retrieve all of the book records as book model objects and store in the
1082               # stash where they can be accessed by the TT template, but only
1083               # retrieve books created within the last $min number of minutes
1084               # AND that have 'TCP' in the title
1085               $c->stash(books => [
1086                       $c->model('DB::Book')
1087                           ->created_after(DateTime->now->subtract(minutes => $mins))
1088                           ->title_like('TCP')
1089                   ]);
1090
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');
1095           }
1096
1097       Try out the "list_recent_tcp" and "list_recent" URLs as we did above.
1098       They should work just the same, but our code is obviously cleaner and
1099       more modular, while also being more flexible at the same time.
1100
1101   Adding Methods to Result Classes
1102       In the previous two sections we saw a good example of how we could use
1103       DBIx::Class ResultSet Classes to clean up our code for an entire query
1104       (for example, our "canned searches" that filtered the entire query).
1105       We can do a similar improvement when working with individual rows as
1106       well.  Whereas the ResultSet construct is used in DBIC to correspond to
1107       an entire query, the Result Class construct is used to represent a row.
1108       Therefore, we can add row-specific "helper methods" to our Result
1109       Classes stored in "lib/MyApp/Schema/Result/". For example, open
1110       "lib/MyApp/Schema/Result/Author.pm" and add the following method (as
1111       always, it must be above the closing ""1;""):
1112
1113           #
1114           # Row-level helper methods
1115           #
1116           sub full_name {
1117               my ($self) = @_;
1118
1119               return $self->first_name . ' ' . $self->last_name;
1120           }
1121
1122       This will allow us to conveniently retrieve both the first and last
1123       name for an author in one shot.  Now open "root/src/books/list.tt2" and
1124       change the definition of "tt_authors" from this:
1125
1126           ...
1127             [% tt_authors = [ ];
1128                tt_authors.push(author.last_name) FOREACH author = book.authors %]
1129           ...
1130
1131       to:
1132
1133           ...
1134             [% tt_authors = [ ];
1135                tt_authors.push(author.full_name) FOREACH author = book.authors %]
1136           ...
1137
1138       (Only "author.last_name" was changed to "author.full_name" -- the rest
1139       of the file should remain the same.)
1140
1141       Now go to the standard book list URL:
1142
1143           http://localhost:3000/books/list
1144
1145       The "Author(s)" column will now contain both the first and last name.
1146       And, because the concatenation logic was encapsulated inside our Result
1147       Class, it keeps the code inside our TT template nice and clean
1148       (remember, we want the templates to be as close to pure HTML markup as
1149       possible). Obviously, this capability becomes even more useful as you
1150       use it to remove even more complicated row-specific logic from your
1151       templates!
1152
1153   Moving Complicated View Code to the Model
1154       The previous section illustrated how we could use a Result Class method
1155       to print the full names of the authors without adding any extra code to
1156       our view, but it still left us with a fairly ugly mess (see
1157       "root/src/books/list.tt2"):
1158
1159           ...
1160           <td>
1161             [% # NOTE: See Chapter 4 for a better way to do this!                      -%]
1162             [% # First initialize a TT variable to hold a list.  Then use a TT FOREACH -%]
1163             [% # loop in 'side effect notation' to load just the last names of the     -%]
1164             [% # authors into the list. Note that the 'push' TT vmethod does not print -%]
1165             [% # a value, so nothing will be printed here.  But, if you have something -%]
1166             [% # in TT that does return a method and you don't want it printed, you    -%]
1167             [% # can: 1) assign it to a bogus value, or 2) use the CALL keyword to     -%]
1168             [% # call it and discard the return value.                                 -%]
1169             [% tt_authors = [ ];
1170                tt_authors.push(author.full_name) FOREACH author = book.authors %]
1171             [% # Now use a TT 'virtual method' to display the author count in parens   -%]
1172             [% # Note the use of the TT filter "| html" to escape dangerous characters -%]
1173             ([% tt_authors.size | html %])
1174             [% # Use another TT vmethod to join & print the names & comma separators   -%]
1175             [% tt_authors.join(', ') | html %]
1176           </td>
1177           ...
1178
1179       Let's combine some of the techniques used earlier in this section to
1180       clean this up.  First, let's add a method to our Book Result Class to
1181       return the number of authors for a book.  Open
1182       "lib/MyApp/Schema/Result/Book.pm" and add the following method:
1183
1184           =head2 author_count
1185
1186           Return the number of authors for the current book
1187
1188           =cut
1189
1190           sub author_count {
1191               my ($self) = @_;
1192
1193               # Use the 'many_to_many' relationship to fetch all of the authors for the current
1194               # and the 'count' method in DBIx::Class::ResultSet to get a SQL COUNT
1195               return $self->authors->count;
1196           }
1197
1198       Next, let's add a method to return a list of authors for a book to the
1199       same "lib/MyApp/Schema/Result/Book.pm" file:
1200
1201           =head2 author_list
1202
1203           Return a comma-separated list of authors for the current book
1204
1205           =cut
1206
1207           sub author_list {
1208               my ($self) = @_;
1209
1210               # Loop through all authors for the current book, calling all the 'full_name'
1211               # Result Class method for each
1212               my @names;
1213               foreach my $author ($self->authors) {
1214                   push(@names, $author->full_name);
1215               }
1216
1217               return join(', ', @names);
1218           }
1219
1220       This method loops through each author, using the "full_name" Result
1221       Class method we added to "lib/MyApp/Schema/Result/Author.pm" in the
1222       prior section.
1223
1224       Using these two methods, we can simplify our TT code.  Open
1225       "root/src/books/list.tt2" and update the "Author(s)" table cell to
1226       match the following:
1227
1228           ...
1229           <td>
1230             [% # Print count and author list using Result Class methods -%]
1231             ([% book.author_count | html %]) [% book.author_list | html %]
1232           </td>
1233           ...
1234
1235       Although most of the code we removed comprised comments, the overall
1236       effect is dramatic... because our view code is so simple, we don't need
1237       huge comments to clue people in to the gist of our code.  The view code
1238       is now self-documenting and readable enough that you could probably get
1239       by with no comments at all.  All of the "complex" work is being done in
1240       our Result Class methods (and, because we have broken the code into
1241       nice, modular chunks, the Result Class code is hardly something you
1242       would call complex).
1243
1244       As we saw in this section, always strive to keep your view AND
1245       controller code as simple as possible by pulling code out into your
1246       model objects.  Because DBIx::Class can be easily extended in so many
1247       ways, it's an excellent to way accomplish this objective.  It will make
1248       your code cleaner, easier to write, less error-prone, and easier to
1249       debug and maintain.
1250
1251       Before you conclude this section, hit Refresh in your browser... the
1252       output should be the same even though the backend code has been trimmed
1253       down.
1254
1255       You can jump to the next chapter of the tutorial here: Authentication
1256

AUTHOR

1258       Kennedy Clark, "hkclark@gmail.com"
1259
1260       Feel free to contact the author for any errors or suggestions, but the
1261       best way to report issues is via the CPAN RT Bug system at
1262       <https://rt.cpan.org/Public/Dist/Display.html?Name=Catalyst-Manual>.
1263
1264       Copyright 2006-2011, Kennedy Clark, under the Creative Commons
1265       Attribution Share-Alike License Version 3.0
1266       (<http://creativecommons.org/licenses/by-sa/3.0/us/>).
1267
1268
1269
1270perl v5.28.1                      20C1a4t-a0l2y-s2t8::Manual::Tutorial::04_BasicCRUD(3)
Impressum