Update year on copyright
[catagits/Catalyst-Manual.git] / lib / Catalyst / Manual / Tutorial / 02_CatalystBasics.pod
d442cc9f 1=head1 NAME
3ab6187c 3Catalyst::Manual::Tutorial::02_CatalystBasics - Catalyst Tutorial - Chapter 2: Catalyst Application Development Basics
d442cc9f 4
6=head1 OVERVIEW
4b4d3884 8This is B<Chapter 2 of 10> for the Catalyst tutorial.
d442cc9f 9
10L<Tutorial Overview|Catalyst::Manual::Tutorial>
12=over 4
14=item 1
3ab6187c 16L<Introduction|Catalyst::Manual::Tutorial::01_Intro>
d442cc9f 17
18=item 2
3ab6187c 20B<02_Catalyst Basics>
d442cc9f 21
22=item 3
3ab6187c 24L<More Catalyst Basics|Catalyst::Manual::Tutorial::03_MoreCatalystBasics>
d442cc9f 25
26=item 4
3ab6187c 28L<Basic CRUD|Catalyst::Manual::Tutorial::04_BasicCRUD>
d442cc9f 29
30=item 5
3ab6187c 32L<Authentication|Catalyst::Manual::Tutorial::05_Authentication>
d442cc9f 33
34=item 6
3ab6187c 36L<Authorization|Catalyst::Manual::Tutorial::06_Authorization>
d442cc9f 37
38=item 7
3ab6187c 40L<Debugging|Catalyst::Manual::Tutorial::07_Debugging>
d442cc9f 41
42=item 8
3ab6187c 44L<Testing|Catalyst::Manual::Tutorial::08_Testing>
d442cc9f 45
46=item 9
3ab6187c 48L<Advanced CRUD|Catalyst::Manual::Tutorial::09_AdvancedCRUD>
3533daff 49
50=item 10
3ab6187c 52L<Appendices|Catalyst::Manual::Tutorial::10_Appendices>
d442cc9f 53
4b4d3884 59In this chapter of the tutorial, we will create a very basic Catalyst
60web application, demonstrating a number of powerful capabilities, such
d442cc9f 62
63=over 4
65=item * Helper Scripts
67Catalyst helper scripts that can be used to rapidly bootstrap the
68skeletal structure of an application.
70=item * MVC
72Model/View/Controller (MVC) provides an architecture that facilitates a
73clean "separation of control" between the different portions of your
74application. Given that many other documents cover this subject in
75detail, MVC will not be discussed in depth here (for an excellent
76introduction to MVC and general Catalyst concepts, please see
865d3efb 77L<Catalyst::Manual::About|Catalyst::Manual::About>). In short:
d442cc9f 78
79=over 4
81=item * Model
83The model usually represents a data store. In most applications, the
84model equates to the objects that are created from and saved to your SQL
87=item * View
89The view takes model objects and renders them into something for the end
90user to look at. Normally this involves a template-generation tool that
91creates HTML for the user's web browser, but it could easily be code
865d3efb 92that generates other forms such as PDF documents, e-mails, spreadsheets,
93or even "behind the scenes" formats such as XML and JSON.
d442cc9f 94
95=item * Controller
97As suggested by its name, the controller takes user requests and routes
98them to the necessary model and view.
102=item * ORM
104The use of Object-Relational Mapping (ORM) technology for database
105access. Specifically, ORM provides an automated and standardized means
444d6b27 106to persist and restore objects to/from a relational database and will
107automatically create our Catalyst model for use with a database.
d442cc9f 108
111You can checkout the source code for this example from the catalyst
112subversion repository as per the instructions in
3ab6187c 113L<Catalyst::Manual::Tutorial::01_Intro|Catalyst::Manual::Tutorial::01_Intro>.
d442cc9f 114
3533daff 115
d442cc9f 116=head1 CREATE A CATALYST PROJECT
3533daff 118Catalyst provides a number of helper scripts that can be used to
119quickly flesh out the basic structure of your application. All
120Catalyst projects begin with the C<catalyst.pl> helper (see
121L<Catalyst::Helper|Catalyst::Helper> for more information on helpers).
122Also note that as of Catalyst 5.7000, you will not have the helper
123scripts unless you install both L<Catalyst::Runtime|Catalyst::Runtime>
124and L<Catalyst::Devel|Catalyst::Devel>.
4b4d3884 126In this first chapter of the tutorial, use the Catalyst C<catalyst.pl>
127script to initialize the framework for an application called C<Hello>:
3533daff 128
129 $ catalyst.pl Hello
130 created "Hello"
131 created "Hello/script"
132 created "Hello/lib"
133 created "Hello/root"
d442cc9f 134 ...
3533daff 135 created "Hello/script/hello_create.pl"
444d6b27 136 Change to application directory and Run "perl Makefile.PL" to make sure your install is complete
3533daff 137 $ cd Hello
d442cc9f 138
444d6b27 139Note: If you are using Strawberry Perl on Win32, drop the ".pl"
140from the end of the "catalyst.pl" command and simply use
141"catalyst Hello".
d442cc9f 143The C<catalyst.pl> helper script will display the names of the
3533daff 144directories and files it creates:
146 Changes # Record of application changes
865d3efb 147 lib # Lib directory for your app's Perl modules
148 Hello # Application main code directory
3533daff 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
45d511e0 154 hello.conf # Application configuration file
3533daff 155 README # README file
156 root # Equiv of htdocs, dir for templates, css, javascript
157 favicon.ico
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
168 02pod.t
169 03podcoverage.t
172Catalyst will "auto-discover" modules in the Controller, Model, and
173View directories. When you use the hello_create.pl script it will
174create Perl module scaffolds in those directories, plus test files in
175the "t" directory. The default location for templates is in the "root"
176directory. The scripts in the script directory will always start with
177the lowercased version of your application name. If your app is
178MaiTai, then the create script would be "maitai_create.pl".
180Though it's too early for any significant celebration, we already have
181a functioning application. We can use the Catalyst supplied script to
182start up a development server and view the default Catalyst page in
183your browser. All scripts in the script directory should be run from
184the base directory of your application, so change to the Hello
187Run the following command to start up the built-in development web
acbd7bdd 188server (make sure you didn't forget the "C<cd Hello>" from the
189previous step):
d442cc9f 190
7a296c6f 191B<Note>: The "-r" argument enables reloading on code changes so you
192don't have to stop and start the server when you update code. See
40a01e5b 193C<perldoc script/hello_server.pl> or C<script/hello_server.pl --help>
194for additional options you might find helpful. Most of the rest of the
195tutorial will assume that you are using "-r" when you start the development
196server, but feel free to manually start and stop it (use C<Ctrl-C> to
197breakout of the dev server) if you prefer.
0f1ac65e 198
199 $ script/hello_server.pl -r
d442cc9f 200 [debug] Debug messages enabled
865d3efb 201 [debug] Statistics enabled
d442cc9f 202 [debug] Loaded plugins:
203 .----------------------------------------------------------------------------.
f34d7f62 204 | Catalyst::Plugin::ConfigLoader 0.27 |
d442cc9f 205 '----------------------------------------------------------------------------'
207 [debug] Loaded dispatcher "Catalyst::Dispatcher"
208 [debug] Loaded engine "Catalyst::Engine::HTTP"
3533daff 209 [debug] Found home "/home/me/Hello"
e13f83cc 210 [debug] Loaded Config "/home/me/Hello/hello.conf"
d442cc9f 211 [debug] Loaded components:
212 .-----------------------------------------------------------------+----------.
213 | Class | Type |
214 +-----------------------------------------------------------------+----------+
3533daff 215 | Hello::Controller::Root | instance |
d442cc9f 216 '-----------------------------------------------------------------+----------'
218 [debug] Loaded Private actions:
219 .----------------------+--------------------------------------+--------------.
220 | Private | Class | Method |
221 +----------------------+--------------------------------------+--------------+
3533daff 222 | /default | Hello::Controller::Root | default |
223 | /end | Hello::Controller::Root | end |
acbd7bdd 224 | /index | Hello::Controller::Root | index |
d442cc9f 225 '----------------------+--------------------------------------+--------------'
865d3efb 227 [debug] Loaded Path actions:
228 .-------------------------------------+--------------------------------------.
229 | Path | Private |
230 +-------------------------------------+--------------------------------------+
865d3efb 231 | / | /index |
08ae25e9 232 | / | /default |
865d3efb 233 '-------------------------------------+--------------------------------------'
acbd7bdd 234
7a296c6f 235 [info] Hello powered by Catalyst 5.80020
acbd7bdd 236 You can connect to your server at http://debian:3000
d442cc9f 237
1435672d 238Point your web browser to L<http://localhost:3000> (substituting a
d442cc9f 239different hostname or IP address as appropriate) and you should be
acbd7bdd 240greeted by the Catalyst welcome screen (if you get some other welcome
241screen or an "Index" screen, you probably forgot to specify port 3000
242in your URL). Information similar to the following should be appended
243to the logging output of the development server:
3dfcf16a 245 [info] *** Request 1 (0.001/s) [23194] [Sat Jan 16 11:09:18 2010] ***
246 [debug] "GET" request for "/" from ""
247 [debug] Path is "/"
248 [info] Request took 0.004851s (206.143/s)
249 .------------------------------------------------------------+-----------.
250 | Action | Time |
251 +------------------------------------------------------------+-----------+
252 | /index | 0.000395s |
253 | /end | 0.000425s |
254 '------------------------------------------------------------+-----------'
d442cc9f 255
7a296c6f 256B<Note>: Press C<Ctrl-C> to break out of the development server if
d442cc9f 258
3533daff 260=head1 HELLO WORLD
d442cc9f 261
3533daff 262=head2 The Simplest Way
d442cc9f 263
3533daff 264The Root.pm controller is a place to put global actions that usually
265execute on the root URL. Open the C<lib/Hello/Controller/Root.pm> file in
865d3efb 266your editor. You will see the "index" subroutine, which is
3533daff 267responsible for displaying the welcome screen that you just saw in
7a296c6f 268your browser.
d442cc9f 269
865d3efb 270 sub index :Path :Args(0) {
3533daff 271 my ( $self, $c ) = @_;
865d3efb 272
273 # Hello World
3533daff 274 $c->response->body( $c->welcome_message );
d442cc9f 275 }
7a296c6f 277Later on you'll want to change that to something more reasonable, such
278as a "404" message or a redirect, but for now just leave it alone.
3533daff 280The "C<$c>" here refers to the Catalyst context, which is used to
281access the Catalyst application. In addition to many other things,
282the Catalyst context provides access to "response" and "request"
d0496197 283objects. (See L<Catalyst|Catalyst>,
284L<Catalyst::Response|Catalyst::Response>, and
d442cc9f 286
14e5ed66 287C<$c-E<gt>response-E<gt>body> sets the HTTP response (see
7a296c6f 288L<Catalyst::Response|Catalyst::Response>), while
289C<$c-E<gt>welcome_message> is a special method that returns the
290welcome message that you saw in your browser.
d442cc9f 291
444d6b27 292The ":Path :Args(0)" after the method name are attributes which
293determine which URLs will be dispatched to this method. (You might see
294":Private" if you are using an older version of Catalyst, but using
7a296c6f 295that with "default" or "index" is currently deprecated. If so, you
444d6b27 296should also probably upgrade before continuing the tutorial.)
d442cc9f 297
3533daff 298Some MVC frameworks handle dispatching in a central place. Catalyst,
299by policy, prefers to handle URL dispatching with attributes on
300controller methods. There is a lot of flexibility in specifying which
301URLs to match. This particular method will match all URLs, because it
865d3efb 302doesn't specify the path (nothing comes after "Path"), but will only
444d6b27 303accept a URL without any args because of the ":Args(0)".
d442cc9f 304
444d6b27 305The default is to map URLs to controller names, and because of the way
306that Perl handles namespaces through package names, it is simple to
307create hierarchical structures in Catalyst. This means that you can
308create controllers with deeply nested actions in a clean and logical
309way. For example, the URL C<http://hello.com/admin/articles/create>
310maps to the package C<Hello::Controller::Admin::Articles>, and the
311C<create> method.
d442cc9f 312
d0496197 313Add the following subroutine to your C<lib/Hello/Controller/Root.pm>
d442cc9f 315
3d0b2e0b 316 sub hello :Global {
3533daff 317 my ( $self, $c ) = @_;
d0496197 318
3533daff 319 $c->response->body("Hello, World!");
320 }
d442cc9f 321
acbd7bdd 322B<TIP>: See Appendix 1 for tips on removing the leading spaces when
323cutting and pasting example code from POD-based documents.
3533daff 325Here you're sending your own string to the webpage.
e7cfb0cc 327Save the file, and you should notice the following in your server output:
3533daff 328
e7cfb0cc 329 Saw changes to the following files:
7a296c6f 330 - /home/me/Hello/lib/Hello/Controller/Root.pm (modify)
e7cfb0cc 331
332 Attempting to restart the server
0ed3df53 333 ...
e7cfb0cc 334 [debug] Loaded Private actions:
335 .----------------------+--------------------------------------+--------------.
336 | Private | Class | Method |
337 +----------------------+--------------------------------------+--------------+
338 | /default | Hello::Controller::Root | default |
339 | /end | Hello::Controller::Root | end |
340 | /index | Hello::Controller::Root | index |
341 | /hello | Hello::Controller::Root | hello |
342 '----------------------+--------------------------------------+--------------'
344 [debug] Loaded Path actions:
345 .-------------------------------------+--------------------------------------.
346 | Path | Private |
347 +-------------------------------------+--------------------------------------+
348 | / | /index |
349 | / | /default |
350 | /hello | /hello |
351 '-------------------------------------+--------------------------------------'
352 ...
7a296c6f 354Go to L<http://localhost:3000/hello> to see "Hello, World!". Also
355notice that the newly defined 'hello' action is listed under "Loaded
356Private actions" in the development server debug output.
865d3efb 358
3533daff 359=head2 Hello, World! Using a View and a Template
444d6b27 361In the Catalyst world a "View" itself is not a page of XHTML or a
362template designed to present a page to a browser. Rather, it is the
363module that determines the I<type> of view -- HTML, pdf, XML, etc. For
364the thing that generates the I<content> of that view (such as the a
365Toolkit Template template file), the actual templates go under the
865d3efb 366"root" directory.
3533daff 367
368To create a TT view, run:
1edbdee6 370 $ script/hello_create.pl view HTML TT
3533daff 371
1edbdee6 372This creates the C<lib/Hello/View/HTML.pm> module, which is a subclass of
1435672d 373C<Catalyst::View::TT>.
375=over 4
377=item *
379The "view" keyword tells the create script that you are creating a view.
381=item *
1edbdee6 383The first argument "HTML" tells the script to name the View module "HTML.pm",
384which is a commonly used name for TT views. You can name it anything you want,
385such as "MyView.pm". If you have more than one view, be sure to set the
386default_view in Hello.pm (See L<Catalyst::View::TT|Catalyst::View::TT> for more
387details on setting this).
1435672d 388
389=item *
444d6b27 391The final "TT" tells Catalyst the I<type> of the view, with "TT"
392indicating that you want to a Template Toolkit view.
1435672d 393
1edbdee6 396If you look at C<lib/Hello/View/HTML.pm> you will find that it only
444d6b27 397contains a config statement to set the TT extension to ".tt".
3533daff 398
1edbdee6 399Now that the HTML.pm "View" exists, Catalyst will autodiscover it and be
444d6b27 400able to use it to display the view templates using the "process"
7a296c6f 401method that it inherits from the C<Catalyst::View::TT> class.
3533daff 402
c010ae0d 403Template Toolkit is a very full featured template facility, with
865d3efb 404excellent documentation at L<http://template-toolkit.org/>,
3533daff 405but since this is not a TT tutorial, we'll stick to only basic TT
406usage here (and explore some of the more common TT features in later
4b4d3884 407chapters of the tutorial).
3533daff 408
409Create a C<root/hello.tt> template file (put it in the C<root> under
410the C<Hello> directory that is the base of your application). Here is
411a simple sample:
af0a93cf 412
3533daff 413 <p>
1435672d 414 This is a TT view template, called '[% template.name %]'.
3533daff 415 </p>
417[% and %] are markers for the TT parts of the template. Inside you can
1435672d 418access Perl variables and classes, and use TT directives. In this
419case, we're using a special TT variable that defines the name of the
420template file (C<hello.tt>). The rest of the template is normal HTML.
422Change the hello method in C<lib/Hello/Controller/Root.pm> to the
3533daff 424
3d0b2e0b 425 sub hello :Global {
3533daff 426 my ( $self, $c ) = @_;
d0496197 427
61cb69fd 428 $c->stash(template => 'hello.tt');
3533daff 429 }
d442cc9f 430
444d6b27 431This time, instead of doing C<$c-E<gt>response-E<gt>body()>, you are
432setting the value of the "template" hash key in the Catalyst "stash",
433an area for putting information to share with other parts of your
434application. The "template" key determines which template will be
435displayed at the end of the request cycle. Catalyst controllers have a
436default "end" action for all methods which causes the first (or
437default) view to be rendered (unless there's a C<$c-E<gt>response-
438E<gt>body()> statement). So your template will be magically displayed
439at the end of your method.
d442cc9f 440
7a296c6f 441After saving the file, the development server should automatically
442restart (again, the tutorial is written to assume that you are
443using the "-r" option -- manually restart it if you aren't),
444and look at L<http://localhost:3000/hello> in your again. You
445should see the template that you just made.
af0a93cf 447B<TIP:> If you keep the server running with "-r" in a "background
448window," don't let that window get totally hidden... if you have an
449syntax error in your code, the debug server output will contain the
450error information.
ddfbd850 452B<Note:> You will probably run into a variation of the "stash"
453statement above that looks like:
455 $c->stash->{template} = 'hello.tt';
457Although this style is still relatively common, the approach we
458used previous is becoming more common because it allows you to
459set multiple stash variables in one line. For example:
461 $c->stash(template => 'hello.tt', foo => 'bar',
462 another_thing => 1);
464You can also set multiple stash values with a hashref:
466 $c->stash({template => 'hello.tt', foo => 'bar',
467 another_thing => 1});
469Any of these formats work, but the C<$c-E<gt>stash(name =E<gt> value);>
470style is growing in popularity -- you may wish to use it all the
471time (even when you are only setting a single value).
7a296c6f 473
d442cc9f 475
3533daff 476Create a controller named "Site" by executing the create script:
d442cc9f 477
3533daff 478 $ script/hello_create.pl controller Site
d442cc9f 479
3533daff 480This will create a C<lib/Hello/Controller/Site.pm> file (and a test
481file). Bring Site.pm up in your editor, and you can see that there's
444d6b27 482not much there.
d442cc9f 483
d0496197 484In C<lib/Hello/Controller/Site.pm>, add the following method:
d442cc9f 485
3d0b2e0b 486 sub test :Local {
3533daff 487 my ( $self, $c ) = @_;
d0496197 488
7a296c6f 489 $c->stash(username => 'John',
0ed3df53 490 template => 'site/test.tt');
d442cc9f 491 }
1435672d 493Notice the "Local" attribute on the C<test> method. This will cause
444d6b27 494the C<test> action (now that we have assigned an "action type" to the
495method it appears as a "controller action" to Catalyst) to be executed
1435672d 496on the "controller/method" URL, or, in this case, "site/test". We
497will see additional information on controller actions throughout the
498rest of the tutorial, but if you are curious take a look at
501It's not actually necessary to set the template value as we do here.
502By default TT will attempt to render a template that follows the
503naming pattern "controller/method.tt", and we're following that
504pattern here. However, in other situations you will need to specify
505the template (such as if you've "forwarded" to the method, or if it
506doesn't follow the default naming convention).
508We've also put the variable "username" into the stash, for use in the
d442cc9f 510
3533daff 511Make a subdirectory "site" in the "root" directory. Copy the hello.tt
d0496197 512file into the directory as C<root/site/test.tt>, or create a new
513template file at that location. Include a line like:
d442cc9f 514
d0496197 515 <p>Hello, [% username %]!</p>
d442cc9f 516
3533daff 517You should see your test.tt file displayed, including the name "John"
518that you set in the controller.
d442cc9f 519
7a296c6f 520Once the server automatically restarts, notice in the server
521output that C</site/test> is listed in the Loaded Path actions.
522Go to L<http://localhost:3000/site/test> in your browser.
d442cc9f 524
3533daff 525=head1 AUTHORS
d442cc9f 526
3533daff 527Gerda Shank, C<gerda.shank@gmail.com>
d442cc9f 528Kennedy Clark, C<hkclark@gmail.com>
530Please report any errors, issues or suggestions to the author. The
531most recent version of the Catalyst Tutorial can be found at
59884771 532L<http://dev.catalyst.perl.org/repos/Catalyst/Catalyst-Manual/5.80/trunk/lib/Catalyst/Manual/Tutorial/>.
d442cc9f 533
4768184b 534Copyright 2006-2010, Kennedy Clark, under Creative Commons License
865d3efb 535(L<http://creativecommons.org/licenses/by-sa/3.0/us/>).