yaml expurgation and placeholders for a couple of upcoming tutorial articles
[catagits/Catalyst-Manual.git] / lib / Catalyst / Manual / Tutorial / CatalystBasics.pod
1 =head1 NAME
2
3 Catalyst::Manual::Tutorial::CatalystBasics - Catalyst Tutorial - Part 2: Catalyst Application Development Basics
4
5
6 =head1 OVERVIEW
7
8 This is B<Part 2 of 10> for the Catalyst tutorial.
9
10 L<Tutorial Overview|Catalyst::Manual::Tutorial>
11
12 =over 4
13
14 =item 1
15
16 L<Introduction|Catalyst::Manual::Tutorial::Intro>
17
18 =item 2
19
20 B<Catalyst Basics>
21
22 =item 3
23
24 L<More Catalyst Basics|Catalyst::Manual::Tutorial::MoreCatalystBasics>
25
26 =item 4
27
28 L<Basic CRUD|Catalyst::Manual::Tutorial::BasicCRUD>
29
30 =item 5
31
32 L<Authentication|Catalyst::Manual::Tutorial::Authentication>
33
34 =item 6
35
36 L<Authorization|Catalyst::Manual::Tutorial::Authorization>
37
38 =item 7
39
40 L<Debugging|Catalyst::Manual::Tutorial::Debugging>
41
42 =item 8
43
44 L<Testing|Catalyst::Manual::Tutorial::Testing>
45
46 =item 9
47
48 L<Advanced CRUD|Catalyst::Manual::Tutorial::AdvancedCRUD>
49
50 =item 10
51
52 L<Appendices|Catalyst::Manual::Tutorial::Appendices>
53
54 =back
55
56
57 =head1 DESCRIPTION
58
59 In this part of the tutorial, we will create a very basic Catalyst web 
60 application, demonstrating a number of powerful capabilities, such as:
61
62 =over 4
63
64 =item * Helper Scripts
65
66 Catalyst helper scripts that can be used to rapidly bootstrap the
67 skeletal structure of an application.
68
69 =item * MVC
70
71 Model/View/Controller (MVC) provides an architecture that facilitates a
72 clean "separation of control" between the different portions of your
73 application. Given that many other documents cover this subject in
74 detail, MVC will not be discussed in depth here (for an excellent
75 introduction to MVC and general Catalyst concepts, please see
76 L<Catalyst::Manual::About>. In short:
77
78 =over 4
79
80 =item * Model
81
82 The model usually represents a data store. In most applications, the
83 model equates to the objects that are created from and saved to your SQL
84 database.
85
86 =item * View
87
88 The view takes model objects and renders them into something for the end
89 user to look at. Normally this involves a template-generation tool that
90 creates HTML for the user's web browser, but it could easily be code
91 that generates other forms such as PDF documents, e-mails, or Excel
92 spreadsheets.
93
94 =item * Controller
95
96 As suggested by its name, the controller takes user requests and routes
97 them to the necessary model and view.
98
99 =back
100
101 =item * ORM
102
103 The use of Object-Relational Mapping (ORM) technology for database
104 access. Specifically, ORM provides an automated and standardized means
105 to persist and restore objects to/from a relational database.
106
107 =back
108
109 You can checkout the source code for this example from the catalyst
110 subversion repository as per the instructions in
111 L<Catalyst::Manual::Tutorial::Intro>
112
113
114 =head1 CREATE A CATALYST PROJECT
115
116 Catalyst provides a number of helper scripts that can be used to 
117 quickly flesh out the basic structure of your application. All 
118 Catalyst projects begin with the C<catalyst.pl> helper (see 
119 L<Catalyst::Helper|Catalyst::Helper> for more information on helpers). 
120 Also note that as of Catalyst 5.7000, you will not have the helper 
121 scripts unless you install both L<Catalyst::Runtime|Catalyst::Runtime> 
122 and L<Catalyst::Devel|Catalyst::Devel>.
123
124 In this first part of the tutorial, use the Catalyst 
125 C<catalyst.pl> script to initialize the framework for an 
126 application called C<Hello>:
127
128     $ catalyst.pl Hello
129     created "Hello"
130     created "Hello/script"
131     created "Hello/lib"
132     created "Hello/root"
133     ...
134     created "Hello/script/hello_create.pl"
135     $ cd Hello
136
137 The C<catalyst.pl> helper script will display the names of the
138 directories and files it creates:
139
140     Changes               # Record of application changes
141     lib                   # Lib directory for Perl modules
142         Hello             # Application code directory
143             Controller    # Directory for Controller modules 
144             Model         # Directory for Models
145             View          # Directory for Views
146         Hello.pm          # Base application module
147     Makefile.PL           # Makefile to build application
148     hello.yml             # Application configuration file
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         hello_cgi.pl      # To run your app as a cgi (not recommended)
156         hello_create.pl   # To create models, views, controllers
157         hello_fastcgi.pl  # To run app as a fastcgi program
158         hello_server.pl   # The normal development server
159         hello_test.pl     # Test your app from the command line
160     t                     # Directory for tests
161         01app.t           # Test scaffold       
162         02pod.t           
163         03podcoverage.t 
164
165
166 Catalyst will "auto-discover" modules in the Controller, Model, and 
167 View directories. When you use the hello_create.pl script it will 
168 create Perl module scaffolds in those directories, plus test files in 
169 the "t" directory. The default location for templates is in the "root" 
170 directory. The scripts in the script directory will always start with 
171 the lowercased version of your application name. If your app is 
172 MaiTai, then the create script would be "maitai_create.pl".
173
174 Though it's too early for any significant celebration, we already have 
175 a functioning application. We can use the Catalyst supplied script to 
176 start up a development server and view the default Catalyst page in 
177 your browser. All scripts in the script directory should be run from 
178 the base directory of your application, so change to the Hello 
179 directory.
180
181 Run the following command to start up the built-in development web 
182 server:
183
184     $ script/hello_server.pl
185     [debug] Debug messages enabled
186     [debug] Loaded plugins:
187     .----------------------------------------------------------------------------.
188     | Catalyst::Plugin::ConfigLoader  0.17                                       |
189     | Catalyst::Plugin::Static::Simple  0.20                                     |
190     '----------------------------------------------------------------------------'
191     
192     [debug] Loaded dispatcher "Catalyst::Dispatcher"
193     [debug] Loaded engine "Catalyst::Engine::HTTP"
194     [debug] Found home "/home/me/Hello"
195     [debug] Loaded Config "/home/me/Hello/hello.yml"
196     [debug] Loaded components:
197     .-----------------------------------------------------------------+----------.
198     | Class                                                           | Type     |
199     +-----------------------------------------------------------------+----------+
200     | Hello::Controller::Root                                         | instance |
201     '-----------------------------------------------------------------+----------'
202     
203     [debug] Loaded Private actions:
204     .----------------------+--------------------------------------+--------------.
205     | Private              | Class                                | Method       |
206     +----------------------+--------------------------------------+--------------+
207     | /default             | Hello::Controller::Root              | default      |
208     | /end                 | Hello::Controller::Root              | end          |
209     '----------------------+--------------------------------------+--------------'
210     
211     [info] Hello powered by Catalyst 5.7011
212     You can connect to your server at http://localhost:3000
213
214 Point your web browser to 
215 L<http://localhost:3000|http://localhost:3000> (substituting a 
216 different hostname or IP address as appropriate) and you should be 
217 greeted by the Catalyst welcome screen.  Information similar to the 
218 following should be appended to the logging output of the development 
219 server:
220
221     [info] *** Request 1 (1.000/s) [10301] [Sun May 18 10:11:36 2008] ***
222     [debug] "GET" request for "/" from "127.0.0.1"
223     [info] Request took 0.017964s (55.667/s)
224     .----------------------------------------------------------------+-----------.
225     | Action                                                         | Time      |
226     +----------------------------------------------------------------+-----------+
227     | /default                                                       | 0.000540s |
228     | /end                                                           | 0.001246s |
229     '----------------------------------------------------------------+-----------'
230
231 Press Ctrl-C to break out of the development server.
232
233
234 =head1 HELLO WORLD
235
236 =head2 The Simplest Way
237
238 The Root.pm controller is a place to put global actions that usually 
239 execute on the root URL. Open the C<lib/Hello/Controller/Root.pm> file in 
240 your editor. You will see the "default" subroutine, which is 
241 responsible for displaying the welcome screen that you just saw in 
242 your browser. Later on you'll want to change that to something more 
243 reasonable, such as a "404" message but for now just leave it alone.
244
245     sub default : Path : Args {
246         my ( $self, $c ) = @_;
247
248         $c->response->body( $c->welcome_message );
249     }
250
251 The "C<$c>" here refers to the Catalyst context, which is used to 
252 access the Catalyst application. In addition to many other things, 
253 the Catalyst context provides access to "response" and "request" 
254 objects. (See L<Catalyst>, L<Catalyst::Response>, and L<Catalyst::Request>) 
255
256 C<$c->response->body> sets the HTTP response (see 
257 L<Catalyst::Response>), while C<$c->welcome_message> is a special method 
258 that returns the welcome message that you saw in your browser.
259
260 The ": Path : Args" after the method name are attributes which determine 
261 which URLs will be dispatched to this method. (Depending on your version of 
262 Catalyst, it used to say "Private" but using that with default is 
263 currently deprecated.)
264
265 Some MVC frameworks handle dispatching in a central place. Catalyst, 
266 by policy, prefers to handle URL dispatching with attributes on 
267 controller methods. There is a lot of flexibility in specifying which 
268 URLs to match.  This particular method will match all URLs, because it 
269 doesn't specify the path (nothing comes after "Path"), and will accept 
270 any number of args (nothing after args). 
271
272 The default is to map URLs to controller names, and because of 
273 the way that Perl handles namespaces through package names, 
274 it is simple to create hierarchical structures in 
275 Catalyst. This means that you can create controllers with deeply 
276 nested actions in a clean and logical way. 
277
278 For example, the URL C<http://hello.com/admin/articles/create> maps 
279 to the package C<Hello::Controller::Admin::Articles>, and the C<create>
280 method. 
281
282
283 Add the following subroutine to your Root.pm file:
284
285     sub hello : Global {
286         my ( $self, $c ) = @_;
287         $c->response->body("Hello, World!");
288     }
289
290 Here you're sending your own string to the webpage.
291
292 Save the file, start the server (stop and restart it if it's still 
293 up), and go to L<http://localhost:3000/hello|http://localhost:3000> to 
294 see "Hello, World!"
295
296 =head2 Hello, World! Using a View and a Template
297
298 In the Catalyst world  a "View" is not a page of XHTML or a template 
299 designed to present a page to a browser. It is the module that 
300 determines the type of view--HTML, pdf, XML. For the case of a 
301 template view (such as the default Toolkit Template) the actual 
302 templates go under the "root" directory.
303
304 To create a TT view, run:
305
306     $ script/hello_create.pl view TT TT
307
308 This creates the C<lib/Hello/View/TT.pm> module, which is a subclass of 
309 C<Catalyst::View::TT>. The "view" keyword tells the create script that 
310 you are creating a view, the first "TT" tells it that you are creating 
311 a Template Toolkit view, and the second "TT" tells the script to name 
312 the View module "TT.pm", which is a commonly used name for TT views. 
313 (You can name it anything you want, such as "HTML.pm".) If you look at 
314 TT.pm, you will find that it only contains a config statement to set 
315 the TT extension to ".tt".
316
317 Now that the TT.pm "View" exists, Catalyst will autodiscover it and be 
318 able to use it to display the view templates, using the "process" 
319 method that it inherits from the C<Catalyst::View::TT class>.
320
321 Template Toolkit is a very full featured template facility, with 
322 excellent documentation at 
323 L<http://template-tookit.org/|http://template-tookit.org/>, 
324 but since this is not a TT tutorial, we'll stick to only basic TT 
325 usage here (and explore some of the more common TT features in later 
326 parts of the tutorial).
327
328 Create a C<root/hello.tt> template file (put it in the C<root> under 
329 the C<Hello> directory that is the base of your application). Here is 
330 a simple sample:
331   
332     [% META title = 'Hello, World!' %]
333     <p>
334         This is a TT view template, located in the root directory.
335     </p>
336
337 [% and %] are markers for the TT parts of the template. Inside you can 
338 access Perl variables and classes, and use TT directives. The rest of 
339 the template is normal HTML. Change the hello method in Root.pm to the 
340 following:
341
342     sub hello : Global {
343         my ( $self, $c ) = @_;
344         $c->stash->{template} = 'hello.tt';
345     }
346
347 This time, instead of doing C<$c->response->body()>, you are setting 
348 the value of the "template" hash key in the Catalyst "stash", an area 
349 for putting information to share with other parts of your application. 
350 The "template" key determines which template will be displayed at the 
351 end of the method. Catalyst controllers have a default "end" action 
352 for all methods which causes the first (or default) view to be 
353 rendered (unless there's a C<$c->response->body()> statement). So your 
354 template will be magically displayed at the end of your method.
355
356 After saving the file, restart the development server, and look at 
357 L<http://localhost:3000/hello|http://localhost:3000> again. You should 
358 see the template that you just made.
359
360
361 =head1 CREATE A SIMPLE CONTROLLER AND AN ACTION
362
363 Create a controller named "Site" by executing the create script:
364
365     $ script/hello_create.pl controller Site
366
367 This will create a C<lib/Hello/Controller/Site.pm> file (and a test 
368 file). Bring Site.pm up in your editor, and you can see that there's 
369 not much there. Most people probably don't bother to use the create 
370 script to make controllers after they're used to using Catalyst.
371
372 In Site.pm, add the following method:
373
374     sub test : Local {
375         my ( $self, $c ) = @_;
376         $c->stash->{username} = "John";
377         $c->stash->{template} = 'site/test.tt';
378     }
379
380 Notice the "Local" attribute on the method. This will allow the action 
381 to be executed on the "controller/method" URL, or, in this case, 
382 "site/test", instead of at the root site URL, like "Global". It's not 
383 actually necessary to set the template value, since by default TT will 
384 attempt to render a template that follows the naming pattern 
385 "controller/method.tt", and we're following that pattern here, but in 
386 other situations you will need to specify the template (such as if 
387 you've "forwarded" to the method, or if it doesn't follow the default 
388 naming convention). We've also put the variable "name" into the stash, 
389 for use in the template.
390
391 Make a subdirectory "site" in the "root" directory. Copy the hello.tt 
392 file into the directory as root/site/test.tt, or create a new template 
393 file at that location. Include a line like: 
394
395     <p>Hello, [% username %]!</p> 
396
397 Bring up or restart the server.  Notice in the server output that 
398 C</site/test> is listed in the Loaded Path actions. Go to 
399 L<http://localhost:3000/site/test|http://localhosst:3000/site/test> 
400
401 You should see your test.tt file displayed, including the name "John"
402 that you set in the controller.
403
404
405 =head1 AUTHORS
406
407 Gerda Shank, C<gerda.shank@gmail.com>
408 Kennedy Clark, C<hkclark@gmail.com>
409
410 Please report any errors, issues or suggestions to the author.  The
411 most recent version of the Catalyst Tutorial can be found at
412 L<http://dev.catalyst.perl.org/repos/Catalyst/trunk/Catalyst-Manual/lib/Catalyst/Manual/Tutorial/>.
413
414 Copyright 2006, Kennedy Clark & Gerda Shank, under Creative Commons License
415 (L<http://creativecommons.org/licenses/by-nc-sa/2.5/>).