3 Catalyst::Manual::Tutorial::CatalystBasics - Catalyst Tutorial - Part 2: Catalyst Application Development Basics
8 This is B<Part 2 of 10> for the Catalyst tutorial.
10 L<Tutorial Overview|Catalyst::Manual::Tutorial>
16 L<Introduction|Catalyst::Manual::Tutorial::Intro>
24 L<More Catalyst Basics|Catalyst::Manual::Tutorial::MoreCatalystBasics>
28 L<Basic CRUD|Catalyst::Manual::Tutorial::BasicCRUD>
32 L<Authentication|Catalyst::Manual::Tutorial::Authentication>
36 L<Authorization|Catalyst::Manual::Tutorial::Authorization>
40 L<Debugging|Catalyst::Manual::Tutorial::Debugging>
44 L<Testing|Catalyst::Manual::Tutorial::Testing>
48 L<Advanced CRUD|Catalyst::Manual::Tutorial::AdvancedCRUD>
52 L<Appendices|Catalyst::Manual::Tutorial::Appendices>
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:
64 =item * Helper Scripts
66 Catalyst helper scripts that can be used to rapidly bootstrap the
67 skeletal structure of an application.
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|Catalyst::Manual::About>). In short:
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
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, spreadsheets,
92 or even "behind the scenes" formats such as XML and JSON.
96 As suggested by its name, the controller takes user requests and routes
97 them to the necessary model and view.
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.
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|Catalyst::Manual::Tutorial::Intro>.
114 =head1 CREATE A CATALYST PROJECT
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>.
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>:
130 created "Hello/script"
134 created "Hello/script/hello_create.pl"
137 The C<catalyst.pl> helper script will display the names of the
138 directories and files it creates:
140 Changes # Record of application changes
141 lib # Lib directory for your app's Perl modules
142 Hello # Application main 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.conf # Application configuration file
150 root # Equiv of htdocs, dir for templates, css, javascript
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
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".
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
181 Run the following command to start up the built-in development web
184 $ script/hello_server.pl
185 [debug] Debug messages enabled
186 [debug] Statistics enabled
187 [debug] Loaded plugins:
188 .----------------------------------------------------------------------------.
189 | Catalyst::Plugin::ConfigLoader 0.20 |
190 | Catalyst::Plugin::Static::Simple 0.20 |
191 '----------------------------------------------------------------------------'
193 [debug] Loaded dispatcher "Catalyst::Dispatcher"
194 [debug] Loaded engine "Catalyst::Engine::HTTP"
195 [debug] Found home "/home/me/Hello"
196 [debug] Loaded Config "/home/me/Hello/hello.conf"
197 [debug] Loaded components:
198 .-----------------------------------------------------------------+----------.
200 +-----------------------------------------------------------------+----------+
201 | Hello::Controller::Root | instance |
202 '-----------------------------------------------------------------+----------'
204 [debug] Loaded Private actions:
205 .----------------------+--------------------------------------+--------------.
206 | Private | Class | Method |
207 +----------------------+--------------------------------------+--------------+
208 | /default | Hello::Controller::Root | default |
209 | /end | Hello::Controller::Root | end |
210 '----------------------+--------------------------------------+--------------'
212 [debug] Loaded Path actions:
213 .-------------------------------------+--------------------------------------.
215 +-------------------------------------+--------------------------------------+
218 '-------------------------------------+--------------------------------------'
220 [info] Hello powered by Catalyst 5.7014
221 You can connect to your server at http://localhost:3000
223 Point your web browser to L<http://localhost:3000> (substituting a
224 different hostname or IP address as appropriate) and you should be
225 greeted by the Catalyst welcome screen. Information similar to the
226 following should be appended to the logging output of the development
229 [info] *** Request 1 (1.000/s) [10301] [Sun Nov 23 10:11:36 2008] ***
230 [debug] "GET" request for "/" from "127.0.0.1"
231 [info] Request took 0.017964s (55.667/s)
232 .----------------------------------------------------------------+-----------.
234 +----------------------------------------------------------------+-----------+
235 | /default | 0.000540s |
237 '----------------------------------------------------------------+-----------'
239 Press Ctrl-C to break out of the development server.
244 =head2 The Simplest Way
246 The Root.pm controller is a place to put global actions that usually
247 execute on the root URL. Open the C<lib/Hello/Controller/Root.pm> file in
248 your editor. You will see the "index" subroutine, which is
249 responsible for displaying the welcome screen that you just saw in
250 your browser. Later on you'll want to change that to something more
251 reasonable, such as a "404" message or a redirect, but for now just
254 sub index :Path :Args(0) {
255 my ( $self, $c ) = @_;
258 $c->response->body( $c->welcome_message );
261 The "C<$c>" here refers to the Catalyst context, which is used to
262 access the Catalyst application. In addition to many other things,
263 the Catalyst context provides access to "response" and "request"
264 objects. (See L<Catalyst|Catalyst>,
265 L<Catalyst::Response|Catalyst::Response>, and
266 L<Catalyst::Request|Catalyst::Request>)
268 C<$c-E<gt>response-E<gt>body> sets the HTTP response (see
269 L<Catalyst::Response|Catalyst::Response>), while C<$c-E<gt>welcome_message>
270 is a special method that returns the welcome message that you saw in
273 The ":Path :Args(0)" after the method name are attributes which determine
274 which URLs will be dispatched to this method. (Depending on your version of
275 Catalyst, it used to say "Private" but using that with 'default' or 'index'
276 is currently deprecated.)
278 Some MVC frameworks handle dispatching in a central place. Catalyst,
279 by policy, prefers to handle URL dispatching with attributes on
280 controller methods. There is a lot of flexibility in specifying which
281 URLs to match. This particular method will match all URLs, because it
282 doesn't specify the path (nothing comes after "Path"), but will only
283 accept a single args because of the ":Args(0)".
285 The default is to map URLs to controller names, and because of
286 the way that Perl handles namespaces through package names,
287 it is simple to create hierarchical structures in
288 Catalyst. This means that you can create controllers with deeply
289 nested actions in a clean and logical way.
291 For example, the URL C<http://hello.com/admin/articles/create> maps
292 to the package C<Hello::Controller::Admin::Articles>, and the C<create>
295 Add the following subroutine to your C<lib/Hello/Controller/Root.pm>
299 my ( $self, $c ) = @_;
301 $c->response->body("Hello, World!");
304 Here you're sending your own string to the webpage.
306 Save the file, start the server (stop and restart it if it's still
307 up), and go to L<http://localhost:3000/hello> to
311 =head2 Hello, World! Using a View and a Template
313 In the Catalyst world a "View" is not a page of XHTML or a template
314 designed to present a page to a browser. It is the module that
315 determines the I<type> of view -- HTML, pdf, XML, etc. For the
316 thing that generates the I<content> of that view, (such as the
317 default Toolkit Template) the actual templates go under the
320 To create a TT view, run:
322 $ script/hello_create.pl view TT TT
324 This creates the C<lib/Hello/View/TT.pm> module, which is a subclass of
325 C<Catalyst::View::TT>.
331 The "view" keyword tells the create script that you are creating a view.
335 The first "TT" tells the script to name the View module "TT.pm", which is a
336 commonly used name for TT views. (You can name it anything you want, such as
341 The final "TT" tells it that you are creating a Template Toolkit view.
345 If you look at C<lib/Hello/View/TT.pm> you will find that it only contains a
346 config statement to set the TT extension to ".tt".
348 Now that the TT.pm "View" exists, Catalyst will autodiscover it and be
349 able to use it to display the view templates, using the "process"
350 method that it inherits from the C<Catalyst::View::TT class>.
352 Template Toolkit is a very full featured template facility, with
353 excellent documentation at L<http://template-toolkit.org/>,
354 but since this is not a TT tutorial, we'll stick to only basic TT
355 usage here (and explore some of the more common TT features in later
356 parts of the tutorial).
358 Create a C<root/hello.tt> template file (put it in the C<root> under
359 the C<Hello> directory that is the base of your application). Here is
363 This is a TT view template, called '[% template.name %]'.
366 [% and %] are markers for the TT parts of the template. Inside you can
367 access Perl variables and classes, and use TT directives. In this
368 case, we're using a special TT variable that defines the name of the
369 template file (C<hello.tt>). The rest of the template is normal HTML.
371 Change the hello method in C<lib/Hello/Controller/Root.pm> to the
375 my ( $self, $c ) = @_;
377 $c->stash->{template} = 'hello.tt';
380 This time, instead of doing C<$c-E<gt>response-E<gt>body()>, you are setting
381 the value of the "template" hash key in the Catalyst "stash", an area
382 for putting information to share with other parts of your application.
383 The "template" key determines which template will be displayed at the
384 end of the method. Catalyst controllers have a default "end" action
385 for all methods which causes the first (or default) view to be
386 rendered (unless there's a C<$c-E<gt>response-E<gt>body()> statement). So your
387 template will be magically displayed at the end of your method.
389 After saving the file, restart the development server, and look at
390 L<http://localhost:3000/hello> again. You should
391 see the template that you just made.
394 =head1 CREATE A SIMPLE CONTROLLER AND AN ACTION
396 Create a controller named "Site" by executing the create script:
398 $ script/hello_create.pl controller Site
400 This will create a C<lib/Hello/Controller/Site.pm> file (and a test
401 file). Bring Site.pm up in your editor, and you can see that there's
402 not much there. Most people probably don't bother to use the create
403 script to make controllers after they're used to using Catalyst.
405 In C<lib/Hello/Controller/Site.pm>, add the following method:
408 my ( $self, $c ) = @_;
410 $c->stash->{username} = "John";
411 $c->stash->{template} = 'site/test.tt';
414 Notice the "Local" attribute on the C<test> method. This will cause
415 the C<test> action (now that we have assigned an action type to the
416 method it appears as a controller "action" to Catalyst) to be executed
417 on the "controller/method" URL, or, in this case, "site/test". We
418 will see additional information on controller actions throughout the
419 rest of the tutorial, but if you are curious take a look at
420 L<Catalyst::Manual::Intro/Actions>.
422 It's not actually necessary to set the template value as we do here.
423 By default TT will attempt to render a template that follows the
424 naming pattern "controller/method.tt", and we're following that
425 pattern here. However, in other situations you will need to specify
426 the template (such as if you've "forwarded" to the method, or if it
427 doesn't follow the default naming convention).
429 We've also put the variable "username" into the stash, for use in the
432 Make a subdirectory "site" in the "root" directory. Copy the hello.tt
433 file into the directory as C<root/site/test.tt>, or create a new
434 template file at that location. Include a line like:
436 <p>Hello, [% username %]!</p>
438 Bring up or restart the server. Notice in the server output that
439 C</site/test> is listed in the Loaded Path actions. Go to
440 L<http://localhost:3000/site/test> in your browser.
442 You should see your test.tt file displayed, including the name "John"
443 that you set in the controller.
448 Gerda Shank, C<gerda.shank@gmail.com>
449 Kennedy Clark, C<hkclark@gmail.com>
451 Please report any errors, issues or suggestions to the author. The
452 most recent version of the Catalyst Tutorial can be found at
453 L<http://dev.catalyst.perl.org/repos/Catalyst/Catalyst-Manual/5.70/trunk/lib/Catalyst/Manual/Tutorial/>.
455 Copyright 2006-2008, Kennedy Clark & Gerda Shank, under Creative Commons License
456 (L<http://creativecommons.org/licenses/by-sa/3.0/us/>).