Catalys...stBasics(3)
π NAME π
okay so this is Catalys...stBasics(3), from the User Contributed Perl Documentation corner of the manual-verse, and it's the page for Catalyst::Manual::Tutorial::03_MoreCatalystBasics β aka Catalyst Tutorial - Chapter 3: More Catalyst Application Development Basics. Long name, iconic energy, we move.
β¨ OVERVIEW β¨
This is Chapter 3 of 10 for the Catalyst tutorial. Bestie, we're literally in the middle of a saga.
π Tutorial Overview π
- Introduction
- Catalyst Basics
- 03_More Catalyst Basics
- Basic CRUD
- Authentication
- Authorization
- Debugging
- Testing
- Advanced CRUD
- Appendices
π¦ DESCRIPTION π¦
This chapter builds on the work from Chapter 2 and explores features that are more typical of "real world" web applications. From here onward, we're building a simple book database application. Is it going to be useful to anyone? No, lowkey too limited for that. But it gives us a basic environment to explore a bunch of features used in virtually all web applications. Slay.
Source code for the tutorial is included in the /home/catalyst/Final directory of the Tutorial Virtual Machine (one subdirectory per chapter). There are also instructions for downloading the code in Catalyst::Manual::Tutorial::01_Intro.
π«Ά Please take a look at "STARTING WITH THE TUTORIAL VIRTUAL MACHINE" in Catalyst::Manual::Tutorial::01_Intro before doing the rest of this tutorial. The tutorial should work correctly under most any recent version of Perl running on any operating system, but it was written using the virtual machine that's available for download. The entire tutorial has been tested to make sure it runs correctly in this environment, so it's the most trouble-free way to get started with Catalyst. No cap.
π CREATE A NEW APPLICATION π
The remainder of the tutorial will build an application called MyApp. First, use the Catalyst catalyst.pl script to initialize the framework for the MyApp application. Make sure you aren't still inside the directory of the Hello application from the previous chapter, or in a directory that already has a MyApp subdirectory. We're not doing chaos energy today.
$ catalyst.pl MyApp
created "MyApp"
created "MyApp/script"
created "MyApp/lib"
created "MyApp/root"
...
created "MyApp/script/myapp_create.pl"
Change to application directory and Run "perl Makefile.PL" to make sure your install is complete
And change into the MyApp directory the helper created:
$ cd MyApp
This creates a similar skeletal structure to what we saw in Chapter 2 of the tutorial, except with MyApp and myapp substituted for Hello and hello. (As noted in Chapter 2, omit the .pl from the command if you are using Strawberry Perl.)
π EDIT THE LIST OF CATALYST PLUGINS π
One of the greatest benefits of Catalyst is that it has such a large library of base classes and plugins available that you can use to easily add functionality to your application. Plugins are used to seamlessly integrate existing Perl modules into the overall Catalyst framework. In general, they do this by adding additional methods to the context object (generally written as $c) that Catalyst passes to every component throughout the framework.
Take a look at the file lib/MyApp.pm that the helper created above. By default, Catalyst enables three plugins/flags:
-DebugFlag β Enables the Catalyst debug output you saw when we started thescript/myapp_server.pldevelopment server earlier. You can remove this item when you place your application into production.- To be technically correct, it turns out that
-Debugis not a plugin, but a flag. Although most of the items specified on theuse Catalystline of your application class will be plugins, Catalyst supports a limited number of flag options (of these,-Debugis the most common). See the documentation forCatalyst.pmto get details on other flags (currently-Engine,-Home,-Log, and-Stats). - If you prefer, there are several other ways to enable debug output:
- the
$c->debugmethod on the$cCatalyst context object - the
-doption on thescript/myapp_server.plscript - the
CATALYST_DEBUG=1environment variable (orCATALYST_DEBUG=0to temporarily disable debug output)
- the
- TIP: Depending on your needs, it can be helpful to permanently remove
-Debugfromlib/MyApp.pmand then use the-doption toscript/myapp_server.plto re-enable it when needed. We will not be using that approach in the tutorial, but feel free to make use of it in your own projects.
- To be technically correct, it turns out that
Catalyst::Plugin::ConfigLoaderβConfigLoaderprovides an automatic way to load configurable parameters for your application from a centralConfig::Generalfile (versus having the values hard-coded inside your Perl modules).Config::Generaluses syntax very similar to Apache configuration files. We will see how to use this feature of Catalyst during the authentication and authorization sections (Chapter 5 and Chapter 6).- IMPORTANT NOTE: If you are using a version of
Catalyst::Develprior to version1.06, be aware that Catalyst changed the default format from YAML to the more straightforwardConfig::Generalstyle. This tutorial uses the newermyapp.conffile forConfig::General. However, Catalyst supports both formats and will automatically use eithermyapp.conformyapp.yml(or any other format supported byCatalyst::Plugin::ConfigLoaderandConfig::Any). If you are using a version ofCatalyst::Develprior to1.06, you can convert to the newer format by simply creating themyapp.conffile manually and deletingmyapp.yml. The default contents of themyapp.confyou create should only consist of one line:
- IMPORTANT NOTE: If you are using a version of
name MyApp
- TIP: This script can be useful for converting between configuration formats:
perl -Ilib -e 'use MyApp; use Config::General;
Config::General->new->save_file("myapp.conf", MyApp->config);'
Catalyst::Plugin::Static::SimpleβStatic::Simpleprovides an easy way to serve static content, such as images and CSS files, from the development server.
For our application, we want to add one new plugin to the mix. To do this, edit lib/MyApp.pm (this file is generally referred to as your application class) and delete the lines with:
use Catalyst qw/
-Debug
ConfigLoader
Static::Simple
/;
Then replace it with:
# Load plugins
use Catalyst qw/
-Debug
ConfigLoader
Static::Simple
StackTrace
/;
Note: Recent versions of Catalyst::Devel have used a variety of techniques to load these plugins/flags. For example, you might see the following:
__PACKAGE__->setup(qw/-Debug ConfigLoader Static::Simple/);
Don't let these variations confuse you β they all accomplish the same result. It's giving "same fit, different accessories."
This tells Catalyst to start using one additional plugin, Catalyst::Plugin::StackTrace, to add a stack trace near the top of the standard Catalyst "debug screen" (the screen Catalyst sends to your browser when an error occurs). Be aware that StackTrace output appears in your browser, not in the console window from which you're running your application, which is where logging output usually goes.
Make sure when adding new plugins you also include them as a new dependency within the Makefile.PL file. For example, after adding the StackTrace plugin the Makefile.PL should include the following line:
requires 'Catalyst::Plugin::StackTrace';
Notes:
__PACKAGE__is just a shorthand way of referencing the name of the package where it is used. Therefore, inMyApp.pm,__PACKAGE__is equivalent toMyApp.- You will want to disable
StackTracebefore you put your application into production, but it can be helpful during development. - When specifying plugins, you can omit
Catalyst::Plugin::from the name. Additionally, you can spread the plugin names across multiple lines as shown here or place them all on one line. - If you want to see what the
StackTraceerror screen looks like, editlib/MyApp/Controller/Root.pmand put adie "Oops";command in thesub index :Path :Args(0)method. Then start the development server and openhttp://localhost:3000/in your browser. You should get a screen that starts withCaught exception in MyApp::Controller::Root->indexwith sections showing a stacktrace, information about the Request and Response objects, the stash (something we will learn about soon), and the applications configuration. Just don't forget to remove thediebefore you continue the tutorial! :-)
π CREATE A CATALYST CONTROLLER π
okay so remember how we said earlier that controllers are literally where you write the methods that talk to user input? yeah, that. typically your controller methods are the ones responding to GET and POST requests coming in from the user's web browser. π
So use the Catalyst create script to add a controller for book-related stuff, like this:
$ script/myapp_create.pl controller Books
exists "/home/catalyst/MyApp/script/../lib/MyApp/Controller"
exists "/home/catalyst/MyApp/script/../t"
created "/home/catalyst/MyApp/script/../lib/MyApp/Controller/Books.pm"
created "/home/catalyst/MyApp/script/../t/controller_Books.t"
Then go edit lib/MyApp/Controller/Books.pm β and just so you know (this was already discussed in Chapter 2 of the Tutorial), Catalyst keeps a separate directory under lib/MyApp for each of the three parts of MVC: Model, View and Controller β and add this method to the controller:
=head2 list
Fetch all book objects and pass to books/list.tt2 in stash to be displayed
=cut
sub list :Local {
# Retrieve the usual Perl OO '$self' for this object. $c is the Catalyst
# 'Context' that's used to 'glue together' the various components
# that make up the application
my ($self, $c) = @_;
# Retrieve all of the book records as book model objects and store in the
# stash where they can be accessed by the TT template
# $c->stash(books => [$c->model('DB::Book')->all]);
# But, for now, use this code until we create the model later
$c->stash(books => '');
# Set the TT template to use. You will almost always want to do this
# in your action methods (action methods respond to user input in
# your controllers).
$c->stash(template => 'books/list.tt2');
}
TIP: See Appendix 1 for tips on removing the leading spaces when cutting and pasting example code from POD-based documents. (real talk, those leading spaces will get you π)
So if you've done object-oriented Perl before, you should be looking at $self and going "yep, that's a reference to the object where this method was called." iconic. but $c is gonna be new to a lot of Perl programmers who haven't touched Catalyst before. This is the Catalyst Context object, and it gets automatically passed as the second argument to all Catalyst action methods. It's the one carrying info between components and handing you access to Catalyst and plugin functionality. main character energy tbh. β¨
Catalyst Controller actions are regular Perl methods, but they use attributes (that's the ":Local" sitting next to the "sub list" in the code above) to hand extra info over to the Catalyst dispatcher logic β and ngl, there can be an optional space between the colon and the attribute name, so you'll see attributes written both ways. Most Catalyst Controllers use one of five action types:
:Privateβ use:Privatefor methods you do want to make into an action, but you do not want Catalyst to directly expose to your users. Catalyst will not map:Privatemethods to a URI. Use them for all sorts of "special" methods (thebegin,auto, etc. discussed below) or for methods you want to be able toforwardordetachto. (And if the method is a "plain old method" that you don't want to be an action at all? then just define the method without any attribute β you can still call it in your code, but the Catalyst dispatcher will ignore it. Heads up though: you'll also have to manually include$cif you want access to the context object in the method, versus having Catalyst automatically include$cin the argument list for you if it's a full-fledged action.)
There are five types of "special" built-in :Private actions: begin, end, default, index, and auto.
- With
begin,end,default,indexprivate actions, only the most specific action of each type will be called. So for example, if you define abeginaction in your controller it will override abeginaction in your application/root controller β only the action in your controller will get called. π - Unlike the other actions where only a single method is called for each request, every auto action along the chain of namespaces will be called. Each
autoaction gets called from the application/root controller down through the most specific class.
:Pathβ:Pathactions let you map a method to an explicit URI path. So for example,:Path('list')inlib/MyApp/Controller/Books.pmwould match on the URLhttp://localhost:3000/books/list, but:Path('/list')would match onhttp://localhost:3000/list(because of that leading slash, sneaky). You can use:Args()to specify how many arguments an action should accept. See "Action-types" in Catalyst::Manual::Intro for more info and examples.:Localβ:Localis merely a shorthand for:Path('_name_of_method_'). For example, these are equivalent:"sub create_book :Local {...}"and"sub create_book :Path('create_book') {...}". slay, less typing π«Ά:Globalβ:Globalis merely a shorthand for:Path('/_name_of_method_'). For example, these are equivalent:"sub create_book :Global {...}"and"sub create_book :Path('/create_book') {...}".:Chainedβ newer Catalyst applications tend to use the Chained dispatch form of action types because of its power and flexibility. It lets a whole series of controller methods be automatically dispatched when servicing a single user request. See Catalyst::Manual::Tutorial::04_BasicCRUD and Catalyst::DispatchType::Chained for more info on chained actions. π₯
You should refer to "Action-types" in Catalyst::Manual::Intro for additional information, and for coverage of some of the lesser-used action types we didn't get into here (Regex and LocalRegex). iykyk π
π CATALYST VIEWS π
Okay so real talk, bestie: like Chapter 2 of the tutorial said, views are literally where you render output β usually for display in the user's web browser (but they can also generate other types of output such as PDF or JSON). The code in lib/MyApp/View selects the type of view to use, and the actual rendering template is found in the "root" directory. As with virtually every aspect of Catalyst, options abound when it comes to the specific view technology you adopt inside your application, periodt. However, most Catalyst applications use the Template Toolkit, known as TT (for more information on TT, see <http://www.template-toolkit.org>). Other somewhat popular view technologies include Mason (<http://www.masonhq.com> and <https://masonbook.houseabsolute.com/book/>) and HTML::Template. π¦
β¨ Create a Catalyst View β¨
When using TT for the Catalyst view, the main helper script is Catalyst::Helper::View::TT. You may also come across references to Catalyst::Helper::View::TTSite, but its use is now deprecated. π¨
Not me warning you again: Catalyst::Helper::View::TTSite is deprecated, so leave it in the past, bestie. π
For our book application, enter the following command to enable the "TT" style of view rendering:
$ script/myapp_create.pl view HTML TT
exists "/home/catalyst/MyApp/script/../lib/MyApp/View"
exists "/home/catalyst/MyApp/script/../t"
created "/home/catalyst/MyApp/script/../lib/MyApp/View/HTML.pm"
created "/home/catalyst/MyApp/script/../t/view_HTML.t"
This creates a view called "HTML" (the first argument) in a file called "HTML.pm" that uses Catalyst::View::TT (the second argument) as the "rendering engine". It's giving rendering engine realness β¨
Now it is up to you to decide how you want to structure your view layout. For the tutorial, we will start with a very simple TT template to initially demonstrate the concepts, but quickly migrate to a more typical "wrapper page" type of configuration (where the "wrapper" controls the overall "look and feel" of your site from a single file or set of files). Wrapper pages are iconic and we're obsessed, no cap.
Edit lib/MyApp/View/HTML.pm and you should see something similar to the following:
__PACKAGE__->config(
TEMPLATE_EXTENSION => '.tt',
render_die => 1,
);
And update it to match:
__PACKAGE__->config(
# Change default TT extension
TEMPLATE_EXTENSION => '.tt2',
render_die => 1,
);
This changes the default extension for Template Toolkit from '.tt' to '.tt2'.
You can also configure components in your application class. For example, edit lib/MyApp.pm and you should see the default configuration above the call to _PACKAGE__->setup (your defaults could be different depending on the version of Catalyst you are using):
__PACKAGE__->config(
name => 'MyApp',
# Disable deprecated behavior needed by old applications
disable_component_resolution_regex_fallback => 1,
);
Change this to match the following (insert a new __PACKAGE__->config below the existing statement):
__PACKAGE__->config(
name => 'MyApp',
# Disable deprecated behavior needed by old applications
disable_component_resolution_regex_fallback => 1,
);
__PACKAGE__->config(
# Configure the view
'View::HTML' => {
#Set the location for TT files
INCLUDE_PATH => [
__PACKAGE__->path_to( 'root', 'src' ),
],
},
);
This changes the base directory for your template files from "root" to root/src.
Please stick with the settings above for the duration of the tutorial, but feel free to use whatever options you desire in your applications (as with most things in Perl, there's more than one way to do it...). No cap, this part matters for the tutorial. π«Ά
π Note: We will useroot/srcas the base directory for our template files, with a full naming convention ofroot/src/_controller_name_/_action_name_.tt2. Another popular option is to useroot/as the base (with a full filename pattern ofroot/_controller_name_/_action_name_.tt2).
πΈ Create a TT Template Page πΈ
First create a directory for book-related TT templates:
$ mkdir -p root/src/books
Then create root/src/books/list.tt2 in your editor and enter:
[% # This is a TT comment. -%]
[%- # Provide a title -%]
[% META title = 'Book List' -%]
[% # Note That the '-' at the beginning or end of TT code -%]
[% # "chomps" the whitespace/newline at that end of the -%]
[% # output (use View Source in browser to see the effect) -%]
[% # Some basic HTML with a loop to display books -%]
<table>
<tr><th>Title</th><th>Rating</th><th>Author(s)</th></tr>
[% # Display each book in a table row %]
[% FOREACH book IN books -%]
<tr>
<td>[% book.title %]</td>
<td>[% book.rating %]</td>
<td></td>
</tr>
[% END -%]
</table>
As indicated by the inline comments above, the "META title" line uses TT's META feature to provide a title to the "wrapper" that we will create later (and essentially does nothing at the moment). Meanwhile, the "FOREACH" loop iterates through each "book" model object and prints the "title" and "rating" fields. That loop is lowkey the main character here π
The "[%" and "%]" tags are used to delimit Template Toolkit code. TT supports a wide variety of directives for "calling" other files, looping, conditional logic, etc. In general, TT simplifies the usual range of Perl operators down to the single dot (".") operator. This applies to operations as diverse as method calls, hash lookups, and list index values (see Template::Manual::Variables for details and examples). In addition to the usual Template::Toolkit module Pod documentation, you can access the TT manual at Template::Manual. TT ate that β slay π
π‘ TIP: While you can build all sorts of complex logic into your TT templates, you should in general keep the"code"part of your templates as simple as possible. If you need more complex logic, create helper methods in your model that abstract out a set of code into a single call from your TT template. (Note that the same is true of your controller logic as well -- complex sections of code in your controllers should often be pulled out and placed into your model objects.) In Chapter 4 of the tutorial we will explore some extremely helpful and powerful features ofDBIx::Classthat allow you to pull code out of your views and controllers and place it where it rightfully belongs in a model class.
π¦ Test Run The Application π¦
To test your work so far, first start the development server:
$ script/myapp_server.pl -r
Then point your browser to <http://localhost:3000> and you should still get the Catalyst welcome page. Next, change the URL in your browser to <http://localhost:3000/books/list>. If you have everything working so far, you should see a web page that displays nothing other than our column headers for "Title", "Rating", and "Author(s)" -- we will not see any books until we get the database and model working below. Vibe check: headers only, bestie π§
If you run into problems getting your application to run correctly, it might be helpful to refer to some of the debugging techniques covered in the Debugging chapter of the tutorial. You got this fr fr π
ποΈ CREATE A SQLITE DATABASE β¨
okay bestie, plot twist: we need somewhere to actually put our data π so in this step we're making a text file full of SQL commands that creates a database table and loads in some sample data. slay.
we're using SQLite (https://www.sqlite.org), which is that popular database that's lightweight and easy to use β literally the low-maintenance bestie of databases π«Ά. be sure to get at least version 3, no cap.
open myapp01.sql in your editor and type this in, exactly:
--
-- Create a very simple database to hold book and author information
--
PRAGMA foreign_keys = ON;
CREATE TABLE book (
id INTEGER PRIMARY KEY,
title TEXT ,
rating INTEGER
);
-- 'book_author' is a many-to-many join table between books & authors
CREATE TABLE book_author (
book_id INTEGER REFERENCES book(id) ON DELETE CASCADE ON UPDATE CASCADE,
author_id INTEGER REFERENCES author(id) ON DELETE CASCADE ON UPDATE CASCADE,
PRIMARY KEY (book_id, author_id)
);
CREATE TABLE author (
id INTEGER PRIMARY KEY,
first_name TEXT,
last_name TEXT
);
---
--- Load some sample data
---
INSERT INTO book VALUES (1, 'CCSP SNRS Exam Certification Guide', 5);
INSERT INTO book VALUES (2, 'TCP/IP Illustrated, Volume 1', 5);
INSERT INTO book VALUES (3, 'Internetworking with TCP/IP Vol.1', 4);
INSERT INTO book VALUES (4, 'Perl Cookbook', 5);
INSERT INTO book VALUES (5, 'Designing with Web Standards', 5);
INSERT INTO author VALUES (1, 'Greg', 'Bastien');
INSERT INTO author VALUES (2, 'Sara', 'Nasseh');
INSERT INTO author VALUES (3, 'Christian', 'Degu');
INSERT INTO author VALUES (4, 'Richard', 'Stevens');
INSERT INTO author VALUES (5, 'Douglas', 'Comer');
INSERT INTO author VALUES (6, 'Tom', 'Christiansen');
INSERT INTO author VALUES (7, 'Nathan', 'Torkington');
INSERT INTO author VALUES (8, 'Jeffrey', 'Zeldman');
INSERT INTO book_author VALUES (1, 1);
INSERT INTO book_author VALUES (1, 2);
INSERT INTO book_author VALUES (1, 3);
INSERT INTO book_author VALUES (2, 4);
INSERT INTO book_author VALUES (3, 5);
INSERT INTO book_author VALUES (4, 6);
INSERT INTO book_author VALUES (4, 7);
INSERT INTO book_author VALUES (5, 8);
then run this command to build a myapp.db SQLite database:
$ sqlite3 myapp.db < myapp01.sql
π real talk though: if you ever need to create the database more than once, you're gonna want to hit it with the rm myapp.db command first to delete the database before you run that sqlite3 myapp.db < myapp01.sql command again. clean slate energy π
once the myapp.db database file has been created and initialized, you can hop into the SQLite command line environment and do a quick dump of what's inside:
$ sqlite3 myapp.db
SQLite version 3.7.3
Enter ".help" for instructions
Enter SQL statements terminated with a ";"
sqlite> select * from book;
1|CCSP SNRS Exam Certification Guide|5
2|TCP/IP Illustrated, Volume 1|5
3|Internetworking with TCP/IP Vol.1|4
4|Perl Cookbook|5
5|Designing with Web Standards|5
sqlite> .q
$
or, if you're feeling efficient β¨:
$ sqlite3 myapp.db "select * from book"
1|CCSP SNRS Exam Certification Guide|5
2|TCP/IP Illustrated, Volume 1|5
3|Internetworking with TCP/IP Vol.1|4
4|Perl Cookbook|5
5|Designing with Web Standards|5
so, like with most other SQL tools β if you're using the full "interactive" environment, you gotta terminate your SQL commands with a ; π (it's not required if you do a single SQL statement on the command line, iykyk). and use .q to exit from SQLite in interactive mode and get back to your OS command prompt π¦.
okay important note bestie π: here we chose to use 'singular' table names. why? because the default inflection code for older versions of DBIx::Class::Schema::Loader does NOT handle plurals. periodt.
and ngl there's been much philosophical discussion on whether table names should be plural or singular π there is no one correct answer β as long as you make a choice and stay consistent with it, you're golden. but if you prefer plural table names (like, maybe you think they're easier to read), then go see the documentation in "naming" in DBIx::Class::Schema::Loader::Base (version 0.05 or greater) π
for using other databases, such as PostgreSQL or MySQL, see Appendix 2 πΈ
π¦ DATABASE ACCESS WITH DBIx::Class π¦
okay so bestie, here's the tea: Catalyst can vibe with basically any datastore you can reach through Perl. Like, genuinely anything. For example, Catalyst::Model::DBI can hit databases through the classic Perl DBI interface, or you can use a model to slurp up files of any type on the filesystem. No cap.
But β and this is the main character detail β most Catalyst apps use some form of object-relational mapping (ORM) technology to create objects associated with tables in a relational database, and Matt Trout's DBIx::Class (abbreviated as "DBIC") is the usual choice. This tutorial? We're using DBIx::Class. Periodt. π
So here's a thing you should know: DBIx::Class has included support for a create=dynamic mode that automatically reads the database structure every time the application starts β but its use is no longer recommended. I know, I know, it can make for "flashy" demos π but the create=static mode we use below can be implemented just as quickly and provides many advantages (such as the ability to add your own methods to the overall DBIC framework β a technique that we see in Chapter 4). lowkey iconic.
πΎ Create Static DBIx::Class Schema Files πΎ
Note: If you are not following along in the Tutorial Virtual Machine, please be sure that you have version 1.27 or higher ofDBD::SQLiteand version 0.39 or higher ofCatalyst::Model::DBIC::Schema. (The Tutorial VM already has versions that are known to work β she's prepped, she's ready. π«Ά)
You can get your currently installed version numbers with the following commands:
$ perl -MCatalyst::Model::DBIC::Schema\ 999
$ perl -MDBD::SQLite\ 999
Before you continue, make sure your myapp.db database file is in the application's topmost directory. Now use the model helper with the create=static option to read the database with DBIx::Class::Schema::Loader and automatically build the required files for us:
$ script/myapp_create.pl model DB DBIC::Schema MyApp::Schema \
create=static dbi:SQLite:myapp.db \
on_connect_do="PRAGMA foreign_keys = ON"
exists "/home/catalyst/MyApp/script/../lib/MyApp/Model"
exists "/home/catalyst/MyApp/script/../t"
Dumping manual schema for MyApp::Schema to directory /home/catalyst/MyApp/script/../lib ...
Schema dump completed.
created "/home/catalyst/MyApp/script/../lib/MyApp/Model/DB.pm"
created "/home/catalyst/MyApp/script/../t/model_DB.t"
Please note the \ above, bestie β don't ignore her. Depending on your environment, you might be able to cut and paste the text as shown, or need to remove the \ character so that the command is all on a single line.
The script/myapp_create.pl command breaks down like this:
DBis the name of the model class to be created by the helper in thelib/MyApp/Modeldirectory.DBIC::Schemais the type of the model to create. This equates toCatalyst::Model::DBIC::Schema, the standard way to use a DBIC-based model inside of Catalyst.MyApp::Schemais the name of the DBIC schema file written tolib/MyApp/Schema.pm.create=staticcausesDBIx::Class::Schema::Loaderto load the schema as it runs and then write that information out intolib/MyApp/Schema.pmand files under thelib/MyApp/Schemadirectory.dbi:SQLite:myapp.dbis the standard DBI connect string for use with SQLite.- And finally, the
on_connect_dostring requests thatDBIx::Class::Schema::Loadercreate foreign key relationships for us (this is not needed for databases such as PostgreSQL and MySQL, but is required for SQLite). If you take a look atlib/MyApp/Model/DB.pm, you will see that the SQLite pragma is propagated to the Model, so that SQLite's recent (and optional) foreign key enforcement is enabled at the start of every database connection. slay. π₯
If you look in the lib/MyApp/Schema.pm file, you will find that it only contains a call to the load_namespaces method. You will also find that lib/MyApp contains a Schema subdirectory, which then has a subdirectory called Result. This Result subdirectory then has files named according to each of the tables in our simple database (Author.pm, BookAuthor.pm, and Book.pm). These three files are called "Result Classes" (or "ResultSource Classes") in DBIx::Class nomenclature. ngl, the naming is giving very much "the classes correspond to the row-level data that is returned by DBIC" β and you'll get more on this later, especially in "EXPLORING THE POWER OF DBIC" in Catalyst::Manual::Tutorial::04_BasicCRUD. π
The idea with the Result Source files created under lib/MyApp/Schema/Result by the create=static option is to only edit the files below the # DO NOT MODIFY THIS OR ANYTHING ABOVE! warning. If you place all of your changes below that point in the file, you can regenerate the automatically created information at the top of each file should your database structure get updated. that's the whole strategy bestie, respect the line π
Also note the "flow" of the model information across the various files and directories. Catalyst will initially load the model from lib/MyApp/Model/DB.pm. This file contains a reference to lib/MyApp/Schema.pm, so that file is loaded next. Finally, the call to load_namespaces in Schema.pm will load each of the "Result Class" files from the lib/MyApp/Schema/Result subdirectory. The final outcome is that Catalyst will dynamically create three table-specific Catalyst models every time the application starts (you can see these three model files listed in the debug output generated when you launch the application). it's giving choreography. absolutely ate. β¨
Additionally, the lib/MyApp/Schema.pm model can easily be loaded outside of Catalyst β for example, in command-line utilities and/or cron jobs. lib/MyApp/Model/DB.pm provides a very thin "bridge" between Catalyst and this external database model. Once you see how we can add some powerful features to our DBIC model in Chapter 4, the elegance of this approach will start to become more obvious. π¦
NOTE: Older versions ofCatalyst::Model::DBIC::Schemause the deprecatedDBIx::Classload_classestechnique instead of the newerload_namespaces. For new applications, please try to useload_namespacessince it more easily supports a very useful DBIC technique called "ResultSet Classes." If you need to convert an existing application fromload_classestoload_namespaces, you can use this process to automate the migration, but first make sure you have version 0.39 ofCatalyst::Model::DBIC::SchemaandDBIx::Class::Schema::Loaderversion 0.05000 or later. fr fr, check ya versions first. π
$ # Re-run the helper to upgrade for you
$ script/myapp_create.pl model DB DBIC::Schema MyApp::Schema \
create=static naming=current use_namespaces=1 \
dbi:SQLite:myapp.db \
on_connect_do="PRAGMA foreign_keys = ON"
and that's the whole upgrade glow-up β but hold up, we're not done yet, because next we're gonna talk about what all this actually does for you when you start poking at the dataβ¦ π§
ENABLE THE MODEL IN THE CONTROLLER</p> π
okay bestie, so open up lib/MyApp/Controller/Books.pm and un-comment the model code we left sitting there all sad and disabled earlier β make your version match this exactly (that means un-comment the line containing [$c->model('DB::Book')->all] and delete the next 2 lines):
=head2 list
Fetch all book objects and pass to books/list.tt2 in stash to be displayed
=cut
sub list :Local {
# Retrieve the usual Perl OO '$self' for this object. $c is the Catalyst
# 'Context' that's used to 'glue together' the various components
# that make up the application
my ($self, $c) = @_;
# Retrieve all of the book records as book model objects and store
# in the stash where they can be accessed by the TT template
$c->stash(books => [$c->model('DB::Book')->all]);
# Set the TT template to use. You will almost always want to do this
# in your action methods (action methods respond to user input in
# your controllers).
$c->stash(template => 'books/list.tt2');
}
TIP: you might see the$c->model('DB::Book')up there un-commented and written as$c->model('DB')->resultset('Book'). bestie, they're literally the same thing, no cap. either way,$c->modelhands you back aDBIx::Class::ResultSetwhich handles queries against the database and iterating over the set of results that comes back. π
So we're using ->all to snag all of the books. and like, DBIC supports a wide variety of more advanced operations so you can easily do stuff like filtering and sorting the results. for example, this right here would sort the results by descending title:
$c->model('DB::Book')->search({}, {order_by => 'title DESC'});
some other examples live in "Complex WHERE clauses" in DBIx::Class::Manual::Cookbook, and there's even more info at "search" in DBIx::Class::ResultSet, "Searching" in DBIx::Class::Manual::FAQ, DBIx::Class::Manual::Intro and Catalyst::Model::DBIC::Schema. iykyk πΈ
Test Run The Application π§
First things first β let's enable an environment variable that makes DBIx::Class dump the SQL statements it uses to hit the database. it's genuinely such a helpful trick when you're trying to debug your database-oriented code. hit Ctrl+C to break out of the development server, then enter:
$ export DBIC_TRACE=1
$ script/myapp_server.pl -r
this assumes you're using bash as your shell β adjust accordingly if you're on a different one (for example, under tcsh, use setenv DBIC_TRACE 1). π
NOTE: you can also set this in your code using $class->storage->debug(1);. see DBIx::Class::Manual::Troubleshooting for details (including options to log to a file instead of displaying to the Catalyst development server log). π
Then launch the Catalyst development server. the log output should display something like:
$ script/myapp_server.pl -r
[debug] Debug messages enabled
[debug] Statistics enabled
[debug] Loaded plugins:
.----------------------------------------------------------------------------.
| Catalyst::Plugin::ConfigLoader 0.30 |
| Catalyst::Plugin::StackTrace 0.11 |
'----------------------------------------------------------------------------'
[debug] Loaded dispatcher "Catalyst::Dispatcher"
[debug] Loaded engine "Catalyst::Engine"
[debug] Found home "/home/catalyst/MyApp"
[debug] Loaded Config "/home/catalyst/MyApp/myapp.conf"
[debug] Loaded components:
.-----------------------------------------------------------------+----------.
| Class | Type |
+-----------------------------------------------------------------+----------+
| MyApp::Controller::Books | instance |
| MyApp::Controller::Root | instance |
| MyApp::Model::DB | instance |
| MyApp::Model::DB::Author | class |
| MyApp::Model::DB::Book | class |
| MyApp::Model::DB::BookAuthor | class |
| MyApp::View::HTML | instance |
'-----------------------------------------------------------------+----------'
[debug] Loaded Private actions:
.----------------------+--------------------------------------+--------------.
| Private | Class | Method |
+----------------------+--------------------------------------+--------------+
| /default | MyApp::Controller::Root | default |
| /end | MyApp::Controller::Root | end |
| /index | MyApp::Controller::Root | index |
| /books/index | MyApp::Controller::Books | index |
| /books/list | MyApp::Controller::Books | list |
'----------------------+--------------------------------------+--------------'
[debug] Loaded Path actions:
.-------------------------------------+--------------------------------------.
| Path | Private |
+-------------------------------------+--------------------------------------+
| / | /default |
| / | /index |
| /books | /books/index |
| /books/list | /books/list |
'-------------------------------------+--------------------------------------'
[info] MyApp powered by Catalyst 5.80020
HTTP::Server::PSGI: Accepting connections at http://0:3000
NOTE: be sure you run thescript/myapp_server.plcommand from the 'base' directory of your application β not inside thescriptdirectory itself, or it will not be able to locate themyapp.dbdatabase file. π you can use a fully qualified or a relative path to locate the database file, but we didn't specify that when we ran the model helper earlier.
Some things you should note in the output above:
- Catalyst::Model::DBIC::Schema dynamically created three model classes, one to represent each of the three tables in our database (
MyApp::Model::DB::Author,MyApp::Model::DB::BookAuthor, andMyApp::Model::DB::Book). π - the
listaction in our Books controller showed up with a path of/books/list. β¨
Point your browser to <http://localhost:3000> and you should still get the Catalyst welcome page.
Next, to view the book list, change the URL in your browser to <http://localhost:3000/books/list>. you should get a list of the five books loaded by the myapp01.sql script above without any formatting. the rating for each book should appear on each row, but the "Author(s)" column will still be blank (we will fill that in later). π
Also notice in the output of the script/myapp_server.pl that DBIx::Class used the following SQL to retrieve the data:
SELECT me.id, me.title, me.rating FROM book me
...because we enabled DBIC_TRACE. π₯
You now have the beginnings of a simple but workable web application. continue on to future sections and we will develop the application more fully. π«Ά
CREATE A WRAPPER FOR THE VIEW π
When using TT, you can (and should) create a wrapper that will literally wrap content around each of your templates. this is certainly useful since you get one main source for changing things that appear across your entire site/application instead of having to edit a million individual files. it's giving efficiency, honestly. π
Configure HTML.pm For The Wrapper
In order to create a wrapper, you must first edit your TT view and tell it where to find your wrapper file.
Edit your TT view in lib/MyApp/View/HTML.pm and change it to match the following:
__PACKAGE__->config(
# Change default TT extension
TEMPLATE_EXTENSION => '.tt2',
# Set the location for TT files
INCLUDE_PATH => [
MyApp->path_to( 'root', 'src' ),
],
# Set to 1 for detailed timer stats in your HTML as comments
TIMER => 0,
# This is your wrapper template located in the 'root/src'
WRAPPER => 'wrapper.tt2',
);
Create the Wrapper Template File and Stylesheet π¦
Next you need to set up your wrapper template. basically, you'll want to take the overall layout of your site and put it into this file. for the tutorial, open root/src/wrapper.tt2 and input the following:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" [%#
%]"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<title>[% template.title or "My Catalyst App!" %]</title>
<link rel="stylesheet" href="[% c.uri_for('/static/css/main.css') %]" />
</head>
<body>
<div id="outer">
<div id="header">
[%# Your logo could go here -%]
<img src="[% c.uri_for('/static/images/btn_88x31_powered.png') %]" />
[%# Insert the page title -%]
<h1>[% template.title or site.title %]</h1>
</div>
<div id="bodyblock">
<div id="menu">
Navigation:
<ul>
<li><a href="[% c.uri_for('/books/list') %]">Home</a></li>
<li><a href="[% c.uri_for('/')
%]" title="Catalyst Welcome Page">Welcome</a></li>
</ul>
</div><!-- end menu -->
<div id="content">
[%# Status and error messages %]
<span class="message">[% status_msg %]</span>
<span class="error">[% error_msg %]</span>
[%# This is where TT will stick all of your template's contents. -%]
[% content %]
</div><!-- end content -->
</div><!-- end bodyblock -->
<div id="footer">Copyright (c) your name goes here</div>
</div><!-- end outer -->
</body>
</html>
Notice the status and error message sections in the code above:
<span class="status">[% status_msg %]</span>
<span class="error">[% error_msg %]</span>
If we set either message in the Catalyst stash (e.g., $c->stash->{status_msg} = 'Request was successful!') it will be displayed whenever any view used by that request is rendered. the message and error CSS styles can be customized to suit your needs in the root/static/css/main.css file we create below. π
Notes:
- The Catalyst stash only lasts for a single HTTP request. If you need to retain information across requests you can use
Catalyst::Plugin::Session(we will use Catalyst sessions in the Authentication chapter of the tutorial). π - Although it is beyond the scope of this tutorial, you may wish to use a JavaScript or AJAX tool such as jQuery (
https://www.jquery.com) or Dojo (https://dojotoolkit.org/). β¨
π Create A Basic Stylesheet π
First, make a central spot for stylesheets under the static directory:
$ mkdir root/static/css
Then open the file root/static/css/main.css β that's the file referenced in the stylesheet href link of our wrapper above β and drop in this content:
#header {
text-align: center;
}
#header h1 {
margin: 0;
}
#header img {
float: right;
}
#footer {
text-align: center;
font-style: italic;
padding-top: 20px;
}
#menu {
font-weight: bold;
background-color: #ddd;
}
#menu ul {
list-style: none;
float: left;
margin: 0;
padding: 0 0 50% 5px;
font-weight: normal;
background-color: #ddd;
width: 100px;
}
#content {
margin-left: 120px;
}
.message {
color: #390;
}
.error {
color: #f00;
}
You may wish to check out a "CSS Framework" like Emastic (http://code.google.com/p/emastic/) as a way to quickly provide lots of high-quality CSS functionality. πΈ
β¨ Test Run The Application β¨
Hit Reload in your web browser and you should now see a formatted version of our basic book list. (Again, the development server should have automatically restarted when you made changes to lib/MyApp/View/HTML.pm. If you are not using the -r option, you will need to hit Ctrl+C and manually restart it. Also note that the development server does NOT need to restart for changes to the TT and static files we created and edited in the root directory β those updates are handled on a per-request basis.) π«Ά
Although our wrapper and stylesheet are obviously very simple, you should see how it allows us to control the overall look of an entire website from two central files. To add new pages to the site, just provide a template that fills in the content section of our wrapper template β the wrapper will provide the overall feel of the page. π
π§ Updating the Generated DBIx::Class Result Class Files π§
If you take a look at the Schema files automatically generated by DBIx::Class::Schema::Loader, you will see that it has already defined has_many and belongs_to relationships on each side of our foreign keys. For example, take a look at lib/MyApp/Schema/Result/Book.pm and notice the following code:
=head1 RELATIONS
=head2 book_authors
Type: has_many
Related object: L<MyApp::Schema::Result::BookAuthor>
=cut
__PACKAGE__->has_many(
"book_authors",
"MyApp::Schema::Result::BookAuthor",
{ "foreign.book_id" => "self.id" },
{ cascade_copy => 0, cascade_delete => 0 },
);
Each Book has_many book_authors, where BookAuthor is the many-to-many table that allows each Book to have multiple Authors, and each Author to have multiple books. The arguments to has_many are:
book_authorsβ The name for this relationship. DBIC will create an accessor on theBooksDBIC Row object with this name.MyApp::Schema::Result::BookAuthorβ The name of the DBIC model class referenced by thishas_manyrelationship.foreign.book_idβbook_idis the name of the foreign key column in the foreign table that points back to this table.self.idβidis the name of the column in this table that is referenced by the foreign key.
See has_many in DBIx::Class::Relationship for additional information. Note that you might see a "hand coded" version of the has_many relationship above expressed as:
__PACKAGE__->has_many(
"book_authors",
"MyApp::Schema::Result::BookAuthor",
"book_id",
);
Where the third argument is simply the name of the column in the foreign table. However, the hashref syntax used by DBIx::Class::Schema::Loader is more flexible (for example, it can handle "multi-column foreign keys"). π₯
Note: If you are using older versions of SQLite and related DBIC tools, you will need to manually define yourhas_manyandbelongs_torelationships. We recommend upgrading to the versions specified above.:-)
Have a look at lib/MyApp/Schema/Result/BookAuthor.pm and notice that there is a belongs_to relationship defined that acts as the "mirror image" to the has_many relationship we just looked at above:
=head1 RELATIONS
=head2 book
Type: belongs_to
Related object: L<MyApp::Schema::Result::Book>
=cut
__PACKAGE__->belongs_to(
"book",
"MyApp::Schema::Result::Book",
{ id => "book_id" },
{ join_type => "LEFT", on_delete => "CASCADE", on_update => "CASCADE" },
);
The arguments are similar, but see belongs_to in DBIx::Class::Relationship for the details. π
Although recent versions of SQLite and DBIx::Class::Schema::Loader automatically handle the has_many and belongs_to relationships, many_to_many relationship bridges (not technically a relationship) currently need to be manually inserted. To add a many_to_many relationship bridge, first edit lib/MyApp/Schema/Result/Book.pm and add the following text below the # You can replace this text... comment:
# many_to_many():
# args:
# 1) Name of relationship bridge, DBIC will create accessor with this name
# 2) Name of has_many() relationship this many_to_many() is shortcut for
# 3) Name of belongs_to() relationship in model class of has_many() above
# You must already have the has_many() defined to use a many_to_many().
__PACKAGE__->many_to_many(authors => 'book_authors', 'author');
Note: Be careful to put this code above the1;at the end of the file. As with any Perl package, we need to end the last line with a statement that evaluates totrue. This is customarily done with1;on a line by itself.
The many_to_many relationship bridge is optional, but it makes it easier to map a book to its collection of authors. Without it, we would have to "walk" through the book_author table as in $book->book_author->first->author->last_name (we will see examples on how to use DBIx::Class objects in your code soon, but note that because $book->book_author can return multiple authors, we have to use first to display a single author). many_to_many allows us to use the shorter $book->author->first->last_name. Note that you cannot define a many_to_many relationship bridge without also having the has_many relationship in place. π¦
Then edit lib/MyApp/Schema/Result/Author.pm and add the reverse many_to_many relationship bridge for Author as follows (again, be careful to put in above the 1; but below the # DO NOT MODIFY THIS OR ANYTHING ABOVE! comment):
# many_to_many():
# args:
# 1) Name of relationship bridge, DBIC will create accessor with this name
# 2) Name of has_many() relationship this many_to_many() is shortcut for
# 3) Name of belongs_to() relationship in model class of has_many() above
# You must already have the has_many() defined to use a many_to_many().
__PACKAGE__->many_to_many(books => 'book_authors', 'book');
π Run The Application π
Run the Catalyst development server script with the DBIC_TRACE option (it might still be enabled from earlier in the tutorial, but here is an alternate way to specify the trace option just in case):
$ DBIC_TRACE=1 script/myapp_server.pl -r
Make sure that the application loads correctly and that you see the three dynamically created model classes (one for each of the Result Classes we created). π
Then hit the URL http://localhost:3000/books/list with your browser and be sure that the book list still displays correctly. β
Note: You will not see the authors yet because the view isn't taking advantage of these relationships. Read on to the next section where we update the template to do that. π
π UPDATING THE VIEW π
okay bestie, let's add a new column to our book list page that takes advantage of the relationship info we manually added to our schema files in the previous section. Edit root/src/books/list.tt2 and replace the empty table cell <td></td> with this:
...
<td>
[% # NOTE: See Chapter 4 for a better way to do this! -%]
[% # First initialize a TT variable to hold a list. Then use a TT FOREACH -%]
[% # loop in 'side effect notation' to load just the last names of the -%]
[% # authors into the list. Note that the 'push' TT vmethod doesn't return -%]
[% # a value, so nothing will be printed here. But, if you have something -%]
[% # in TT that does return a value and you don't want it printed, you -%]
[% # 1) assign it to a bogus value, or -%]
[% # 2) use the CALL keyword to call it and discard the return value. -%]
[% tt_authors = [ ];
tt_authors.push(author.last_name) FOREACH author = book.authors %]
[% # Now use a TT 'virtual method' to display the author count in parens -%]
[% # Note the use of the TT filter "| html" to escape dangerous characters -%]
([% tt_authors.size | html %])
[% # Use another TT vmethod to join & print the names & comma separators -%]
[% tt_authors.join(', ') | html %]
</td>
...
IMPORTANT NOTE: Again, you should keep as much "logic code" as possible out of your views. This kind of logic belongs in your model (the same goes for controllers -- keep them as "thin" as possible and push all of the "complicated code" out to your model objects). Avoid code like you see in the previous example -- we are only using it here to show some extra features in TT until we get to the more advanced model features we will see in Chapter 4 (see "EXPLORING THE POWER OF DBIC" in Catalyst::Manual::Tutorial::04_BasicCRUD).
Then hit "Reload" in your browser (note that you don't need to reload the development server or use the -r option when updating TT templates) and you should now see the number of authors each book has along with a comma-separated list of the authors' last names. (If you didn't leave the development server running from the previous step, you will obviously need to start it before you can refresh your browser window.)
If you are still running the development server with DBIC_TRACE enabled, you should also now see five more SELECT statements in the debug output (one for each book as the authors are being retrieved by DBIx::Class):
SELECT me.id, me.title, me.rating FROM book me:
SELECT author.id, author.first_name, author.last_name FROM book_author me
JOIN author author ON author.id = me.author_id WHERE ( me.book_id = ? ): '1'
SELECT author.id, author.first_name, author.last_name FROM book_author me
JOIN author author ON author.id = me.author_id WHERE ( me.book_id = ? ): '2'
SELECT author.id, author.first_name, author.last_name FROM book_author me
JOIN author author ON author.id = me.author_id WHERE ( me.book_id = ? ): '3'
SELECT author.id, author.first_name, author.last_name FROM book_author me
JOIN author author ON author.id = me.author_id WHERE ( me.book_id = ? ): '4'
SELECT author.id, author.first_name, author.last_name FROM book_author me
JOIN author author ON author.id = me.author_id WHERE ( me.book_id = ? ): '5'
Also note in root/src/books/list.tt2 that we are using | html, a type of TT filter, to escape characters such as < and > to < and > and avoid various types of dangerous hacks against your application. In a real application, you would probably want to put | html at the end of every field where a user has control over the information that can appear in that field (and can therefore inject markup or code if you don't "neutralize" those fields). In addition to | html, Template Toolkit has a variety of other useful filters that can be found in the documentation for Template::Filters. (While we are on the topic of security and escaping of dangerous values, one of the advantages of using tools like DBIC for database access or HTML::FormFu for form management [see Chapter 9] is that they automatically handle most escaping for you and therefore dramatically increase the security of your app.)
π RUNNING THE APPLICATION FROM THE COMMAND LINE π
In some situations, it can be useful to run your application and display a page without using a browser. Catalyst lets you do this using the script/myapp_test.pl script. Just supply the URL you wish to display and it will run that request through the normal controller dispatch logic and use the appropriate view to render the output (obviously, complex pages may dump a lot of text to your terminal window). For example, if you Ctrl+C out of the development server and then type:
$ script/myapp_test.pl "/books/list"
You should get the same text as if you visited http://localhost:3000/books/list with the normal development server and asked your browser to view the page source. You can even pipe this HTML text output to a text-based browser using a command like:
$ script/myapp_test.pl "/books/list" | lynx -stdin
And you should see a fully rendered text-based view of your page. (If you are following along in Debian 6, type sudo aptitude -y install lynx to install lynx.) If you do start lynx, you can use the Q key to quit.
π OPTIONAL INFORMATION π
NOTE: The rest of this chapter of the tutorial is optional. You can skip to Chapter 4, Basic CRUD, if you wish.
β¨ Using 'RenderView' for the Default View β¨
Once your controller logic has processed the request from a user, it forwards processing to your view in order to generate the appropriate response output. Catalyst uses Catalyst::Action::RenderView by default to automatically perform this operation. If you look in lib/MyApp/Controller/Root.pm, you should see the empty definition for the sub end method:
sub end : ActionClass('RenderView') {}
The following bullet points provide a quick overview of the RenderView process:
Root.pmis designed to hold application-wide logic.- At the end of a given user request, Catalyst will call the most specific
endmethod that's appropriate. For example, if the controller for a request has anendmethod defined, it will be called. However, if the controller does not define a controller-specificendmethod, the "global"endmethod inRoot.pmwill be called. - Because the definition includes an
ActionClassattribute, theCatalyst::Action::RenderViewlogic will be executed after any code inside the definition ofsub endis run. SeeCatalyst::Manual::Actionsfor more information onActionClass. - Because
sub endis empty, this effectively just runs the default logic inRenderView. However, you can easily extend theRenderViewlogic by adding your own code inside the empty method body ({}) created by the Catalyst Helpers when we first ran thecatalyst.plto initialize our application. SeeCatalyst::Action::RenderViewfor more detailed information on how to extendRenderViewinsub end.
π΅οΈ RenderView's "dump_info" Feature π΅οΈ
One of the nice features of RenderView is that it automatically allows you to add dump_info=1 to the end of any URL for your application and it will force the display of the "exception dump" screen to the client browser. You can try this out by pointing your browser to this URL:
http://localhost:3000/books/list?dump_info=1
You should get a page with the following message at the top:
Caught exception in MyApp::Controller::Root->end "Forced debug -
Scrubbed output at /usr/share/perl5/Catalyst/Action/RenderView.pm line 46."
Along with a summary of your application's state at the end of the processing for that request. The "Stash" section should show a summarized version of the DBIC book model objects. If desired, you can adjust the summarization logic (called "scrubbing" logic) -- see Catalyst::Action::RenderView for details.
Note that you shouldn't need to worry about "normal clients" using this technique to "reverse engineer" your application -- RenderView only supports the dump_info=1 feature when your application is running in -Debug mode (something you won't do once you have your application deployed in production).
π Using The Default Template Name π
By default, Catalyst::View::TT will look for a template that uses the same name as your controller action, allowing you to save the step of manually specifying the template name in each action. For example, this would allow us to remove the $c->stash->{template} = 'books/list.tt2'; line of our list action in the Books controller. Open lib/MyApp/Controller/Books.pm in your editor and comment out this line to match the following (only the $c->stash->{template} line has changed):
=head2 list
Fetch all book objects and pass to books/list.tt2 in stash to be displayed
=cut
sub list :Local {
# Retrieve the usual Perl OO '$self' for this object. $c is the Catalyst
# 'Context' that's used to 'glue together' the various components
# that make up the application
my ($self, $c) = @_;
# Retrieve all of the book records as book model objects and store in the
# stash where they can be accessed by the TT template
$c->stash(books => [$c->model('DB::Book')->all]);
# Set the TT template to use. You will almost always want to do this
# in your action methods (actions methods respond to user input in
# your controllers).
#$c->stash(template => 'books/list.tt2');
}
You should now be able to access the http://localhost:3000/books/list URL as before.
NOTE: If you use the default template technique, you will not be able to use either the$c->forwardor the$c->detachmechanisms (these are discussed in Chapter 2 and Chapter 9 of the Tutorial).
IMPORTANT: Make sure that you do not skip the following section before continuing to the next chapter 4 Basic CRUD.
π Return To A Manually Specified Template π
In order to be able to use $c->forward and $c->detach later in the tutorial, you should remove the comment from the statement in sub list in lib/MyApp/Controller/Books.pm:
$c->stash(template => 'books/list.tt2');
Then delete the TEMPLATE_EXTENSION line in lib/MyApp/View/HTML.pm.
Check the http://localhost:3000/books/list URL in your browser. It should look the same manner as with earlier sections.
You can jump to the next chapter of the tutorial here: Basic CRUD
π AUTHOR π
Okay so this whole manual was written by Kennedy Clark, and if you need to reach him his email is "hkclark@gmail.com" β yes bestie, keep the quotes, theyβre literally part of it.
He says feel free to contact the author about any errors or suggestions, but the best way to report issues is through the CPAN RT Bug system at https://rt.cpan.org/Public/Dist/Display.html?Name=Catalyst-Manual. Thatβs the move, fr fr.
Copyright 2006-2011, Kennedy Clark, under the Creative Commons Attribution Share-Alike License Version 3.0 (https://creativecommons.org/licenses/by-sa/3.0/us/).
And thatβs the whole page, bestie π«Ά this one came from perl v5.42.0, dated 2024-03-23, and itβs the manual page for Catalys...stBasics(3). Slay, you made it to the end π
β¨
π¦ where this page comes from
- opensuse-leap 16.0: perl-Catalyst-Manual 5.9013-bp160.1.11 Β· Artistic-1.0 OR GPL-1.0-or-later
- π girlified by deepseek-ai/DeepSeek-V4.1-Flash-1017 on : a language model's rewrite of the original, under its terms