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 to
111       every page in the whole application via a single line of code (remember
112       from Chapter 3, that every "auto" method gets run in the Controller
113       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 to
198       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
220Use "":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
238Do 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 myapp01.sql
384       plus one additional book for each time you ran one of the url_create
385       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 save
431       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 (two
495       sections have changed: 1) the additional '<th>Links</th>' table header,
496       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 add
584       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 following
614       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" method
703       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 lib/MyApp/Controller/Books.pm
742       and update the existing "sub delete" method to match the following:
743
744           =head2 delete
745
746           Delete a book
747
748           =cut
749
750           sub delete :Chained('object') :PathPart('delete') :Args(0) {
751               my ($self, $c) = @_;
752
753               # Use the book object saved by 'object' and delete it along
754               # with related 'book_author' entries
755               $c->stash->{object}->delete;
756
757               # Redirect the user back to the list page with status msg as an arg
758               $c->response->redirect($c->uri_for($self->action_for('list'),
759                   {status_msg => "Book deleted."}));
760           }
761
762       This modification simply leverages the ability of "uri_for" to include
763       an arbitrary number of name/value pairs in a hash reference.  Next, we
764       need to update root/src/wrapper.tt2 to handle "status_msg" as a query
765       parameter:
766
767           ...
768           <div id="content">
769               [%# Status and error messages %]
770               <span class="message">[%
771                   status_msg || c.request.params.status_msg | html %]</span>
772               <span class="error">[% error_msg %]</span>
773               [%# This is where TT will stick all of your template's contents. -%]
774               [% content %]
775           </div><!-- end content -->
776           ...
777
778       Although the sample above only shows the "content" div, leave the rest
779       of the file intact -- the only change we made to the wrapper.tt2 was to
780       add ""|| c.request.params.status_msg"" to the "<span class="message">"
781       line.  Note that we definitely want the ""| html"" TT filter here since
782       it would be easy for users to modify the message on the URL and
783       possibly inject harmful code into the application if we left that off.
784
785   Try the Delete and Redirect With Query Param Logic
786       Point your browser to <http://localhost:3000/books/list> (you should
787       now be able to safely hit "refresh" in your browser). Then delete the
788       remaining copy of "TCPIP_Illustrated_Vol-2". The green "Book deleted"
789       status message should return.  But notice that you can now hit the
790       "Reload" button in your browser and it just redisplays the book list
791       (and it correctly shows it without the "Book deleted" message on
792       redisplay).
793
794       NOTE: Be sure to check out Authentication where we use an improved
795       technique that is better suited to your real world applications.
796

EXPLORING THE POWER OF DBIC

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

AUTHOR

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