1Catalyst::Manual::TutorUisaelr::C0o4n_tBraisbiuctCCeaRdtUaDPl(ey3rs)lt:D:oMcaunmueanlt:a:tTiuotnorial::04_BasicCRUD(3)
2
3
4
6 Catalyst::Manual::Tutorial::04_BasicCRUD - Catalyst Tutorial - Chapter
7 4: Basic CRUD
8
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
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 2 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 You can check out the source code for this example from the Catalyst
52 Subversion repository as per the instructions in
53 Catalyst::Manual::Tutorial::01_Intro.
54
56 Our initial attempt at object creation will utilize the "URL arguments"
57 feature of Catalyst (we will employ the more common form- based
58 submission in the sections that follow).
59
60 Include a Create Action in the Books Controller
61 Edit "lib/MyApp/Controller/Books.pm" and enter the following method:
62
63 =head2 url_create
64
65 Create a book with the supplied title, rating, and author
66
67 =cut
68
69 sub url_create :Local {
70 # In addition to self & context, get the title, rating, &
71 # author_id args from the URL. Note that Catalyst automatically
72 # puts extra information after the "/<controller_name>/<action_name/"
73 # into @_. The args are separated by the '/' char on the URL.
74 my ($self, $c, $title, $rating, $author_id) = @_;
75
76 # Call create() on the book model object. Pass the table
77 # columns/field values we want to set as hash values
78 my $book = $c->model('DB::Book')->create({
79 title => $title,
80 rating => $rating
81 });
82
83 # Add a record to the join table for this book, mapping to
84 # appropriate author
85 $book->add_to_book_authors({author_id => $author_id});
86 # Note: Above is a shortcut for this:
87 # $book->create_related('book_authors', {author_id => $author_id});
88
89 # Assign the Book object to the stash for display and set template
90 $c->stash(book => $book,
91 template => 'books/create_done.tt2');
92 }
93
94 Notice that Catalyst takes "extra slash-separated information" from the
95 URL and passes it as arguments in @_. The "url_create" action then
96 uses a simple call to the DBIC "create" method to add the requested
97 information to the database (with a separate call to
98 "add_to_book_authors" to update the join table). As do virtually all
99 controller methods (at least the ones that directly handle user input),
100 it then sets the template that should handle this request.
101
102 Include a Template for the 'url_create' Action:
103 Edit "root/src/books/create_done.tt2" and then enter:
104
105 [% # Use the TT Dumper plugin to Data::Dumper variables to the browser -%]
106 [% # Not a good idea for production use, though. :-) 'Indent=1' is -%]
107 [% # optional, but prevents "massive indenting" of deeply nested objects -%]
108 [% USE Dumper(Indent=1) -%]
109
110 [% # Set the page title. META can 'go back' and set values in templates -%]
111 [% # that have been processed 'before' this template (here it's for -%]
112 [% # root/lib/site/html and root/lib/site/header). Note that META only -%]
113 [% # works on simple/static strings (i.e. there is no variable -%]
114 [% # interpolation). -%]
115 [% META title = 'Book Created' %]
116
117 [% # Output information about the record that was added. First title. -%]
118 <p>Added book '[% book.title %]'
119
120 [% # Output the last name of the first author. -%]
121 by '[% book.authors.first.last_name %]'
122
123 [% # Output the rating for the book that was added -%]
124 with a rating of [% book.rating %].</p>
125
126 [% # Provide a link back to the list page -%]
127 [% # 'uri_for()' builds a full URI; e.g., 'http://localhost:3000/books/list' -%]
128 <p><a href="[% c.uri_for('/books/list') %]">Return to list</a></p>
129
130 [% # Try out the TT Dumper (for development only!) -%]
131 <pre>
132 Dump of the 'book' variable:
133 [% Dumper.dump(book) %]
134 </pre>
135
136 The TT "USE" directive allows access to a variety of plugin modules (TT
137 plugins, that is, not Catalyst plugins) to add extra functionality to
138 the base TT capabilities. Here, the plugin allows Data::Dumper "pretty
139 printing" of objects and variables. Other than that, the rest of the
140 code should be familiar from the examples in Chapter 3.
141
142 Note: If you are using TT v2.15 you will need to change the code that
143 outputs the "last name for the first author" above to match this:
144
145 [% authors = book.authors %]
146 by '[% authors.first.last_name IF authors.first;
147 authors.list.first.value.last_name IF ! authors.first %]'
148
149 to get around an issue in TT v2.15 where blessed hash objects were not
150 handled correctly. But, if you are still using v2.15, it's probably
151 time to upgrade (v2.15 is almost 4 years old). If you are following
152 along in Debian, then you should be on at least v2.20. You can test
153 your version of Template Toolkit with the following:
154
155 perl -MTemplate -e 'print "$Template::VERSION\n"'
156
157 Try the 'url_create' Feature
158 Make sure the development server is running with the "-r" restart
159 option:
160
161 $ DBIC_TRACE=1 script/myapp_server.pl -r
162
163 Note that new path for "/books/url_create" appears in the startup debug
164 output.
165
166 Next, use your browser to enter the following URL:
167
168 http://localhost:3000/books/url_create/TCPIP_Illustrated_Vol-2/5/4
169
170 Your browser should display "Added book 'TCPIP_Illustrated_Vol-2' by
171 'Stevens' with a rating of 5." along with a dump of the new book model
172 object as it was returned by DBIC. You should also see the following
173 DBIC debug messages displayed in the development server log messages if
174 you have DBIC_TRACE set:
175
176 INSERT INTO book (rating, title) VALUES (?, ?): `5', `TCPIP_Illustrated_Vol-2'
177 INSERT INTO book_author (author_id, book_id) VALUES (?, ?): `4', `6'
178
179 The "INSERT" statements are obviously adding the book and linking it to
180 the existing record for Richard Stevens. The "SELECT" statement
181 results from DBIC automatically fetching the book for the
182 "Dumper.dump(book)".
183
184 If you then click the "Return to list" link, you should find that there
185 are now six books shown (if necessary, Shift+Reload or Ctrl+Reload your
186 browser at the "/books/list" page). You should now see the six DBIC
187 debug messages similar to the following (where N=1-6):
188
189 SELECT author.id, author.first_name, author.last_name
190 FROM book_author me JOIN author author
191 ON author.id = me.author_id WHERE ( me.book_id = ? ): 'N'
192
194 Although the example above uses the same "Local" action type for the
195 method that we saw in the previous chapter of the tutorial, there is an
196 alternate approach that allows us to be more specific while also paving
197 the way for more advanced capabilities. Change the method declaration
198 for "url_create" in "lib/MyApp/Controller/Books.pm" you entered above
199 to match the following:
200
201 sub url_create :Chained('/') :PathPart('books/url_create') :Args(3) {
202 # In addition to self & context, get the title, rating, &
203 # author_id args from the URL. Note that Catalyst automatically
204 # puts the first 3 arguments worth of extra information after the
205 # "/<controller_name>/<action_name/" into @_ because we specified
206 # "Args(3)". The args are separated by the '/' char on the URL.
207 my ($self, $c, $title, $rating, $author_id) = @_;
208
209 ...
210
211 This converts the method to take advantage of the Chained
212 action/dispatch type. Chaining lets you have a single URL automatically
213 dispatch to several controller methods, each of which can have precise
214 control over the number of arguments that it will receive. A chain can
215 essentially be thought of having three parts -- a beginning, a middle,
216 and an end. The bullets below summarize the key points behind each of
217 these parts of a chain:
218
219 · Beginning
220
221 · Use "":Chained('/')"" to start a chain
222
223 · Get arguments through "CaptureArgs()"
224
225 · Specify the path to match with "PathPart()"
226
227 · Middle
228
229 · Link to previous part of the chain with ":Chained('_name_')"
230
231 · Get arguments through "CaptureArgs()"
232
233 · Specify the path to match with "PathPart()"
234
235 · End
236
237 · Link to previous part of the chain with ":Chained('_name_')"
238
239 · Do NOT get arguments through ""CaptureArgs()"," use ""Args()""
240 instead to end a chain
241
242 · Specify the path to match with "PathPart()"
243
244 In our "url_create" method above, we have combined all three parts into
245 a single method: ":Chained('/')" to start the chain,
246 ":PathPart('books/url_create')" to specify the base URL to match, and
247 :Args(3) to capture exactly three arguments and to end the chain.
248
249 As we will see shortly, a chain can consist of as many "links" as you
250 wish, with each part capturing some arguments and doing some work along
251 the way. We will continue to use the Chained action type in this
252 chapter of the tutorial and explore slightly more advanced capabilities
253 with the base method and delete feature below. But Chained dispatch is
254 capable of far more. For additional information, see "Action types" in
255 Catalyst::Manual::Intro, Catalyst::DispatchType::Chained, and the 2006
256 Advent calendar entry on the subject:
257 <http://www.catalystframework.org/calendar/2006/10>.
258
259 Try the Chained Action
260 If you look back at the development server startup logs from your
261 initial version of the "url_create" method (the one using the ":Local"
262 attribute), you will notice that it produced output similar to the
263 following:
264
265 [debug] Loaded Path actions:
266 .-------------------------------------+--------------------------------------.
267 | Path | Private |
268 +-------------------------------------+--------------------------------------+
269 | / | /default |
270 | / | /index |
271 | /books | /books/index |
272 | /books/list | /books/list |
273 | /books/url_create | /books/url_create |
274 '-------------------------------------+--------------------------------------'
275
276 When the development server restarts, the debug output should change to
277 something along the lines 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 form 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
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.
392
393 Add Method to Display The Form
394 Edit "lib/MyApp/Controller/Books.pm" and add the following method:
395
396 =head2 form_create
397
398 Display form to collect information for book to create
399
400 =cut
401
402 sub form_create :Chained('base') :PathPart('form_create') :Args(0) {
403 my ($self, $c) = @_;
404
405 # Set the TT template to use
406 $c->stash(template => 'books/form_create.tt2');
407 }
408
409 This action simply invokes a view containing a form to create a book.
410
411 Add a Template for the Form
412 Open "root/src/books/form_create.tt2" in your editor and enter:
413
414 [% META title = 'Manual Form Book Create' -%]
415
416 <form method="post" action="[% c.uri_for('form_create_do') %]">
417 <table>
418 <tr><td>Title:</td><td><input type="text" name="title"></td></tr>
419 <tr><td>Rating:</td><td><input type="text" name="rating"></td></tr>
420 <tr><td>Author ID:</td><td><input type="text" name="author_id"></td></tr>
421 </table>
422 <input type="submit" name="Submit" value="Submit">
423 </form>
424
425 Note that we have specified the target of the form data as
426 "form_create_do", the method created in the section that follows.
427
428 Add a Method to Process Form Values and Update Database
429 Edit "lib/MyApp/Controller/Books.pm" and add the following method to
430 save the form information to the database:
431
432 =head2 form_create_do
433
434 Take information from form and add to database
435
436 =cut
437
438 sub form_create_do :Chained('base') :PathPart('form_create_do') :Args(0) {
439 my ($self, $c) = @_;
440
441 # Retrieve the values from the form
442 my $title = $c->request->params->{title} || 'N/A';
443 my $rating = $c->request->params->{rating} || 'N/A';
444 my $author_id = $c->request->params->{author_id} || '1';
445
446 # Create the book
447 my $book = $c->model('DB::Book')->create({
448 title => $title,
449 rating => $rating,
450 });
451 # Handle relationship with author
452 $book->add_to_book_authors({author_id => $author_id});
453 # Note: Above is a shortcut for this:
454 # $book->create_related('book_authors', {author_id => $author_id});
455
456 # Avoid Data::Dumper issue mentioned earlier
457 # You can probably omit this
458 $Data::Dumper::Useperl = 1;
459
460 # Store new model object in stash and set template
461 $c->stash(book => $book,
462 template => 'books/create_done.tt2');
463 }
464
465 Test Out The Form
466 Notice that the server startup log reflects the two new chained methods
467 that we added:
468
469 [debug] Loaded Chained actions:
470 .-------------------------------------+--------------------------------------.
471 | Path Spec | Private |
472 +-------------------------------------+--------------------------------------+
473 | /books/form_create | /books/base (0) |
474 | | => /books/form_create |
475 | /books/form_create_do | /books/base (0) |
476 | | => /books/form_create_do |
477 | /books/url_create/*/*/* | /books/base (0) |
478 | | => /books/url_create |
479 '-------------------------------------+--------------------------------------'
480
481 Point your browser to <http://localhost:3000/books/form_create> and
482 enter "TCP/IP Illustrated, Vol 3" for the title, a rating of 5, and an
483 author ID of 4. You should then see the output of the same
484 "create_done.tt2" template seen in earlier examples. Finally, click
485 "Return to list" to view the full list of books.
486
487 Note: Having the user enter the primary key ID for the author is
488 obviously crude; we will address this concern with a drop-down list and
489 add validation to our forms in Chapter 9.
490
492 Turning our attention to the Delete portion of CRUD, this section
493 illustrates some basic techniques that can be used to remove
494 information from the database.
495
496 Include a Delete Link in the List
497 Edit "root/src/books/list.tt2" and update it to match the following
498 (two sections have changed: 1) the additional '<th>Links</th>' table
499 header, and 2) the four lines for the Delete link near the bottom):
500
501 [% # This is a TT comment. The '-' at the end "chomps" the newline. You won't -%]
502 [% # see this "chomping" in your browser because HTML ignores blank lines, but -%]
503 [% # it WILL eliminate a blank line if you view the HTML source. It's purely -%]
504 [%- # optional, but both the beginning and the ending TT tags support chomping. -%]
505
506 [% # Provide a title -%]
507 [% META title = 'Book List' -%]
508
509 <table>
510 <tr><th>Title</th><th>Rating</th><th>Author(s)</th><th>Links</th></tr>
511 [% # Display each book in a table row %]
512 [% FOREACH book IN books -%]
513 <tr>
514 <td>[% book.title %]</td>
515 <td>[% book.rating %]</td>
516 <td>
517 [% # NOTE: See "Exploring The Power of DBIC" for a better way to do this! -%]
518 [% # First initialize a TT variable to hold a list. Then use a TT FOREACH -%]
519 [% # loop in 'side effect notation' to load just the last names of the -%]
520 [% # authors into the list. Note that the 'push' TT vmethod doesn't return -%]
521 [% # a value, so nothing will be printed here. But, if you have something -%]
522 [% # in TT that does return a value and you don't want it printed, you can -%]
523 [% # 1) assign it to a bogus value, or -%]
524 [% # 2) use the CALL keyword to call it and discard the return value. -%]
525 [% tt_authors = [ ];
526 tt_authors.push(author.last_name) FOREACH author = book.authors %]
527 [% # Now use a TT 'virtual method' to display the author count in parens -%]
528 [% # Note the use of the TT filter "| html" to escape dangerous characters -%]
529 ([% tt_authors.size | html %])
530 [% # Use another TT vmethod to join & print the names & comma separators -%]
531 [% tt_authors.join(', ') | html %]
532 </td>
533 <td>
534 [% # Add a link to delete a book %]
535 <a href="[% 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; in practice, anything that
544 modifies data should be handled with a form sending a POST request).
545
546 Also notice that we are using a more advanced form of "uri_for" than we
547 have seen before. Here we use "$c->controller->action_for" to
548 automatically generate a URI appropriate for that action based on the
549 method we want to link to while inserting the "book.id" value into the
550 appropriate place. Now, if you ever change ":PathPart('delete')" in
551 your controller method to ":PathPart('kill')", then your links will
552 automatically update without any changes to your .tt2 template file.
553 As long as the name of your method does not change (here, "delete"),
554 then your links will still be correct. There are a few shortcuts and
555 options when using "action_for()":
556
557 · If you are referring to a method in the current controller, you can
558 use "$self->action_for('_method_name_')".
559
560 · If you are referring to a method in a different controller, you
561 need to include that controller's name as an argument to
562 "controller()", as in
563 "$c->controller('_controller_name_')->action_for('_method_name_')".
564
565 Note: In practice you should never use a GET request to delete a record
566 -- always use POST for actions that will modify data. We are doing it
567 here for illustrative and simplicity purposes only.
568
569 Add a Common Method to Retrieve a Book for the Chain
570 As mentioned earlier, since we have a mixture of actions that operate
571 on a single book ID and others that do not, we should not have "base"
572 capture the book ID, find the corresponding book in the database and
573 save it in the stash for later links in the chain. However, just
574 because that logic does not belong in "base" doesn't mean that we can't
575 create another location to centralize the book lookup code. In our
576 case, we will create a method called "object" that will store the
577 specific book in the stash. Chains that always operate on a single
578 existing book can chain off this method, but methods such as
579 "url_create" that don't operate on an existing book can chain directly
580 off base.
581
582 To add the "object" method, edit "lib/MyApp/Controller/Books.pm" and
583 add the following code:
584
585 =head2 object
586
587 Fetch the specified book object based on the book ID and store
588 it in the stash
589
590 =cut
591
592 sub object :Chained('base') :PathPart('id') :CaptureArgs(1) {
593 # $id = primary key of book to delete
594 my ($self, $c, $id) = @_;
595
596 # Find the book object and store it in the stash
597 $c->stash(object => $c->stash->{resultset}->find($id));
598
599 # Make sure the lookup was successful. You would probably
600 # want to do something like this in a real app:
601 # $c->detach('/error_404') if !$c->stash->{object};
602 die "Book $id not found!" if !$c->stash->{object};
603
604 # Print a message to the debug log
605 $c->log->debug("*** INSIDE OBJECT METHOD for obj id=$id ***");
606 }
607
608 Now, any other method that chains off "object" will automatically have
609 the appropriate book waiting for it in "$c->stash->{object}".
610
611 Add a Delete Action to the Controller
612 Open "lib/MyApp/Controller/Books.pm" in your editor and add the
613 following method:
614
615 =head2 delete
616
617 Delete a book
618
619 =cut
620
621 sub delete :Chained('object') :PathPart('delete') :Args(0) {
622 my ($self, $c) = @_;
623
624 # Use the book object saved by 'object' and delete it along
625 # with related 'book_author' entries
626 $c->stash->{object}->delete;
627
628 # Set a status message to be displayed at the top of the view
629 $c->stash->{status_msg} = "Book deleted.";
630
631 # Forward to the list action/method in this controller
632 $c->forward('list');
633 }
634
635 This method first deletes the book object saved by the "object" method.
636 However, it also removes the corresponding entry from the "book_author"
637 table with a cascading delete.
638
639 Then, rather than forwarding to a "delete done" page as we did with the
640 earlier create example, it simply sets the "status_msg" to display a
641 notification to the user as the normal list view is rendered.
642
643 The "delete" action uses the context "forward" method to return the
644 user to the book list. The "detach" method could have also been used.
645 Whereas "forward" returns to the original action once it is completed,
646 "detach" does not return. Other than that, the two are equivalent.
647
648 Try the Delete Feature
649 One you save the Books controller, the server should automatically
650 restart. The "delete" method should now appear in the "Loaded Chained
651 actions" section of the startup debug output:
652
653 [debug] Loaded Chained actions:
654 .-------------------------------------+--------------------------------------.
655 | Path Spec | Private |
656 +-------------------------------------+--------------------------------------+
657 | /books/id/*/delete | /books/base (0) |
658 | | -> /books/object (1) |
659 | | => /books/delete |
660 | /books/form_create | /books/base (0) |
661 | | => /books/form_create |
662 | /books/form_create_do | /books/base (0) |
663 | | => /books/form_create_do |
664 | /books/url_create/*/*/* | /books/base (0) |
665 | | => /books/url_create |
666 '-------------------------------------+--------------------------------------'
667
668 Then point your browser to <http://localhost:3000/books/list> and click
669 the "Delete" link next to the first "TCPIP_Illustrated_Vol-2". A green
670 "Book deleted" status message should display at the top of the page,
671 along with a list of the eight remaining books. You will also see the
672 cascading delete operation via the DBIC_TRACE output:
673
674 SELECT me.id, me.title, me.rating FROM book me WHERE ( ( me.id = ? ) ): '6'
675 DELETE FROM book WHERE ( id = ? ): '6'
676 SELECT me.book_id, me.author_id FROM book_author me WHERE ( me.book_id = ? ): '6'
677 DELETE FROM book_author WHERE ( author_id = ? AND book_id = ? ): '4', '6'
678
679 Fixing a Dangerous URL
680 Note the URL in your browser once you have performed the deletion in
681 the prior step -- it is still referencing the delete action:
682
683 http://localhost:3000/books/id/6/delete
684
685 What if the user were to press reload with this URL still active? In
686 this case the redundant delete is harmless (although it does generate
687 an exception screen, it doesn't perform any undesirable actions on the
688 application or database), but in other cases this could clearly be
689 extremely dangerous.
690
691 We can improve the logic by converting to a redirect. Unlike
692 "$c->forward('list'))" or "$c->detach('list'))" that perform a server-
693 side alteration in the flow of processing, a redirect is a client-side
694 mechanism that causes the browser to issue an entirely new request. As
695 a result, the URL in the browser is updated to match the destination of
696 the redirection URL.
697
698 To convert the forward used in the previous section to a redirect, open
699 "lib/MyApp/Controller/Books.pm" and edit the existing "sub delete"
700 method to match:
701
702 =head2 delete
703
704 Delete a book
705
706 =cut
707
708 sub delete :Chained('object') :PathPart('delete') :Args(0) {
709 my ($self, $c) = @_;
710
711 # Use the book object saved by 'object' and delete it along
712 # with related 'book_author' entries
713 $c->stash->{object}->delete;
714
715 # Set a status message to be displayed at the top of the view
716 $c->stash->{status_msg} = "Book deleted.";
717
718 # Redirect the user back to the list page. Note the use
719 # of $self->action_for as earlier in this section (BasicCRUD)
720 $c->response->redirect($c->uri_for($self->action_for('list')));
721 }
722
723 Try the Delete and Redirect Logic
724 Point your browser to <http://localhost:3000/books/list> (don't just
725 hit "Refresh" in your browser since we left the URL in an invalid state
726 in the previous section!) and delete the first copy of the remaining
727 two "TCPIP_Illustrated_Vol-2" books. The URL in your browser should
728 return to the <http://localhost:3000/books/list> URL, so that is an
729 improvement, but notice that no green "Book deleted" status message is
730 displayed. Because the stash is reset on every request (and a redirect
731 involves a second request), the "status_msg" is cleared before it can
732 be displayed.
733
734 Using 'uri_for' to Pass Query Parameters
735 There are several ways to pass information across a redirect. One
736 option is to use the "flash" technique that we will see in Chapter 5 of
737 this tutorial; however, here we will pass the information via query
738 parameters on the redirect itself. Open
739 "lib/MyApp/Controller/Books.pm" and update the existing "sub delete"
740 method to match the following:
741
742 =head2 delete
743
744 Delete a book
745
746 =cut
747
748 sub delete :Chained('object') :PathPart('delete') :Args(0) {
749 my ($self, $c) = @_;
750
751 # Use the book object saved by 'object' and delete it along
752 # with related 'book_author' entries
753 $c->stash->{object}->delete;
754
755 # Redirect the user back to the list page with status msg as an arg
756 $c->response->redirect($c->uri_for($self->action_for('list'),
757 {status_msg => "Book deleted."}));
758 }
759
760 This modification simply leverages the ability of "uri_for" to include
761 an arbitrary number of name/value pairs in a hash reference. Next, we
762 need to update "root/src/wrapper.tt2" to handle "status_msg" as a query
763 parameter:
764
765 ...
766 <div id="content">
767 [%# Status and error messages %]
768 <span class="message">[% status_msg || c.request.params.status_msg %]</span>
769 <span class="error">[% error_msg %]</span>
770 [%# This is where TT will stick all of your template's contents. -%]
771 [% content %]
772 </div><!-- end content -->
773 ...
774
775 Although the sample above only shows the "content" div, leave the rest
776 of the file intact -- the only change we made to the "wrapper.tt2" was
777 to add ""|| c.request.params.status_msg"" to the "<span
778 class="message">" line.
779
780 Try the Delete and Redirect With Query Param Logic
781 Point your browser to <http://localhost:3000/books/list> (you should
782 now be able to safely hit "refresh" in your browser). Then delete the
783 remaining copy of "TCPIP_Illustrated_Vol-2". The green "Book deleted"
784 status message should return. But notice that you can now hit the
785 "Reload" button in your browser and it just redisplays the book list
786 (and it correctly shows it without the "Book deleted" message on
787 redisplay).
788
789 NOTE: Another popular method for maintaining server-side information
790 across a redirect is to use the "flash" technique we discuss in the
791 next chapter of the tutorial, Authentication. While "flash" is a
792 "slicker" mechanism in that it's all handled by the server and doesn't
793 "pollute" your URLs, it is important to note that "flash" can lead to
794 situations where the wrong information shows up in the wrong browser
795 window if the user has multiple windows or browser tabs open. For
796 example, Window A causes something to be placed in the stash, but
797 before that window performs a redirect, Window B makes a request to the
798 server and gets the status information that should really go to Window
799 A. For this reason, you may wish to use the "query param" technique
800 shown here in your applications.
801
803 In this section we will explore some additional capabilities offered by
804 DBIx::Class. Although these features have relatively little to do with
805 Catalyst per se, you will almost certainly want to take advantage of
806 them in your applications.
807
808 Add Datetime Columns to Our Existing Books Table
809 Let's add two columns to our existing "books" table to track when each
810 book was added and when each book is updated:
811
812 $ sqlite3 myapp.db
813 sqlite> ALTER TABLE book ADD created INTEGER;
814 sqlite> ALTER TABLE book ADD updated INTEGER;
815 sqlite> UPDATE book SET created = DATETIME('NOW'), updated = DATETIME('NOW');
816 sqlite> SELECT * FROM book;
817 1|CCSP SNRS Exam Certification Guide|5|2010-02-16 04:15:45|2010-02-16 04:15:45
818 2|TCP/IP Illustrated, Volume 1|5|2010-02-16 04:15:45|2010-02-16 04:15:45
819 3|Internetworking with TCP/IP Vol.1|4|2010-02-16 04:15:45|2010-02-16 04:15:45
820 4|Perl Cookbook|5|2010-02-16 04:15:45|2010-02-16 04:15:45
821 5|Designing with Web Standards|5|2010-02-16 04:15:45|2010-02-16 04:15:45
822 9|TCP/IP Illustrated, Vol 3|5|2010-02-16 04:15:45|2010-02-16 04:15:45
823 sqlite> .quit
824 $
825
826 This will modify the "books" table to include the two new fields and
827 populate those fields with the current time.
828
829 Update DBIx::Class to Automatically Handle the Datetime Columns
830 Next, we should re-run the DBIC helper to update the Result Classes
831 with the new fields:
832
833 $ script/myapp_create.pl model DB DBIC::Schema MyApp::Schema \
834 create=static components=TimeStamp dbi:SQLite:myapp.db \
835 on_connect_do="PRAGMA foreign_keys = ON"
836 exists "/root/dev/MyApp/script/../lib/MyApp/Model"
837 exists "/root/dev/MyApp/script/../t"
838 Dumping manual schema for MyApp::Schema to directory /root/dev/MyApp/script/../lib ...
839 Schema dump completed.
840 exists "/root/dev/MyApp/script/../lib/MyApp/Model/DB.pm"
841
842 Notice that we modified our use of the helper slightly: we told it to
843 include the DBIx::Class::TimeStamp in the "load_components" line of the
844 Result Classes.
845
846 If you open "lib/MyApp/Schema/Result/Book.pm" in your editor you should
847 see that the "created" and "updated" fields are now included in the
848 call to "add_columns()". However, also notice that the "many_to_many"
849 relationships we manually added below the ""# DO NOT MODIFY..."" line
850 were automatically preserved.
851
852 While we have this file open, let's update it with some additional
853 information to have DBIC automatically handle the updating of these two
854 fields for us. Insert the following code at the bottom of the file (it
855 must be below the ""# DO NOT MODIFY..."" line and above the "1;" on the
856 last line):
857
858 #
859 # Enable automatic date handling
860 #
861 __PACKAGE__->add_columns(
862 "created",
863 { data_type => 'datetime', set_on_create => 1 },
864 "updated",
865 { data_type => 'datetime', set_on_create => 1, set_on_update => 1 },
866 );
867
868 This will override the definition for these fields that Schema::Loader
869 placed at the top of the file. The "set_on_create" and "set_on_update"
870 options will cause DBIx::Class to automatically update the timestamps
871 in these columns whenever a row is created or modified.
872
873 Then enter the following URL into your web browser:
874
875 http://localhost:3000/books/url_create/TCPIP_Illustrated_Vol-2/5/4
876
877 You should get the same "Book Created" screen we saw above. However,
878 if you now use the sqlite3 command-line tool to dump the "books" table,
879 you will see that the new book we added has an appropriate date and
880 time entered for it (see the last line in the listing below):
881
882 $ sqlite3 myapp.db "select * from book"
883 1|CCSP SNRS Exam Certification Guide|5|2010-02-16 04:15:45|2010-02-16 04:15:45
884 2|TCP/IP Illustrated, Volume 1|5|2010-02-16 04:15:45|2010-02-16 04:15:45
885 3|Internetworking with TCP/IP Vol.1|4|2010-02-16 04:15:45|2010-02-16 04:15:45
886 4|Perl Cookbook|5|2010-02-16 04:15:45|2010-02-16 04:15:45
887 5|Designing with Web Standards|5|2010-02-16 04:15:45|2010-02-16 04:15:45
888 9|TCP/IP Illustrated, Vol 3|5|2010-02-16 04:15:45|2010-02-16 04:15:45
889 10|TCPIP_Illustrated_Vol-2|5|2010-02-16 04:18:42|2010-02-16 04:18:42
890 sqlite> .q
891
892 Notice in the debug log that the SQL DBIC generated has changed to
893 incorporate the datetime logic:
894
895 INSERT INTO book ( created, rating, title, updated ) VALUES ( ?, ?, ?, ? ):
896 '2010-02-16 04:18:42', '5', 'TCPIP_Illustrated_Vol-2', '2010-02-16 04:18:42'
897 INSERT INTO book_author ( author_id, book_id ) VALUES ( ?, ? ): '4', '10'
898
899 Create a ResultSet Class
900 An often overlooked but extremely powerful features of DBIC is that it
901 allows you to supply your own subclasses of "DBIx::Class::ResultSet".
902 It allows you to pull complex and unsightly "query code" out of your
903 controllers and encapsulate it in a method of your ResultSet Class.
904 These "canned queries" in your ResultSet Class can then be invoked via
905 a single call, resulting in much cleaner and easier to read controller
906 code.
907
908 To illustrate the concept with a fairly simple example, let's create a
909 method that returns books added in the last 10 minutes. Start by
910 making a directory where DBIx::Class will look for our ResultSet Class:
911
912 $ mkdir lib/MyApp/Schema/ResultSet
913
914 Then open "lib/MyApp/Schema/ResultSet/Book.pm" and enter the following:
915
916 package MyApp::Schema::ResultSet::Book;
917
918 use strict;
919 use warnings;
920 use base 'DBIx::Class::ResultSet';
921
922 =head2 created_after
923
924 A predefined search for recently added books
925
926 =cut
927
928 sub created_after {
929 my ($self, $datetime) = @_;
930
931 my $date_str = $self->result_source->schema->storage
932 ->datetime_parser->format_datetime($datetime);
933
934 return $self->search({
935 created => { '>' => $date_str }
936 });
937 }
938
939 1;
940
941 Then add the following method to the "lib/MyApp/Controller/Books.pm":
942
943 =head2 list_recent
944
945 List recently created books
946
947 =cut
948
949 sub list_recent :Chained('base') :PathPart('list_recent') :Args(1) {
950 my ($self, $c, $mins) = @_;
951
952 # Retrieve all of the book records as book model objects and store in the
953 # stash where they can be accessed by the TT template, but only
954 # retrieve books created within the last $min number of minutes
955 $c->stash(books => [$c->model('DB::Book')
956 ->created_after(DateTime->now->subtract(minutes => $mins))]);
957
958 # Set the TT template to use. You will almost always want to do this
959 # in your action methods (action methods respond to user input in
960 # your controllers).
961 $c->stash(template => 'books/list.tt2');
962 }
963
964 Now try different values for the "minutes" argument (the final number
965 value) using the URL "http://localhost:3000/books/list_recent/_#_" in
966 your browser. For example, this would list all books added in the last
967 fifteen minutes:
968
969 http://localhost:3000/books/list_recent/15
970
971 Depending on how recently you added books, you might want to try a
972 higher or lower value for the minutes.
973
974 Chaining ResultSets
975 One of the most helpful and powerful features in DBIx::Class is that it
976 allows you to "chain together" a series of queries (note that this has
977 nothing to do with the "Chained Dispatch" for Catalyst that we were
978 discussing above). Because each ResultSet returns another ResultSet,
979 you can take an initial query and immediately feed that into a second
980 query (and so on for as many queries you need). Note that no matter how
981 many ResultSets you chain together, the database itself will not be hit
982 until you use a method that attempts to access the data. And, because
983 this technique carries over to the ResultSet Class feature we
984 implemented in the previous section for our "canned search", we can
985 combine the two capabilities. For example, let's add an action to our
986 "Books" controller that lists books that are both recent and have "TCP"
987 in the title. Open up "lib/MyApp/Controller/Books.pm" and add the
988 following method:
989
990 =head2 list_recent_tcp
991
992 List recently created books
993
994 =cut
995
996 sub list_recent_tcp :Chained('base') :PathPart('list_recent_tcp') :Args(1) {
997 my ($self, $c, $mins) = @_;
998
999 # Retrieve all of the book records as book model objects and store in the
1000 # stash where they can be accessed by the TT template, but only
1001 # retrieve books created within the last $min number of minutes
1002 # AND that have 'TCP' in the title
1003 $c->stash(books => [$c->model('DB::Book')
1004 ->created_after(DateTime->now->subtract(minutes => $mins))
1005 ->search({title => {'like', '%TCP%'}})
1006 ]);
1007
1008 # Set the TT template to use. You will almost always want to do this
1009 # in your action methods (action methods respond to user input in
1010 # your controllers).
1011 $c->stash(template => 'books/list.tt2');
1012 }
1013
1014 To try this out, enter the following URL into your browser:
1015
1016 http://localhost:3000/books/list_recent_tcp/100
1017
1018 And you should get a list of books added in the last 100 minutes that
1019 contain the string "TCP" in the title. However, if you look at all
1020 books within the last 100 minutes, you should get a longer list (again,
1021 you might have to adjust the number of minutes depending on how
1022 recently you added books to your database):
1023
1024 http://localhost:3000/books/list_recent/100
1025
1026 Take a look at the DBIC_TRACE output in the development server log for
1027 the first URL and you should see something similar to the following:
1028
1029 SELECT me.id, me.title, me.rating, me.created, me.updated FROM book me
1030 WHERE ( ( title LIKE ? AND created > ? ) ): '%TCP%', '2010-02-16 02:49:32'
1031
1032 However, let's not pollute our controller code with this raw "TCP"
1033 query -- it would be cleaner to encapsulate that code in a method on
1034 our ResultSet Class. To do this, open
1035 "lib/MyApp/Schema/ResultSet/Book.pm" and add the following method:
1036
1037 =head2 title_like
1038
1039 A predefined search for books with a 'LIKE' search in the string
1040
1041 =cut
1042
1043 sub title_like {
1044 my ($self, $title_str) = @_;
1045
1046 return $self->search({
1047 title => { 'like' => "%$title_str%" }
1048 });
1049 }
1050
1051 We defined the search string as $title_str to make the method more
1052 flexible. Now update the "list_recent_tcp" method in
1053 "lib/MyApp/Controller/Books.pm" to match the following (we have
1054 replaced the "->search" line with the "->title_like" line shown here --
1055 the rest of the method should be the same):
1056
1057 =head2 list_recent_tcp
1058
1059 List recently created books
1060
1061 =cut
1062
1063 sub list_recent_tcp :Chained('base') :PathPart('list_recent_tcp') :Args(1) {
1064 my ($self, $c, $mins) = @_;
1065
1066 # Retrieve all of the book records as book model objects and store in the
1067 # stash where they can be accessed by the TT template, but only
1068 # retrieve books created within the last $min number of minutes
1069 # AND that have 'TCP' in the title
1070 $c->stash(books => [$c->model('DB::Book')
1071 ->created_after(DateTime->now->subtract(minutes => $mins))
1072 ->title_like('TCP')
1073 ]);
1074
1075 # Set the TT template to use. You will almost always want to do this
1076 # in your action methods (action methods respond to user input in
1077 # your controllers).
1078 $c->stash(template => 'books/list.tt2');
1079 }
1080
1081 Try out the "list_recent_tcp" and "list_recent" URLs as we did above.
1082 They should work just the same, but our code is obviously cleaner and
1083 more modular, while also being more flexible at the same time.
1084
1085 Adding Methods to Result Classes
1086 In the previous two sections we saw a good example of how we could use
1087 DBIx::Class ResultSet Classes to clean up our code for an entire query
1088 (for example, our "canned searches" that filtered the entire query).
1089 We can do a similar improvement when working with individual rows as
1090 well. Whereas the ResultSet construct is used in DBIC to correspond to
1091 an entire query, the Result Class construct is used to represent a row.
1092 Therefore, we can add row-specific "helper methods" to our Result
1093 Classes stored in "lib/MyApp/Schema/Result/". For example, open
1094 "lib/MyApp/Schema/Result/Author.pm" and add the following method (as
1095 always, it must be above the closing ""1;""):
1096
1097 #
1098 # Row-level helper methods
1099 #
1100 sub full_name {
1101 my ($self) = @_;
1102
1103 return $self->first_name . ' ' . $self->last_name;
1104 }
1105
1106 This will allow us to conveniently retrieve both the first and last
1107 name for an author in one shot. Now open "root/src/books/list.tt2" and
1108 change the definition of "tt_authors" from this:
1109
1110 ...
1111 [% tt_authors = [ ];
1112 tt_authors.push(author.last_name) FOREACH author = book.authors %]
1113 ...
1114
1115 to:
1116
1117 ...
1118 [% tt_authors = [ ];
1119 tt_authors.push(author.full_name) FOREACH author = book.authors %]
1120 ...
1121
1122 (Only "author.last_name" was changed to "author.full_name" -- the rest
1123 of the file should remain the same.)
1124
1125 Now go to the standard book list URL:
1126
1127 http://localhost:3000/books/list
1128
1129 The "Author(s)" column will now contain both the first and last name.
1130 And, because the concatenation logic was encapsulated inside our Result
1131 Class, it keeps the code inside our TT template nice and clean
1132 (remember, we want the templates to be as close to pure HTML markup as
1133 possible). Obviously, this capability becomes even more useful as you
1134 use to to remove even more complicated row-specific logic from your
1135 templates!
1136
1137 Moving Complicated View Code to the Model
1138 The previous section illustrated how we could use a Result Class method
1139 to print the full names of the authors without adding any extra code to
1140 our view, but it still left us with a fairly ugly mess (see
1141 "root/src/books/list.tt2"):
1142
1143 ...
1144 <td>
1145 [% # NOTE: See Chapter 4 for a better way to do this! -%]
1146 [% # First initialize a TT variable to hold a list. Then use a TT FOREACH -%]
1147 [% # loop in 'side effect notation' to load just the last names of the -%]
1148 [% # authors into the list. Note that the 'push' TT vmethod does not print -%]
1149 [% # a value, so nothing will be printed here. But, if you have something -%]
1150 [% # in TT that does return a method and you don't want it printed, you -%]
1151 [% # can: 1) assign it to a bogus value, or 2) use the CALL keyword to -%]
1152 [% # call it and discard the return value. -%]
1153 [% tt_authors = [ ];
1154 tt_authors.push(author.full_name) FOREACH author = book.authors %]
1155 [% # Now use a TT 'virtual method' to display the author count in parens -%]
1156 [% # Note the use of the TT filter "| html" to escape dangerous characters -%]
1157 ([% tt_authors.size | html %])
1158 [% # Use another TT vmethod to join & print the names & comma separators -%]
1159 [% tt_authors.join(', ') | html %]
1160 </td>
1161 ...
1162
1163 Let's combine some of the techniques used earlier in this section to
1164 clean this up. First, let's add a method to our Book Result Class to
1165 return the number of authors for a book. Open
1166 "lib/MyApp/Schema/Result/Book.pm" and add the following method:
1167
1168 =head2 author_count
1169
1170 Return the number of authors for the current book
1171
1172 =cut
1173
1174 sub author_count {
1175 my ($self) = @_;
1176
1177 # Use the 'many_to_many' relationship to fetch all of the authors for the current
1178 # and the 'count' method in DBIx::Class::ResultSet to get a SQL COUNT
1179 return $self->authors->count;
1180 }
1181
1182 Next, let's add a method to return a list of authors for a book to the
1183 same "lib/MyApp/Schema/Result/Book.pm" file:
1184
1185 =head2 author_list
1186
1187 Return a comma-separated list of authors for the current book
1188
1189 =cut
1190
1191 sub author_list {
1192 my ($self) = @_;
1193
1194 # Loop through all authors for the current book, calling all the 'full_name'
1195 # Result Class method for each
1196 my @names;
1197 foreach my $author ($self->authors) {
1198 push(@names, $author->full_name);
1199 }
1200
1201 return join(', ', @names);
1202 }
1203
1204 This method loops through each author, using the "full_name" Result
1205 Class method we added to "lib/MyApp/Schema/Result/Author.pm" in the
1206 prior section.
1207
1208 Using these two methods, we can simplify our TT code. Open
1209 "root/src/books/list.tt2" and update the "Author(s)" table cell to
1210 match the following:
1211
1212 ...
1213 <td>
1214 [% # Print count and author list using Result Class methods -%]
1215 ([% book.author_count | html %]) [% book.author_list | html %]
1216 </td>
1217 ...
1218
1219 Although most of the code we removed comprised comments, the overall
1220 effect is dramatic... because our view code is so simple, we don't need
1221 huge comments to clue people in to the gist of our code. The view code
1222 is now self-documenting and readable enough that you could probably get
1223 by with no comments at all. All of the "complex" work is being done in
1224 our Result Class methods (and, because we have broken the code into
1225 nice, modular chucks, the Result Class code is hardly something you
1226 would call complex).
1227
1228 As we saw in this section, always strive to keep your view AND
1229 controller code as simple as possible by pulling code out into your
1230 model objects. Because DBIx::Class can be easily extended in so many
1231 ways, it's an excellent to way accomplish this objective. It will make
1232 your code cleaner, easier to write, less error-prone, and easier to
1233 debug and maintain.
1234
1235 Before you conclude this section, hit Refresh in your browser... the
1236 output should be the same even though the backend code has been trimmed
1237 down.
1238
1240 Kennedy Clark, "hkclark@gmail.com"
1241
1242 Please report any errors, issues or suggestions to the author. The
1243 most recent version of the Catalyst Tutorial can be found at
1244 http://dev.catalyst.perl.org/repos/Catalyst/Catalyst-Manual/5.80/trunk/lib/Catalyst/Manual/Tutorial/
1245 <http://dev.catalyst.perl.org/repos/Catalyst/Catalyst-
1246 Manual/5.80/trunk/lib/Catalyst/Manual/Tutorial/>.
1247
1248 Copyright 2006-2008, Kennedy Clark, under Creative Commons License
1249 (http://creativecommons.org/licenses/by-sa/3.0/us/
1250 <http://creativecommons.org/licenses/by-sa/3.0/us/>).
1251
1252
1253
1254perl v5.12.0 20C1a0t-a0l2y-s1t7::Manual::Tutorial::04_BasicCRUD(3)