Merge from depluralization branch
[catagits/Catalyst-Manual.git] / lib / Catalyst / Manual / Tutorial / CatalystBasics.pod
d442cc9f 1=head1 NAME
4b4d3884 3Catalyst::Manual::Tutorial::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
18=item 2
20B<Catalyst Basics>
22=item 3
3533daff 24L<More Catalyst Basics|Catalyst::Manual::Tutorial::MoreCatalystBasics>
d442cc9f 25
26=item 4
3533daff 28L<Basic CRUD|Catalyst::Manual::Tutorial::BasicCRUD>
d442cc9f 29
30=item 5
3533daff 32L<Authentication|Catalyst::Manual::Tutorial::Authentication>
d442cc9f 33
34=item 6
3533daff 36L<Authorization|Catalyst::Manual::Tutorial::Authorization>
d442cc9f 37
38=item 7
3533daff 40L<Debugging|Catalyst::Manual::Tutorial::Debugging>
d442cc9f 41
42=item 8
3533daff 44L<Testing|Catalyst::Manual::Tutorial::Testing>
d442cc9f 45
46=item 9
3533daff 48L<Advanced CRUD|Catalyst::Manual::Tutorial::AdvancedCRUD>
50=item 10
d442cc9f 52L<Appendices|Catalyst::Manual::Tutorial::Appendices>
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
106to persist and restore objects to/from a relational database.
110You can checkout the source code for this example from the catalyst
111subversion repository as per the instructions in
1390ef0e 112L<Catalyst::Manual::Tutorial::Intro|Catalyst::Manual::Tutorial::Intro>.
d442cc9f 113
3533daff 114
d442cc9f 115=head1 CREATE A CATALYST PROJECT
3533daff 117Catalyst provides a number of helper scripts that can be used to
118quickly flesh out the basic structure of your application. All
119Catalyst projects begin with the C<> helper (see
120L<Catalyst::Helper|Catalyst::Helper> for more information on helpers).
121Also note that as of Catalyst 5.7000, you will not have the helper
122scripts unless you install both L<Catalyst::Runtime|Catalyst::Runtime>
123and L<Catalyst::Devel|Catalyst::Devel>.
4b4d3884 125In this first chapter of the tutorial, use the Catalyst C<>
126script to initialize the framework for an application called C<Hello>:
3533daff 127
128 $ Hello
129 created "Hello"
130 created "Hello/script"
131 created "Hello/lib"
132 created "Hello/root"
d442cc9f 133 ...
3533daff 134 created "Hello/script/"
135 $ cd Hello
d442cc9f 136
137The C<> helper script will display the names of the
3533daff 138directories and files it creates:
140 Changes # Record of application changes
865d3efb 141 lib # Lib directory for your app's Perl modules
142 Hello # Application main code directory
3533daff 143 Controller # Directory for Controller modules
144 Model # Directory for Models
145 View # Directory for Views
146 # Base application module
147 Makefile.PL # Makefile to build application
45d511e0 148 hello.conf # Application configuration file
3533daff 149 README # README file
150 root # Equiv of htdocs, dir for templates, css, javascript
151 favicon.ico
152 static # Directory for static files
153 images # Directory for image files used in welcome screen
154 script # Directory for Perl scripts
155 # To run your app as a cgi (not recommended)
156 # To create models, views, controllers
157 # To run app as a fastcgi program
158 # The normal development server
159 # Test your app from the command line
160 t # Directory for tests
161 01app.t # Test scaffold
162 02pod.t
163 03podcoverage.t
166Catalyst will "auto-discover" modules in the Controller, Model, and
167View directories. When you use the script it will
168create Perl module scaffolds in those directories, plus test files in
169the "t" directory. The default location for templates is in the "root"
170directory. The scripts in the script directory will always start with
171the lowercased version of your application name. If your app is
172MaiTai, then the create script would be "".
174Though it's too early for any significant celebration, we already have
175a functioning application. We can use the Catalyst supplied script to
176start up a development server and view the default Catalyst page in
177your browser. All scripts in the script directory should be run from
178the base directory of your application, so change to the Hello
181Run the following command to start up the built-in development web
acbd7bdd 182server (make sure you didn't forget the "C<cd Hello>" from the
183previous step):
d442cc9f 184
3533daff 185 $ script/
d442cc9f 186 [debug] Debug messages enabled
865d3efb 187 [debug] Statistics enabled
d442cc9f 188 [debug] Loaded plugins:
189 .----------------------------------------------------------------------------.
865d3efb 190 | Catalyst::Plugin::ConfigLoader 0.20 |
3533daff 191 | Catalyst::Plugin::Static::Simple 0.20 |
d442cc9f 192 '----------------------------------------------------------------------------'
194 [debug] Loaded dispatcher "Catalyst::Dispatcher"
195 [debug] Loaded engine "Catalyst::Engine::HTTP"
3533daff 196 [debug] Found home "/home/me/Hello"
e13f83cc 197 [debug] Loaded Config "/home/me/Hello/hello.conf"
d442cc9f 198 [debug] Loaded components:
199 .-----------------------------------------------------------------+----------.
200 | Class | Type |
201 +-----------------------------------------------------------------+----------+
3533daff 202 | Hello::Controller::Root | instance |
d442cc9f 203 '-----------------------------------------------------------------+----------'
205 [debug] Loaded Private actions:
206 .----------------------+--------------------------------------+--------------.
207 | Private | Class | Method |
208 +----------------------+--------------------------------------+--------------+
3533daff 209 | /default | Hello::Controller::Root | default |
210 | /end | Hello::Controller::Root | end |
acbd7bdd 211 | /index | Hello::Controller::Root | index |
d442cc9f 212 '----------------------+--------------------------------------+--------------'
865d3efb 214 [debug] Loaded Path actions:
215 .-------------------------------------+--------------------------------------.
216 | Path | Private |
217 +-------------------------------------+--------------------------------------+
218 | / | /default |
219 | / | /index |
220 '-------------------------------------+--------------------------------------'
acbd7bdd 221
3b1fa91b 222 [info] Hello powered by Catalyst 5.80003
acbd7bdd 223 You can connect to your server at http://debian:3000
d442cc9f 224
1435672d 225Point your web browser to L<http://localhost:3000> (substituting a
d442cc9f 226different hostname or IP address as appropriate) and you should be
acbd7bdd 227greeted by the Catalyst welcome screen (if you get some other welcome
228screen or an "Index" screen, you probably forgot to specify port 3000
229in your URL). Information similar to the following should be appended
230to the logging output of the development server:
232 [info] *** Request 1 (0.005/s) [20712] [Sun Mar 8 15:49:09 2009] ***
233 [debug] "GET" request for "/" from ""
234 [info] Request took 0.007342s (136.203/s)
d442cc9f 235 .----------------------------------------------------------------+-----------.
236 | Action | Time |
237 +----------------------------------------------------------------+-----------+
acbd7bdd 238 | /index | 0.000491s |
239 | /end | 0.000595s |
d442cc9f 240 '----------------------------------------------------------------+-----------'
242Press Ctrl-C to break out of the development server.
3533daff 245=head1 HELLO WORLD
d442cc9f 246
3533daff 247=head2 The Simplest Way
d442cc9f 248
3533daff 249The controller is a place to put global actions that usually
250execute on the root URL. Open the C<lib/Hello/Controller/> file in
865d3efb 251your editor. You will see the "index" subroutine, which is
3533daff 252responsible for displaying the welcome screen that you just saw in
253your browser. Later on you'll want to change that to something more
865d3efb 254reasonable, such as a "404" message or a redirect, but for now just
255leave it alone.
d442cc9f 256
865d3efb 257 sub index :Path :Args(0) {
3533daff 258 my ( $self, $c ) = @_;
865d3efb 259
260 # Hello World
3533daff 261 $c->response->body( $c->welcome_message );
d442cc9f 262 }
3533daff 264The "C<$c>" here refers to the Catalyst context, which is used to
265access the Catalyst application. In addition to many other things,
266the Catalyst context provides access to "response" and "request"
d0496197 267objects. (See L<Catalyst|Catalyst>,
268L<Catalyst::Response|Catalyst::Response>, and
d442cc9f 270
14e5ed66 271C<$c-E<gt>response-E<gt>body> sets the HTTP response (see
272L<Catalyst::Response|Catalyst::Response>), while C<$c-E<gt>welcome_message>
d0496197 273is a special method that returns the welcome message that you saw in
274your browser.
d442cc9f 275
865d3efb 276The ":Path :Args(0)" after the method name are attributes which determine
3533daff 277which URLs will be dispatched to this method. (Depending on your version of
865d3efb 278Catalyst, it used to say "Private" but using that with 'default' or 'index'
279is currently deprecated.)
d442cc9f 280
3533daff 281Some MVC frameworks handle dispatching in a central place. Catalyst,
282by policy, prefers to handle URL dispatching with attributes on
283controller methods. There is a lot of flexibility in specifying which
284URLs to match. This particular method will match all URLs, because it
865d3efb 285doesn't specify the path (nothing comes after "Path"), but will only
286accept a single args because of the ":Args(0)".
d442cc9f 287
3533daff 288The default is to map URLs to controller names, and because of
289the way that Perl handles namespaces through package names,
290it is simple to create hierarchical structures in
291Catalyst. This means that you can create controllers with deeply
292nested actions in a clean and logical way.
d442cc9f 293
3533daff 294For example, the URL C<> maps
295to the package C<Hello::Controller::Admin::Articles>, and the C<create>
d442cc9f 297
d0496197 298Add the following subroutine to your C<lib/Hello/Controller/>
d442cc9f 300
3533daff 301 sub hello : Global {
302 my ( $self, $c ) = @_;
d0496197 303
3533daff 304 $c->response->body("Hello, World!");
305 }
d442cc9f 306
acbd7bdd 307B<TIP>: See Appendix 1 for tips on removing the leading spaces when
308cutting and pasting example code from POD-based documents.
3533daff 310Here you're sending your own string to the webpage.
312Save the file, start the server (stop and restart it if it's still
d0496197 313up), and go to L<http://localhost:3000/hello> to
3533daff 314see "Hello, World!"
865d3efb 316
3533daff 317=head2 Hello, World! Using a View and a Template
319In the Catalyst world a "View" is not a page of XHTML or a template
320designed to present a page to a browser. It is the module that
865d3efb 321determines the I<type> of view -- HTML, pdf, XML, etc. For the
322thing that generates the I<content> of that view, (such as the
323default Toolkit Template) the actual templates go under the
324"root" directory.
3533daff 325
326To create a TT view, run:
328 $ script/ view TT TT
330This creates the C<lib/Hello/View/> module, which is a subclass of
1435672d 331C<Catalyst::View::TT>.
333=over 4
335=item *
337The "view" keyword tells the create script that you are creating a view.
339=item *
341The first "TT" tells the script to name the View module "", which is a
342commonly used name for TT views. (You can name it anything you want, such as
345=item *
347The final "TT" tells it that you are creating a Template Toolkit view.
351If you look at C<lib/Hello/View/> you will find that it only contains a
352config statement to set the TT extension to ".tt".
3533daff 353
354Now that the "View" exists, Catalyst will autodiscover it and be
355able to use it to display the view templates, using the "process"
356method that it inherits from the C<Catalyst::View::TT class>.
c010ae0d 358Template Toolkit is a very full featured template facility, with
865d3efb 359excellent documentation at L<>,
3533daff 360but since this is not a TT tutorial, we'll stick to only basic TT
361usage here (and explore some of the more common TT features in later
4b4d3884 362chapters of the tutorial).
3533daff 363
364Create a C<root/> template file (put it in the C<root> under
365the C<Hello> directory that is the base of your application). Here is
366a simple sample:
3533daff 368 <p>
1435672d 369 This is a TT view template, called '[% %]'.
3533daff 370 </p>
372[% and %] are markers for the TT parts of the template. Inside you can
1435672d 373access Perl variables and classes, and use TT directives. In this
374case, we're using a special TT variable that defines the name of the
375template file (C<>). The rest of the template is normal HTML.
377Change the hello method in C<lib/Hello/Controller/> to the
3533daff 379
380 sub hello : Global {
381 my ( $self, $c ) = @_;
d0496197 382
3533daff 383 $c->stash->{template} = '';
384 }
d442cc9f 385
1435672d 386This time, instead of doing C<$c-E<gt>response-E<gt>body()>, you are setting
3533daff 387the value of the "template" hash key in the Catalyst "stash", an area
388for putting information to share with other parts of your application.
389The "template" key determines which template will be displayed at the
390end of the method. Catalyst controllers have a default "end" action
391for all methods which causes the first (or default) view to be
1435672d 392rendered (unless there's a C<$c-E<gt>response-E<gt>body()> statement). So your
3533daff 393template will be magically displayed at the end of your method.
d442cc9f 394
3533daff 395After saving the file, restart the development server, and look at
d0496197 396L<http://localhost:3000/hello> again. You should
3533daff 397see the template that you just made.
d442cc9f 398
d442cc9f 399
d442cc9f 401
3533daff 402Create a controller named "Site" by executing the create script:
d442cc9f 403
3533daff 404 $ script/ controller Site
d442cc9f 405
3533daff 406This will create a C<lib/Hello/Controller/> file (and a test
407file). Bring up in your editor, and you can see that there's
408not much there. Most people probably don't bother to use the create
409script to make controllers after they're used to using Catalyst.
d442cc9f 410
d0496197 411In C<lib/Hello/Controller/>, add the following method:
d442cc9f 412
3533daff 413 sub test : Local {
414 my ( $self, $c ) = @_;
d0496197 415
3533daff 416 $c->stash->{username} = "John";
417 $c->stash->{template} = 'site/';
d442cc9f 418 }
1435672d 420Notice the "Local" attribute on the C<test> method. This will cause
421the C<test> action (now that we have assigned an action type to the
422method it appears as a controller "action" to Catalyst) to be executed
423on the "controller/method" URL, or, in this case, "site/test". We
424will see additional information on controller actions throughout the
425rest of the tutorial, but if you are curious take a look at
428It's not actually necessary to set the template value as we do here.
429By default TT will attempt to render a template that follows the
430naming pattern "controller/", and we're following that
431pattern here. However, in other situations you will need to specify
432the template (such as if you've "forwarded" to the method, or if it
433doesn't follow the default naming convention).
435We've also put the variable "username" into the stash, for use in the
d442cc9f 437
3533daff 438Make a subdirectory "site" in the "root" directory. Copy the
d0496197 439file into the directory as C<root/site/>, or create a new
440template file at that location. Include a line like:
d442cc9f 441
d0496197 442 <p>Hello, [% username %]!</p>
d442cc9f 443
3533daff 444Bring up or restart the server. Notice in the server output that
445C</site/test> is listed in the Loaded Path actions. Go to
865d3efb 446L<http://localhost:3000/site/test> in your browser.
d442cc9f 447
3533daff 448You should see your file displayed, including the name "John"
449that you set in the controller.
d442cc9f 450
d442cc9f 451
3533daff 452=head1 AUTHORS
d442cc9f 453
3533daff 454Gerda Shank, C<>
d442cc9f 455Kennedy Clark, C<>
457Please report any errors, issues or suggestions to the author. The
458most recent version of the Catalyst Tutorial can be found at
82ab4bbf 459L<>.
d442cc9f 460
45c7830f 461Copyright 2006-2008, Kennedy Clark & Gerda Shank, under Creative Commons License
865d3efb 462(L<>).