3 Catalyst::Manual::Tutorial::02_CatalystBasics - Catalyst Tutorial - Chapter 2: Catalyst Application Development Basics
8 This is B<Chapter 2 of 10> for the Catalyst tutorial.
10 L<Tutorial Overview|Catalyst::Manual::Tutorial>
16 L<Introduction|Catalyst::Manual::Tutorial::01_Intro>
24 L<More Catalyst Basics|Catalyst::Manual::Tutorial::03_MoreCatalystBasics>
28 L<Basic CRUD|Catalyst::Manual::Tutorial::04_BasicCRUD>
32 L<Authentication|Catalyst::Manual::Tutorial::05_Authentication>
36 L<Authorization|Catalyst::Manual::Tutorial::06_Authorization>
40 L<Debugging|Catalyst::Manual::Tutorial::07_Debugging>
44 L<Testing|Catalyst::Manual::Tutorial::08_Testing>
48 L<Advanced CRUD|Catalyst::Manual::Tutorial::09_AdvancedCRUD>
52 L<Appendices|Catalyst::Manual::Tutorial::10_Appendices>
59 In this chapter of the tutorial, we will create a very basic Catalyst
60 web application, demonstrating a number of powerful capabilities, such
65 =item * Helper Scripts
67 Catalyst helper scripts that can be used to rapidly bootstrap the
68 skeletal structure of an application.
72 Model/View/Controller (MVC) provides an architecture that facilitates a
73 clean "separation of control" between the different portions of your
74 application. Given that many other documents cover this subject in
75 detail, MVC will not be discussed in depth here (for an excellent
76 introduction to MVC and general Catalyst concepts, please see
77 L<Catalyst::Manual::About|Catalyst::Manual::About>). In short:
83 The model usually represents a data store. In most applications, the
84 model equates to the objects that are created from and saved to your SQL
89 The view takes model objects and renders them into something for the end
90 user to look at. Normally this involves a template-generation tool that
91 creates HTML for the user's web browser, but it could easily be code
92 that generates other forms such as PDF documents, e-mails, spreadsheets,
93 or even "behind the scenes" formats such as XML and JSON.
97 As suggested by its name, the controller takes user requests and routes
98 them to the necessary model and view.
104 The use of Object-Relational Mapping (ORM) technology for database
105 access. Specifically, ORM provides an automated and standardized means
106 to persist and restore objects to/from a relational database and will
107 automatically create our Catalyst model for use with a database.
111 You can checkout the source code for this example from the catalyst
112 subversion repository as per the instructions in
113 L<Catalyst::Manual::Tutorial::01_Intro|Catalyst::Manual::Tutorial::01_Intro>.
116 =head1 CREATE A CATALYST PROJECT
118 Catalyst provides a number of helper scripts that can be used to
119 quickly flesh out the basic structure of your application. All
120 Catalyst projects begin with the C<catalyst.pl> helper (see
121 L<Catalyst::Helper|Catalyst::Helper> for more information on helpers).
122 Also note that as of Catalyst 5.7000, you will not have the helper
123 scripts unless you install both L<Catalyst::Runtime|Catalyst::Runtime>
124 and L<Catalyst::Devel|Catalyst::Devel>.
126 In this first chapter of the tutorial, use the Catalyst C<catalyst.pl>
127 script to initialize the framework for an application called C<Hello>:
131 created "Hello/script"
135 created "Hello/script/hello_create.pl"
136 Change to application directory and Run "perl Makefile.PL" to make sure your install is complete
139 Note: If you are using Strawberry Perl on Win32, drop the ".pl"
140 from the end of the "catalyst.pl" command and simply use
143 The C<catalyst.pl> helper script will display the names of the
144 directories and files it creates:
146 Changes # Record of application changes
147 lib # Lib directory for your app's Perl modules
148 Hello # Application main code directory
149 Controller # Directory for Controller modules
150 Model # Directory for Models
151 View # Directory for Views
152 Hello.pm # Base application module
153 Makefile.PL # Makefile to build application
154 hello.conf # Application configuration file
156 root # Equiv of htdocs, dir for templates, css, javascript
158 static # Directory for static files
159 images # Directory for image files used in welcome screen
160 script # Directory for Perl scripts
161 hello_cgi.pl # To run your app as a cgi (not recommended)
162 hello_create.pl # To create models, views, controllers
163 hello_fastcgi.pl # To run app as a fastcgi program
164 hello_server.pl # The normal development server
165 hello_test.pl # Test your app from the command line
166 t # Directory for tests
167 01app.t # Test scaffold
172 Catalyst will "auto-discover" modules in the Controller, Model, and
173 View directories. When you use the hello_create.pl script it will
174 create Perl module scaffolds in those directories, plus test files in
175 the "t" directory. The default location for templates is in the "root"
176 directory. The scripts in the script directory will always start with
177 the lowercased version of your application name. If your app is
178 MaiTai, then the create script would be "maitai_create.pl".
180 Though it's too early for any significant celebration, we already have
181 a functioning application. We can use the Catalyst supplied script to
182 start up a development server and view the default Catalyst page in
183 your browser. All scripts in the script directory should be run from
184 the base directory of your application, so change to the Hello
187 Run the following command to start up the built-in development web
188 server (make sure you didn't forget the "C<cd Hello>" from the
191 $ script/hello_server.pl
192 [debug] Debug messages enabled
193 [debug] Statistics enabled
194 [debug] Loaded plugins:
195 .----------------------------------------------------------------------------.
196 | Catalyst::Plugin::ConfigLoader 0.27 |
197 | Catalyst::Plugin::Static::Simple 0.25 |
198 '----------------------------------------------------------------------------'
200 [debug] Loaded dispatcher "Catalyst::Dispatcher"
201 [debug] Loaded engine "Catalyst::Engine::HTTP"
202 [debug] Found home "/home/me/Hello"
203 [debug] Loaded Config "/home/me/Hello/hello.conf"
204 [debug] Loaded components:
205 .-----------------------------------------------------------------+----------.
207 +-----------------------------------------------------------------+----------+
208 | Hello::Controller::Root | instance |
209 '-----------------------------------------------------------------+----------'
211 [debug] Loaded Private actions:
212 .----------------------+--------------------------------------+--------------.
213 | Private | Class | Method |
214 +----------------------+--------------------------------------+--------------+
215 | /default | Hello::Controller::Root | default |
216 | /end | Hello::Controller::Root | end |
217 | /index | Hello::Controller::Root | index |
218 '----------------------+--------------------------------------+--------------'
220 [debug] Loaded Path actions:
221 .-------------------------------------+--------------------------------------.
223 +-------------------------------------+--------------------------------------+
226 '-------------------------------------+--------------------------------------'
228 [info] Hello powered by Catalyst 5.80013
229 You can connect to your server at http://debian:3000
231 Point your web browser to L<http://localhost:3000> (substituting a
232 different hostname or IP address as appropriate) and you should be
233 greeted by the Catalyst welcome screen (if you get some other welcome
234 screen or an "Index" screen, you probably forgot to specify port 3000
235 in your URL). Information similar to the following should be appended
236 to the logging output of the development server:
238 [info] *** Request 1 (0.005/s) [20712] [Sun Oct 11 11:58:51 2009] ***
239 [debug] "GET" request for "/" from "172.0.0.1"
240 [info] Request took 0.007342s (136.203/s)
241 .----------------------------------------------------------------+-----------.
243 +----------------------------------------------------------------+-----------+
244 | /index | 0.000491s |
246 '----------------------------------------------------------------+-----------'
248 Press Ctrl-C to break out of the development server.
253 =head2 The Simplest Way
255 The Root.pm controller is a place to put global actions that usually
256 execute on the root URL. Open the C<lib/Hello/Controller/Root.pm> file in
257 your editor. You will see the "index" subroutine, which is
258 responsible for displaying the welcome screen that you just saw in
259 your browser. Later on you'll want to change that to something more
260 reasonable, such as a "404" message or a redirect, but for now just
263 sub index :Path :Args(0) {
264 my ( $self, $c ) = @_;
267 $c->response->body( $c->welcome_message );
270 The "C<$c>" here refers to the Catalyst context, which is used to
271 access the Catalyst application. In addition to many other things,
272 the Catalyst context provides access to "response" and "request"
273 objects. (See L<Catalyst|Catalyst>,
274 L<Catalyst::Response|Catalyst::Response>, and
275 L<Catalyst::Request|Catalyst::Request>)
277 C<$c-E<gt>response-E<gt>body> sets the HTTP response (see
278 L<Catalyst::Response|Catalyst::Response>), while C<$c-E<gt>welcome_message>
279 is a special method that returns the welcome message that you saw in
282 The ":Path :Args(0)" after the method name are attributes which
283 determine which URLs will be dispatched to this method. (You might see
284 ":Private" if you are using an older version of Catalyst, but using
285 that with 'default' or 'index' is currently deprecated. If so, you
286 should also probably upgrade before continuing the tutorial.)
288 Some MVC frameworks handle dispatching in a central place. Catalyst,
289 by policy, prefers to handle URL dispatching with attributes on
290 controller methods. There is a lot of flexibility in specifying which
291 URLs to match. This particular method will match all URLs, because it
292 doesn't specify the path (nothing comes after "Path"), but will only
293 accept a URL without any args because of the ":Args(0)".
295 The default is to map URLs to controller names, and because of the way
296 that Perl handles namespaces through package names, it is simple to
297 create hierarchical structures in Catalyst. This means that you can
298 create controllers with deeply nested actions in a clean and logical
299 way. For example, the URL C<http://hello.com/admin/articles/create>
300 maps to the package C<Hello::Controller::Admin::Articles>, and the
303 Add the following subroutine to your C<lib/Hello/Controller/Root.pm>
307 my ( $self, $c ) = @_;
309 $c->response->body("Hello, World!");
312 B<TIP>: See Appendix 1 for tips on removing the leading spaces when
313 cutting and pasting example code from POD-based documents.
315 Here you're sending your own string to the webpage.
317 Save the file, start the server (stop and restart it if it's still
318 running), and go to L<http://localhost:3000/hello> to
319 see "Hello, World!" Also notice that a new action is listed under
320 "Loaded Private actions" in the development server debug output.
323 =head2 Hello, World! Using a View and a Template
325 In the Catalyst world a "View" itself is not a page of XHTML or a
326 template designed to present a page to a browser. Rather, it is the
327 module that determines the I<type> of view -- HTML, pdf, XML, etc. For
328 the thing that generates the I<content> of that view (such as the a
329 Toolkit Template template file), the actual templates go under the
332 To create a TT view, run:
334 $ script/hello_create.pl view TT TT
336 This creates the C<lib/Hello/View/TT.pm> module, which is a subclass of
337 C<Catalyst::View::TT>.
343 The "view" keyword tells the create script that you are creating a view.
347 The first "TT" tells the script to name the View module "TT.pm", which is a
348 commonly used name for TT views. (You can name it anything you want, such as
353 The final "TT" tells Catalyst the I<type> of the view, with "TT"
354 indicating that you want to a Template Toolkit view.
358 If you look at C<lib/Hello/View/TT.pm> you will find that it only
359 contains a config statement to set the TT extension to ".tt".
361 Now that the TT.pm "View" exists, Catalyst will autodiscover it and be
362 able to use it to display the view templates using the "process"
363 method that it inherits from the C<Catalyst::View::TT class>.
365 Template Toolkit is a very full featured template facility, with
366 excellent documentation at L<http://template-toolkit.org/>,
367 but since this is not a TT tutorial, we'll stick to only basic TT
368 usage here (and explore some of the more common TT features in later
369 chapters of the tutorial).
371 Create a C<root/hello.tt> template file (put it in the C<root> under
372 the C<Hello> directory that is the base of your application). Here is
376 This is a TT view template, called '[% template.name %]'.
379 [% and %] are markers for the TT parts of the template. Inside you can
380 access Perl variables and classes, and use TT directives. In this
381 case, we're using a special TT variable that defines the name of the
382 template file (C<hello.tt>). The rest of the template is normal HTML.
384 Change the hello method in C<lib/Hello/Controller/Root.pm> to the
388 my ( $self, $c ) = @_;
390 $c->stash->{template} = 'hello.tt';
393 This time, instead of doing C<$c-E<gt>response-E<gt>body()>, you are
394 setting the value of the "template" hash key in the Catalyst "stash",
395 an area for putting information to share with other parts of your
396 application. The "template" key determines which template will be
397 displayed at the end of the request cycle. Catalyst controllers have a
398 default "end" action for all methods which causes the first (or
399 default) view to be rendered (unless there's a C<$c-E<gt>response-
400 E<gt>body()> statement). So your template will be magically displayed
401 at the end of your method.
403 After saving the file, restart the development server, and look at
404 L<http://localhost:3000/hello> again. You should
405 see the template that you just made.
408 =head1 CREATE A SIMPLE CONTROLLER AND AN ACTION
410 Create a controller named "Site" by executing the create script:
412 $ script/hello_create.pl controller Site
414 This will create a C<lib/Hello/Controller/Site.pm> file (and a test
415 file). Bring Site.pm up in your editor, and you can see that there's
418 In C<lib/Hello/Controller/Site.pm>, add the following method:
421 my ( $self, $c ) = @_;
423 $c->stash->{username} = "John";
424 $c->stash->{template} = 'site/test.tt';
427 Notice the "Local" attribute on the C<test> method. This will cause
428 the C<test> action (now that we have assigned an "action type" to the
429 method it appears as a "controller action" to Catalyst) to be executed
430 on the "controller/method" URL, or, in this case, "site/test". We
431 will see additional information on controller actions throughout the
432 rest of the tutorial, but if you are curious take a look at
433 L<Catalyst::Manual::Intro/Actions>.
435 It's not actually necessary to set the template value as we do here.
436 By default TT will attempt to render a template that follows the
437 naming pattern "controller/method.tt", and we're following that
438 pattern here. However, in other situations you will need to specify
439 the template (such as if you've "forwarded" to the method, or if it
440 doesn't follow the default naming convention).
442 We've also put the variable "username" into the stash, for use in the
445 Make a subdirectory "site" in the "root" directory. Copy the hello.tt
446 file into the directory as C<root/site/test.tt>, or create a new
447 template file at that location. Include a line like:
449 <p>Hello, [% username %]!</p>
451 Bring up or restart the server. Notice in the server output that
452 C</site/test> is listed in the Loaded Path actions. Go to
453 L<http://localhost:3000/site/test> in your browser.
455 You should see your test.tt file displayed, including the name "John"
456 that you set in the controller.
461 Gerda Shank, C<gerda.shank@gmail.com>
462 Kennedy Clark, C<hkclark@gmail.com>
464 Please report any errors, issues or suggestions to the author. The
465 most recent version of the Catalyst Tutorial can be found at
466 L<http://dev.catalyst.perl.org/repos/Catalyst/Catalyst-Manual/5.80/trunk/lib/Catalyst/Manual/Tutorial/>.
468 Copyright 2006-2008, Kennedy Clark & Gerda Shank, under Creative Commons License
469 (L<http://creativecommons.org/licenses/by-sa/3.0/us/>).