1Catalyst::Manual::IntroU(s3e)r Contributed Perl DocumentaCtaitoanlyst::Manual::Intro(3)
2
3
4
6 Catalyst::Manual::Intro - Introduction to Catalyst
7
9 This is a brief introduction to Catalyst. It explains the most impor‐
10 tant features of how Catalyst works and shows how to get a simple
11 application up and running quickly. For an introduction (without code)
12 to Catalyst itself, and why you should be using it, see Catalyst::Man‐
13 ual::About. For a systematic step-by-step introduction to writing an
14 application with Catalyst, see Catalyst::Manual::Tutorial.
15
16 What is Catalyst?
17
18 Catalyst is an elegant web application framework, extremely flexible
19 yet extremely simple. It's similar to Ruby on Rails, Spring (Java), and
20 Maypole, upon which it was originally based. Its most important design
21 philosphy is to provide easy access to all the tools you need to
22 develop web applications, with few restrictions on how you need to use
23 these tools. However, this does mean that it is always possible to do
24 things in a different way. Other web frameworks are initially simpler
25 to use, but achieve this by locking the programmer into a single set of
26 tools. Catalyst's emphasis on flexibility means that you have to think
27 more to use it. We view this as a feature. For example, this leads to
28 Catalyst being more suited to system integration tasks than other web
29 frameworks.
30
31 MVC
32
33 Catalyst follows the Model-View-Controller (MVC) design pattern, allow‐
34 ing you to easily separate concerns, like content, presentation, and
35 flow control, into separate modules. This separation allows you to mod‐
36 ify code that handles one concern without affecting code that handles
37 the others. Catalyst promotes the re-use of existing Perl modules that
38 already handle common web application concerns well.
39
40 Here's how the Model, View, and Controller map to those concerns, with
41 examples of well-known Perl modules you may want to use for each.
42
43 * Model
44 Access and modify content (data). DBIx::Class, Class::DBI, Xapian,
45 Net::LDAP...
46
47 * View
48 Present content to the user. Template Toolkit, Mason, HTML::Tem‐
49 plate...
50
51 * Controller
52 Control the whole request phase, check parameters, dispatch
53 actions, flow control. Catalyst itself!
54
55 If you're unfamiliar with MVC and design patterns, you may want to
56 check out the original book on the subject, Design Patterns, by Gamma,
57 Helm, Johnson, and Vlissides, also known as the Gang of Four (GoF).
58 Many, many web application frameworks are based on MVC, which is becom‐
59 ing a popular design paradigm for the world wide web.
60
61 Flexibility
62
63 Catalyst is much more flexible than many other frameworks. Rest assured
64 you can use your favorite Perl modules with Catalyst.
65
66 * Multiple Models, Views, and Controllers
67 To build a Catalyst application, you handle each type of concern
68 inside special modules called "Components". Often this code will be
69 very simple, just calling out to Perl modules like those listed
70 above under "MVC". Catalyst handles these components in a very
71 flexible way. Use as many Models, Views, and Controllers as you
72 like, using as many different Perl modules as you like, all in the
73 same application. Want to manipulate multiple databases, and
74 retrieve some data via LDAP? No problem. Want to present data from
75 the same Model using Template Toolkit and PDF::Template? Easy.
76
77 * Reuseable Components
78 Not only does Catalyst promote the re-use of already existing Perl
79 modules, it also allows you to re-use your Catalyst components in
80 multiple Catalyst applications.
81
82 * Unrestrained URL-to-Action Dispatching
83 Catalyst allows you to dispatch any URLs to any application
84 "Actions", even through regular expressions! Unlike most other
85 frameworks, it doesn't require mod_rewrite or class and method
86 names in URLs.
87
88 With Catalyst you register your actions and address them directly.
89 For example:
90
91 sub hello : Global {
92 my ( $self, $context ) = @_;
93 $context->response->body('Hello World!');
94 }
95
96 Now http://localhost:3000/hello prints "Hello World!".
97
98 * Support for CGI, mod_perl, Apache::Request, FastCGI
99 Use Catalyst::Engine::Apache or Catalyst::Engine::CGI. Other
100 engines are also available.
101
102 Simplicity
103
104 The best part is that Catalyst implements all this flexibility in a
105 very simple way.
106
107 * Building Block Interface
108 Components interoperate very smoothly. For example, Catalyst auto‐
109 matically makes a "Context" object available to every component.
110 Via the context, you can access the request object, share data
111 between components, and control the flow of your application.
112 Building a Catalyst application feels a lot like snapping together
113 toy building blocks, and everything just works.
114
115 * Component Auto-Discovery
116 No need to "use" all of your components. Catalyst automatically
117 finds and loads them.
118
119 * Pre-Built Components for Popular Modules
120 See Catalyst::Model::DBIC::Schema for DBIx::Class, or Cata‐
121 lyst::View::TT for Template Toolkit.
122
123 * Built-in Test Framework
124 Catalyst comes with a built-in, lightweight http server and test
125 framework, making it easy to test applications from the web
126 browser, and the command line.
127
128 * Helper Scripts
129 Catalyst provides helper scripts to quickly generate running
130 starter code for components and unit tests. Install Catalyst::Devel
131 and see Catalyst::Helper.
132
133 Quickstart
134
135 Here's how to install Catalyst and get a simple application up and run‐
136 ning, using the helper scripts described above.
137
138 Install
139
140 Installation of Catalyst can be a time-consuming and frustrating
141 effort, due to its large number of dependencies. The easiest way to get
142 up and running is to use Matt Trout's "cat-install" script, from
143 <http://www.shadowcatsystems.co.uk/static/cat-install>, and then
144 install Catalyst::Devel.
145
146 # perl cat-install
147 # perl -MCPAN -e 'install Catalyst::Devel'
148
149 Setup
150
151 $ catalyst.pl MyApp
152 # output omitted
153 $ cd MyApp
154 $ script/myapp_create.pl controller Library::Login
155
156 Run
157
158 $ script/myapp_server.pl
159
160 Now visit these locations with your favorite browser or user agent to
161 see Catalyst in action:
162
163 (NOTE: Although we create a controller here, we don't actually use it.
164 Both of these URLs should take you to the welcome page.)
165
166 http://localhost:3000/
167 http://localhost:3000/library/login/
168
169 How It Works
170
171 Let's see how Catalyst works, by taking a closer look at the components
172 and other parts of a Catalyst application.
173
174 Components
175
176 Catalyst has an uncommonly flexible component system. You can define as
177 many "Models", "Views", and "Controllers" as you like. As discussed
178 previously, the general idea is that the View is responsible for the
179 output of data to the user (typically via a web browser, but a View can
180 also generate PDFs or e-mails, for example); the Model is responsible
181 for providing data (typically from a relational database); and the Con‐
182 troller is responsible for interacting with the user and deciding how
183 user input determines what actions the application takes.
184
185 In the world of MVC, there are frequent discussions and disagreements
186 about the nature of each element - whether certain types of logic
187 belong in the Model or the Controller, etc. Catalyst's flexibility
188 means that this decision is entirely up to you, the programmer; Cata‐
189 lyst doesn't enforce anything. See Catalyst::Manual::About for a gen‐
190 eral discussion of these issues.
191
192 All components must inherit from Catalyst::Base, which provides a sim‐
193 ple class structure and some common class methods like "config" and
194 "new" (constructor).
195
196 package MyApp::Controller::Catalog;
197
198 use strict;
199 use base 'Catalyst::Base';
200
201 __PACKAGE__->config( foo => 'bar' );
202
203 1;
204
205 You don't have to "use" or otherwise register Models, Views, and Con‐
206 trollers. Catalyst automatically discovers and instantiates them when
207 you call "setup" in the main application. All you need to do is put
208 them in directories named for each Component type. You can use a short
209 alias for each one.
210
211 * MyApp/Model/
212 * MyApp/M/
213 * MyApp/View/
214 * MyApp/V/
215 * MyApp/Controller/
216 * MyApp/C/
217
218 In older versions of Catalyst, the recommended practice (and the one
219 automatically created by helper scripts) was to name the directories
220 "M/", "V/", and "C/". Though these still work, we now recommend the use
221 of the full names.
222
223 Views
224
225 To show how to define views, we'll use an already-existing base class
226 for the Template Toolkit, Catalyst::View::TT. All we need to do is
227 inherit from this class:
228
229 package MyApp::View::TT;
230
231 use strict;
232 use base 'Catalyst::View::TT';
233
234 1;
235
236 (You can also generate this automatically by using the helper script:
237
238 script/myapp_create.pl view TT TT
239
240 where the first "TT" tells the script that the name of the view should
241 be "TT", and the second that it should be a Template Toolkit view.)
242
243 This gives us a process() method and we can now just do $c->for‐
244 ward('MyApp::View::TT') to render our templates. The base class makes
245 process() implicit, so we don't have to say "$c->for‐
246 ward(qw/MyApp::View::TT process/)".
247
248 sub hello : Global {
249 my ( $self, $c ) = @_;
250 $c->stash->{template} = 'hello.tt';
251 }
252
253 sub end : Private {
254 my ( $self, $c ) = @_;
255 $c->forward( $c->view('TT') );
256 }
257
258 You normally render templates at the end of a request, so it's a per‐
259 fect use for the global "end" action.
260
261 In practice, however, you would use a default "end" action as supplied
262 by Catalyst::Action::RenderView.
263
264 Also, be sure to put the template under the directory specified in
265 "$c->config->{root}", or you'll end up looking at the debug screen.
266
267 Models
268
269 Models are providers of data. This data could come from anywhere - a
270 search engine index, a spreadsheet, the file system - but typically a
271 Model represents a database table. The data source does not intrinsi‐
272 cally have much to do with web applications or Catalyst - it could just
273 as easily be used to write an offline report generator or a command-
274 line tool.
275
276 To show how to define models, again we'll use an already-existing base
277 class, this time for DBIx::Class: Catalyst::Model::DBIC::Schema. We'll
278 also need DBIx::Class::Schema::Loader.
279
280 But first, we need a database.
281
282 -- myapp.sql
283 CREATE TABLE foo (
284 id INTEGER PRIMARY KEY,
285 data TEXT
286 );
287
288 CREATE TABLE bar (
289 id INTEGER PRIMARY KEY,
290 foo INTEGER REFERENCES foo,
291 data TEXT
292 );
293
294 INSERT INTO foo (data) VALUES ('TEST!');
295
296 % sqlite /tmp/myapp.db < myapp.sql
297
298 Now we can create a DBIC::Schema model for this database.
299
300 script/myapp_create.pl model MyModel DBIC::Schema MySchema create=static 'dbi:SQLite:/tmp/myapp.db'
301
302 DBIx::Class::Schema::Loader automatically loads table layouts and rela‐
303 tionships, and converts them into a static schema definition
304 "MySchema", which you can edit later.
305
306 Use the stash to pass data to your templates.
307
308 We add the following to MyApp/Controller/Root.pm
309
310 sub view : Global {
311 my ( $self, $c, $id ) = @_;
312
313 $c->stash->{item} = $c->model('MyModel::Foo')->find($id);
314 }
315
316 1;
317
318 sub end : Private {
319 my ( $self, $c ) = @_;
320
321 $c->stash->{template} ⎪⎪= 'index.tt';
322 $c->forward( $c->view('TT') );
323 }
324
325 We then create a new template file "root/index.tt" containing:
326
327 The Id's data is [% item.data %]
328
329 Models do not have to be part of your Catalyst application; you can
330 always call an outside module that serves as your Model:
331
332 # in a Controller
333 sub list : Local {
334 my ( $self, $c ) = @_;
335
336 $c->stash->{template} = 'list.tt';
337
338 use Some::Outside::Database::Module;
339 my @records = Some::Outside::Database::Module->search({
340 artist => 'Led Zeppelin',
341 });
342
343 $c->stash->{records} = \@records;
344 }
345
346 But by using a Model that is part of your Catalyst application, you
347 gain several things: you don't have to "use" each component, Catalyst
348 will find and load it automatically at compile-time; you can "forward"
349 to the module, which can only be done to Catalyst components. Only
350 Catalyst components can be fetched with "$c->model('SomeModel')".
351
352 Happily, since many people have existing Model classes that they would
353 like to use with Catalyst (or, conversely, they want to write Catalyst
354 models that can be used outside of Catalyst, e.g. in a cron job), it's
355 trivial to write a simple component in Catalyst that slurps in an out‐
356 side Model:
357
358 package MyApp::Model::DB;
359 use base qw/Catalyst::Model::DBIC::Schema/;
360 __PACKAGE__->config(
361 schema_class => 'Some::DBIC::Schema',
362 connect_info => ['dbi:SQLite:foo.db', '', '', {AutoCommit=>1}]
363 );
364 1;
365
366 and that's it! Now "Some::DBIC::Schema" is part of your Cat app as
367 "MyApp::Model::DB".
368
369 Within Catalyst, the common approach to writing a model for your appli‐
370 cation is wrapping a generic model (e.g. DBIx::Class::Schema, a bunch
371 of XMLs, or anything really) with an object that contains configuration
372 data, convenience methods, and so forth. Thus you will in effect have
373 two models - a wrapper model that knows something about Catalyst and
374 your web application, and a generic model that is totally independent
375 of these needs.
376
377 Technically, within Catalyst a model is a component - an instance of
378 the model's class belonging to the application. It is important to
379 stress that the lifetime of these objects is per application, not per
380 request.
381
382 While the model base class (Catalyst::Model) provides things like "con‐
383 fig" to better integrate the model into the application, sometimes this
384 is not enough, and the model requires access to $c itself.
385
386 Situations where this need might arise include:
387
388 · Interacting with another model
389
390 · Using per-request data to control behavior
391
392 · Using plugins from a Model (for example Catalyst::Plugin::Cache).
393
394 From a style perspective it's usually considered bad form to make your
395 model "too smart" about things - it should worry about business logic
396 and leave the integration details to the controllers. If, however, you
397 find that it does not make sense at all to use an auxillary controller
398 around the model, and the model's need to access $c cannot be
399 sidestepped, there exists a power tool called "ACCEPT_CONTEXT".
400
401 Controllers
402
403 Multiple controllers are a good way to separate logical domains of your
404 application.
405
406 package MyApp::Controller::Login;
407
408 use base qw/Catalyst::Controller/;
409
410 sub login : Path("login") { }
411 sub new_password : Path("new-password") { }
412 sub logout : Path("logout") { }
413
414 package MyApp::Controller::Catalog;
415
416 use base qw/Catalyst::Controller/;
417
418 sub view : Local { }
419 sub list : Local { }
420
421 package MyApp::Controller::Cart;
422
423 use base qw/Catalyst::Controller/;
424
425 sub add : Local { }
426 sub update : Local { }
427 sub order : Local { }
428
429 Note that you can also supply attributes via the Controller's config so
430 long as you have at least one attribute on a subref to be exported
431 (:Action is commonly used for this) - for example the following is
432 equivalent to the same controller above:
433
434 package MyApp::Controller::Login;
435
436 use base qw/Catalyst::Controller/;
437
438 __PACKAGE__->config(
439 actions => {
440 'sign_in' => { Path => 'sign-in' },
441 'new_password' => { Path => 'new-password' },
442 'sign_out' => { Path => 'sign-out' },
443 },
444 );
445
446 sub sign_in : Action { }
447 sub new_password : Action { }
448 sub sign_out : Action { }
449
450 ACCEPT_CONTEXT
451
452 Whenever you call $c->component("Foo") you get back an object - the
453 instance of the model. If the component supports the "ACCEPT_CONTEXT"
454 method instead of returning the model itself, the return value of
455 "$model->ACCEPT_CONTEXT( $c )" will be used.
456
457 This means that whenever your model/view/controller needs to talk to $c
458 it gets a chance to do this when it's needed.
459
460 A typical "ACCEPT_CONTEXT" method will either clone the model and
461 return one with the context object set, or it will return a thin wrap‐
462 per that contains $c and delegates to the per-application model object.
463
464 A typical "ACCEPT_CONTEXT" method could look like this:
465
466 sub ACCEPT_CONTEXT {
467 my ( $self, $c, @extra_arguments ) = @_;
468 bless { %$self, c => $c }, ref($self);
469 }
470
471 effectively treating $self as a prototype object that gets a new param‐
472 eter. @extra_arguments comes from any trailing arguments to "$c->com‐
473 ponent( $bah, @extra_arguments )" (or "$c->model(...)", "$c->view(...)"
474 etc).
475
476 The life time of this value is per usage, and not per request. To make
477 this per request you can use the following technique:
478
479 Add a field to $c, like "my_model_instance". Then write your
480 "ACCEPT_CONTEXT" method to look like this:
481
482 sub ACCEPT_CONTEXT {
483 my ( $self, $c ) = @_;
484
485 if ( my $per_request = $c->my_model_instance ) {
486 return $per_request;
487 } else {
488 my $new_instance = bless { %$self, c => $c }, ref($self);
489 Scalar::Util::weaken($new_instance->{c}); # or we have a circular reference
490 $c->my_model_instance( $new_instance );
491 return $new_instance;
492 }
493 }
494
495 Application Class
496
497 In addition to the Model, View, and Controller components, there's a
498 single class that represents your application itself. This is where you
499 configure your application, load plugins, and extend Catalyst.
500
501 package MyApp;
502
503 use strict;
504 use Catalyst qw/-Debug/; # Add other plugins here, e.g.
505 # for session support
506
507 MyApp->config(
508 name => 'My Application',
509
510 # You can put anything else you want in here:
511 my_configuration_variable => 'something',
512 );
513 1;
514
515 In older versions of Catalyst, the application class was where you put
516 global actions. However, as of version 5.66, the recommended practice
517 is to place such actions in a special Root controller (see "Actions",
518 below), to avoid namespace collisions.
519
520 * name
521 The name of your application.
522
523 Optionally, you can specify a root parameter for templates and static
524 data. If omitted, Catalyst will try to auto-detect the directory's
525 location. You can define as many parameters as you want for plugins or
526 whatever you need. You can access them anywhere in your application via
527 "$context->config->{$param_name}".
528
529 Context
530
531 Catalyst automatically blesses a Context object into your application
532 class and makes it available everywhere in your application. Use the
533 Context to directly interact with Catalyst and glue your "Components"
534 together. For example, if you need to use the Context from within a
535 Template Toolkit template, it's already there:
536
537 <h1>Welcome to [% c.config.name %]!</h1>
538
539 As illustrated in our URL-to-Action dispatching example, the Context is
540 always the second method parameter, behind the Component object refer‐
541 ence or class name itself. Previously we called it $context for clar‐
542 ity, but most Catalyst developers just call it $c:
543
544 sub hello : Global {
545 my ( $self, $c ) = @_;
546 $c->res->body('Hello World!');
547 }
548
549 The Context contains several important objects:
550
551 * Catalyst::Request
552 $c->request
553 $c->req # alias
554
555 The request object contains all kinds of request-specific informa‐
556 tion, like query parameters, cookies, uploads, headers, and more.
557
558 $c->req->params->{foo};
559 $c->req->cookies->{sessionid};
560 $c->req->headers->content_type;
561 $c->req->base;
562 $c->req->uri_with( { page = $pager->next_page } );
563
564 * Catalyst::Response
565 $c->response
566 $c->res # alias
567
568 The response is like the request, but contains just response-spe‐
569 cific information.
570
571 $c->res->body('Hello World');
572 $c->res->status(404);
573 $c->res->redirect('http://oook.de');
574
575 * Catalyst::Config
576 $c->config
577 $c->config->{root};
578 $c->config->{name};
579
580 * Catalyst::Log
581 $c->log
582 $c->log->debug('Something happened');
583 $c->log->info('Something you should know');
584
585 * Stash
586 $c->stash
587 $c->stash->{foo} = 'bar';
588 $c->stash->{baz} = {baz => 'qox'};
589 $c->stash->{fred} = [qw/wilma pebbles/];
590
591 and so on.
592
593 The last of these, the stash, is a universal hash for sharing data
594 among application components. For an example, we return to our 'hello'
595 action:
596
597 sub hello : Global {
598 my ( $self, $c ) = @_;
599 $c->stash->{message} = 'Hello World!';
600 $c->forward('show_message');
601 }
602
603 sub show_message : Private {
604 my ( $self, $c ) = @_;
605 $c->res->body( $c->stash->{message} );
606 }
607
608 Note that the stash should be used only for passing data in an individ‐
609 ual request cycle; it gets cleared at a new request. If you need to
610 maintain persistent data, use a session. See Catalyst::Plugin::Session
611 for a comprehensive set of Catalyst-friendly session-handling tools.
612
613 Actions
614
615 A Catalyst controller is defined by its actions. An action is a subrou‐
616 tine with a special attribute. You've already seen some examples of
617 actions in this document. The URL (for example http://local‐
618 host.3000/foo/bar) consists of two parts, the base (http://local‐
619 host:3000/ in this example) and the path (foo/bar). Please note that
620 the trailing slash after the hostname[:port] always belongs to base and
621 not to the action.
622
623 * Application Wide Actions
624 Actions which are called at the root level of the application (e.g.
625 http://localhost:3000/ ) go in MyApp::Controller::Root, like this:
626
627 package MyApp::Controller::Root;
628 use base 'Catalyst::Controller';
629 # Sets the actions in this controller to be registered with no prefix
630 # so they function identically to actions created in MyApp.pm
631 __PACKAGE__->config->{namespace} = '';
632 sub default : Private {
633 my ( $self, $context ) = @_;
634 $context->response->body('Catalyst rocks!');
635 }
636 1;
637
638 Action types
639
640 Catalyst supports several types of actions:
641
642 * Literal (Path actions)
643 package MyApp::Controller::My::Controller;
644 sub bar : Path('foo/bar') { }
645
646 Literal "Path" actions will act relative to their current names‐
647 pace. The above example matches only http://localhost:3000/my/con‐
648 troller/foo/bar. If you start your path with a forward slash, it
649 will match from the root. Example:
650
651 package MyApp::Controller::My::Controller;
652 sub bar : Path('/foo/bar') { }
653
654 Matches only http://localhost:3000/foo/bar.
655
656 package MyApp::Controller::My::Controller;
657 sub bar : Path { }
658
659 By leaving the "Path" definition empty, it will match on the names‐
660 pace root. The above code matches http://localhost:3000/my/con‐
661 troller.
662
663 * Regex
664 sub bar : Regex('^item(\d+)/order(\d+)$') { }
665
666 Matches any URL that matches the pattern in the action key, e.g.
667 http://localhost:3000/item23/order42. The '' around the regexp is
668 optional, but perltidy likes it. :)
669
670 Regex matches act globally, i.e. without reference to the namespace
671 from which it is called, so that a "bar" method in the "MyApp::Con‐
672 troller::Catalog::Order::Process" namespace won't match any form of
673 "bar", "Catalog", "Order", or "Process" unless you explicitly put
674 this in the regex. To achieve the above, you should consider using
675 a "LocalRegex" action.
676
677 * LocalRegex
678 sub bar : LocalRegex('^widget(\d+)$') { }
679
680 LocalRegex actions act locally. If you were to use "bar" in
681 "MyApp::Controller::Catalog", the above example would match urls
682 like http://localhost:3000/catalog/widget23.
683
684 If you omit the ""^"" from your regex, then it will match any depth
685 from the controller and not immediately off of the controller name.
686 The following example differs from the above code in that it will
687 match http://localhost:3000/catalog/foo/widget23 as well.
688
689 package MyApp::Controller::Catalog;
690 sub bar : LocalRegex('widget(\d+)$') { }
691
692 For both LocalRegex and Regex actions, if you use capturing paren‐
693 theses to extract values within the matching URL, those values are
694 available in the "$c->req->captures" array. In the above example,
695 "widget23" would capture "23" in the above example, and
696 "$c->req->captures->[0]" would be "23". If you want to pass argu‐
697 ments at the end of your URL, you must use regex action keys. See
698 "URL Path Handling" below.
699
700 * Top-level (Global)
701 package MyApp::Controller::Foo;
702 sub foo : Global { }
703
704 Matches http://localhost:3000/foo. The function name is mapped
705 directly to the application base. You can provide an equivalent
706 function in this case by doing the following:
707
708 package MyApp::Controller::Root
709 sub foo : Local { }
710
711 * Namespace-Prefixed (Local)
712 package MyApp::Controller::My::Controller;
713 sub foo : Local { }
714
715 Matches http://localhost:3000/my/controller/foo.
716
717 This action type indicates that the matching URL must be prefixed
718 with a modified form of the component's class (package) name. This
719 modified class name excludes the parts that have a pre-defined
720 meaning in Catalyst ("MyApp::Controller" in the above example),
721 replaces "::" with "/", and converts the name to lower case. See
722 "Components" for a full explanation of the pre-defined meaning of
723 Catalyst component class names.
724
725 * Chained
726 Catalyst also provides a method to build and dispatch chains of
727 actions, like
728
729 sub catalog : Chained : CaptureArgs(1) {
730 my ( $self, $c, $arg ) = @_;
731 ...
732 }
733
734 sub item : Chained('catalog') : Args(1) {
735 my ( $self, $c, $arg ) = @_;
736 ...
737 }
738
739 to handle a "/catalog/*/item/*" path. For further information about
740 this dispatch type, please see Catalyst::DispatchType::Chained.
741
742 * Private
743 sub foo : Private { }
744
745 Matches no URL, and cannot be executed by requesting a URL that
746 corresponds to the action key. Catalyst's :Private attribute is
747 exclusive and doesn't work with other attributes (so will not work
748 combined with Path or Chained attributes). With the exception of
749 the " index ", " auto " and " default " actions, Private actions
750 can only be executed from inside a Catalyst application, by calling
751 the "forward" or "detach" methods:
752
753 $c->forward('foo');
754 # or
755 $c->detach('foo');
756
757 See "Flow Control" for a full explanation of "forward". Note that,
758 as discussed there, when forwarding from another component, you
759 must use the absolute path to the method, so that a private "bar"
760 method in your "MyApp::Controller::Catalog::Order::Process" con‐
761 troller must, if called from elsewhere, be reached with "$c->for‐
762 ward('/catalog/order/process/bar')".
763
764 * Args
765 Args is not an action type per se, but an action modifier - it adds
766 a match restriction to any action it's provided to, requiring only
767 as many path parts as are specified for the action to be valid -
768 for example in MyApp::Controller::Foo,
769
770 sub bar :Local
771
772 would match any URL starting /foo/bar/. To restrict this you can do
773
774 sub bar :Local :Args(1)
775
776 to only match /foo/bar/*/
777
778 Note: After seeing these examples, you probably wonder what the point
779 is of defining names for regex and path actions. Every public action is
780 also a private one, so you have one unified way of addressing compo‐
781 nents in your "forward"s.
782
783 Built-in Private Actions
784
785 In response to specific application states, Catalyst will automatically
786 call these built-in private actions in your application class:
787
788 * default : Private
789 Called when no other action matches. Could be used, for example,
790 for displaying a generic frontpage for the main app, or an error
791 page for individual controllers.
792
793 If "default" isn't acting how you would expect, look at using a
794 "Literal" "Path" action (with an empty path string). The difference
795 is that "Path" takes arguments relative from the namespace and
796 "default" always takes arguments relative from the root, regardless
797 of what controller it's in. Indeed, this is now the recommended way
798 of handling default situations; the "default" private controller
799 should be considered deprecated.
800
801 * index : Private
802 "index" is much like "default" except that it takes no arguments
803 and it is weighted slightly higher in the matching process. It is
804 useful as a static entry point to a controller, e.g. to have a
805 static welcome page. Note that it's also weighted higher than Path.
806
807 * begin : Private
808 Called at the beginning of a request, before any matching actions
809 are called.
810
811 * end : Private
812 Called at the end of a request, after all matching actions are
813 called.
814
815 Built-in actions in controllers/autochaining
816
817 Package MyApp::Controller::Foo;
818 sub begin : Private { }
819 sub default : Private { }
820 sub auto : Private { }
821
822 You can define built-in private actions within your controllers as
823 well. The actions will override the ones in less-specific controllers,
824 or your application class. In other words, for each of the three built-
825 in private actions, only one will be run in any request cycle. Thus, if
826 "MyApp::Controller::Catalog::begin" exists, it will be run in place of
827 "MyApp::begin" if you're in the "catalog" namespace, and "MyApp::Con‐
828 troller::Catalog::Order::begin" would override this in turn.
829
830 * auto : Private
831 In addition to the normal built-in actions, you have a special
832 action for making chains, "auto". Such "auto" actions will be run
833 after any "begin", but before your action is processed. Unlike the
834 other built-ins, "auto" actions do not override each other; they
835 will be called in turn, starting with the application class and
836 going through to the most specific class. This is the reverse of
837 the order in which the normal built-ins override each other.
838
839 Here are some examples of the order in which the various built-ins
840 would be called:
841
842 for a request for "/foo/foo"
843 MyApp::begin
844 MyApp::auto
845 MyApp::Controller::Foo::default # in the absence of MyApp::Controller::Foo::Foo
846 MyApp::end
847
848 for a request for "/foo/bar/foo"
849 MyApp::Controller::Foo::Bar::begin
850 MyApp::auto
851 MyApp::Controller::Foo::auto
852 MyApp::Controller::Foo::Bar::auto
853 MyApp::Controller::Foo::Bar::default # for MyApp::Controller::Foo::Bar::foo
854 MyApp::Controller::Foo::Bar::end
855
856 The "auto" action is also distinguished by the fact that you can break
857 out of the processing chain by returning 0. If an "auto" action returns
858 0, any remaining actions will be skipped, except for "end". So, for the
859 request above, if the first auto returns false, the chain would look
860 like this:
861
862 for a request for "/foo/bar/foo" where first "auto" returns false
863 MyApp::Controller::Foo::Bar::begin
864 MyApp::auto
865 MyApp::Controller::Foo::Bar::end
866
867 An example of why one might use this is an authentication action: you
868 could set up a "auto" action to handle authentication in your applica‐
869 tion class (which will always be called first), and if authentication
870 fails, returning 0 would skip any remaining methods for that URL.
871
872 Note: Looking at it another way, "auto" actions have to return a true
873 value to continue processing! You can also "die" in the auto action; in
874 that case, the request will go straight to the finalize stage, without
875 processing further actions.
876
877 URL Path Handling
878
879 You can pass variable arguments as part of the URL path, separated with
880 forward slashes (/). If the action is a Regex or LocalRegex, the '$'
881 anchor must be used. For example, suppose you want to handle
882 "/foo/$bar/$baz", where $bar and $baz may vary:
883
884 sub foo : Regex('^foo$') { my ($self, $context, $bar, $baz) = @_; }
885
886 But what if you also defined actions for "/foo/boo" and "/foo/boo/hoo"?
887
888 sub boo : Path('foo/boo') { .. }
889 sub hoo : Path('foo/boo/hoo') { .. }
890
891 Catalyst matches actions in most specific to least specific order:
892
893 /foo/boo/hoo
894 /foo/boo
895 /foo # might be /foo/bar/baz but won't be /foo/boo/hoo
896
897 So Catalyst would never mistakenly dispatch the first two URLs to the
898 '^foo$' action.
899
900 If a Regex or LocalRegex action doesn't use the '$' anchor, the action
901 will still match a URL containing arguments, however the arguments
902 won't be available via @_.
903
904 Parameter Processing
905
906 Parameters passed in the URL query string are handled with methods in
907 the Catalyst::Request class. The "param" method is functionally equiva‐
908 lent to the "param" method of "CGI.pm" and can be used in modules that
909 require this.
910
911 # http://localhost:3000/catalog/view/?category=hardware&page=3
912 my $category = $c->req->param('category');
913 my $current_page = $c->req->param('page') ⎪⎪ 1;
914
915 # multiple values for single parameter name
916 my @values = $c->req->param('scrolling_list');
917
918 # DFV requires a CGI.pm-like input hash
919 my $results = Data::FormValidator->check($c->req->params, \%dfv_profile);
920
921 Flow Control
922
923 You control the application flow with the "forward" method, which
924 accepts the key of an action to execute. This can be an action in the
925 same or another Catalyst controller, or a Class name, optionally fol‐
926 lowed by a method name. After a "forward", the control flow will return
927 to the method from which the "forward" was issued.
928
929 A "forward" is similar to a method call. The main differences are that
930 it wraps the call in an "eval" to allow exception handling; it automat‐
931 ically passes along the context object ($c or $context); and it allows
932 profiling of each call (displayed in the log with debugging enabled).
933
934 sub hello : Global {
935 my ( $self, $c ) = @_;
936 $c->stash->{message} = 'Hello World!';
937 $c->forward('check_message'); # $c is automatically included
938 }
939
940 sub check_message : Private {
941 my ( $self, $c ) = @_;
942 return unless $c->stash->{message};
943 $c->forward('show_message');
944 }
945
946 sub show_message : Private {
947 my ( $self, $c ) = @_;
948 $c->res->body( $c->stash->{message} );
949 }
950
951 A "forward" does not create a new request, so your request object
952 ("$c->req") will remain unchanged. This is a key difference between
953 using "forward" and issuing a redirect.
954
955 You can pass new arguments to a "forward" by adding them in an anony‐
956 mous array. In this case "$c->req->args" will be changed for the dura‐
957 tion of the "forward" only; upon return, the original value of
958 "$c->req->args" will be reset.
959
960 sub hello : Global {
961 my ( $self, $c ) = @_;
962 $c->stash->{message} = 'Hello World!';
963 $c->forward('check_message',[qw/test1/]);
964 # now $c->req->args is back to what it was before
965 }
966
967 sub check_message : Private {
968 my ( $self, $c ) = @_;
969 my $first_argument = $c->req->args->[0]; # now = 'test1'
970 # do something...
971 }
972
973 As you can see from these examples, you can just use the method name as
974 long as you are referring to methods in the same controller. If you
975 want to forward to a method in another controller, or the main applica‐
976 tion, you will have to refer to the method by absolute path.
977
978 $c->forward('/my/controller/action');
979 $c->forward('/default'); # calls default in main application
980
981 Here are some examples of how to forward to classes and methods.
982
983 sub hello : Global {
984 my ( $self, $c ) = @_;
985 $c->forward(qw/MyApp::Model::Hello say_hello/);
986 }
987
988 sub bye : Global {
989 my ( $self, $c ) = @_;
990 $c->forward('MyApp::Model::Hello'); # no method: will try 'process'
991 }
992
993 package MyApp::Model::Hello;
994
995 sub say_hello {
996 my ( $self, $c ) = @_;
997 $c->res->body('Hello World!');
998 }
999
1000 sub process {
1001 my ( $self, $c ) = @_;
1002 $c->res->body('Goodbye World!');
1003 }
1004
1005 Note that "forward" returns to the calling action and continues pro‐
1006 cessing after the action finishes. If you want all further processing
1007 in the calling action to stop, use "detach" instead, which will execute
1008 the "detach"ed action and not return to the calling sub. In both cases,
1009 Catalyst will automatically try to call process() if you omit the
1010 method.
1011
1012 Testing
1013
1014 Catalyst has a built-in http server for testing or local deployment.
1015 (Later, you can easily use a more powerful server, for example
1016 Apache/mod_perl or FastCGI, in a production environment.)
1017
1018 Start your application on the command line...
1019
1020 script/myapp_server.pl
1021
1022 ...then visit http://localhost:3000/ in a browser to view the output.
1023
1024 You can also do it all from the command line:
1025
1026 script/myapp_test.pl http://localhost/
1027
1028 Catalyst has a number of tools for actual regression testing of appli‐
1029 cations. The helper scripts will automatically generate basic tests
1030 that can be extended as you develop your project. To write your own
1031 comprehensive test scripts, Test::WWW::Mechanize::Catalyst is an
1032 invaluable tool.
1033
1034 For more testing ideas, see Catalyst::Manual::Tutorial::Testing.
1035
1036 Have fun!
1037
1039 * Catalyst::Manual::About
1040 * Catalyst::Manual::Tutorial
1041 * Catalyst
1042
1044 IRC:
1045
1046 Join #catalyst on irc.perl.org.
1047 Join #catalyst-dev on irc.perl.org to help with development.
1048
1049 Mailing lists:
1050
1051 http://lists.rawmode.org/mailman/listinfo/catalyst
1052 http://lists.rawmode.org/mailman/listinfo/catalyst-dev
1053
1055 Sebastian Riedel, "sri@oook.de" David Naughton, "naughton@umn.edu" Mar‐
1056 cus Ramberg, "mramberg@cpan.org" Jesse Sheidlower, "jester@panix.com"
1057 Danijel Milicevic, "me@danijel.de" Kieren Diment, "kd@totaldatasolu‐
1058 tion.com" Yuval Kogman, "nothingmuch@woobling.org"
1059
1061 This program is free software. You can redistribute it and/or modify it
1062 under the same terms as Perl itself.
1063
1064
1065
1066perl v5.8.8 2007-02-28 Catalyst::Manual::Intro(3)