1Catalyst::Manual::IntroU(s3e)r Contributed Perl DocumentaCtaitoanlyst::Manual::Intro(3)
2
3
4

NAME

6       Catalyst::Manual::Intro - Introduction to Catalyst
7

DESCRIPTION

9       This is a brief introduction to Catalyst. It explains the most
10       important 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
13       Catalyst::Manual::About.  For a systematic step-by-step introduction to
14       writing an application with Catalyst, see Catalyst::Manual::Tutorial.
15
16   What is Catalyst?
17       Catalyst is an elegant web application framework, extremely flexible
18       yet extremely simple. It's similar to Ruby on Rails, Spring (Java), and
19       Maypole, upon which it was originally based. Its most important design
20       philosphy is to provide easy access to all the tools you need to
21       develop web applications, with few restrictions on how you need to use
22       these tools. However, this does mean that it is always possible to do
23       things in a different way. Other web frameworks are initially simpler
24       to use, but achieve this by locking the programmer into a single set of
25       tools. Catalyst's emphasis on flexibility means that you have to think
26       more to use it. We view this as a feature.  For example, this leads to
27       Catalyst being more suited to system integration tasks than other web
28       frameworks.
29
30       MVC
31
32       Catalyst follows the Model-View-Controller (MVC) design pattern,
33       allowing you to easily separate concerns, like content, presentation,
34       and flow control, into separate modules. This separation allows you to
35       modify code that handles one concern without affecting code that
36       handles the others. Catalyst promotes the re-use of existing Perl
37       modules that already handle common web application concerns well.
38
39       Here's how the Model, View, and Controller map to those concerns, with
40       examples of well-known Perl modules you may want to use for each.
41
42       ·   Model
43
44           Access and modify content (data). DBIx::Class, Class::DBI, Xapian,
45           Net::LDAP...
46
47       ·   View
48
49           Present content to the user. Template Toolkit, Mason,
50           HTML::Template...
51
52       ·   Controller
53
54           Control the whole request phase, check parameters, dispatch
55           actions, flow control. Catalyst itself!
56
57       If you're unfamiliar with MVC and design patterns, you may want to
58       check out the original book on the subject, Design Patterns, by Gamma,
59       Helm, Johnson, and Vlissides, also known as the Gang of Four (GoF).
60       Many, many web application frameworks are based on MVC, which is
61       becoming a popular design paradigm for the world wide web.
62
63       Flexibility
64
65       Catalyst is much more flexible than many other frameworks. Rest assured
66       you can use your favorite Perl modules with Catalyst.
67
68       ·   Multiple Models, Views, and Controllers
69
70           To build a Catalyst application, you handle each type of concern
71           inside special modules called "Components". Often this code will be
72           very simple, just calling out to Perl modules like those listed
73           above under "MVC". Catalyst handles these components in a very
74           flexible way. Use as many Models, Views, and Controllers as you
75           like, using as many different Perl modules as you like, all in the
76           same application. Want to manipulate multiple databases, and
77           retrieve some data via LDAP? No problem. Want to present data from
78           the same Model using Template Toolkit and PDF::Template? Easy.
79
80       ·   Reuseable Components
81
82           Not only does Catalyst promote the re-use of already existing Perl
83           modules, it also allows you to re-use your Catalyst components in
84           multiple Catalyst applications.
85
86       ·   Unrestrained URL-to-Action Dispatching
87
88           Catalyst allows you to dispatch any URLs to any application
89           "Actions", even through regular expressions! Unlike most other
90           frameworks, it doesn't require mod_rewrite or class and method
91           names in URLs.
92
93           With Catalyst you register your actions and address them directly.
94           For example:
95
96               sub hello : Local {
97                   my ( $self, $context ) = @_;
98                   $context->response->body('Hello World!');
99               }
100
101           Now http://localhost:3000/hello prints "Hello World!".
102
103           Note that actions with the " :Global " attribute are equivalent to
104           using a ":Path('action_name') " attribute, so our action could be
105           equivalently:
106
107               sub hi : Path('hello') {
108                   my ( $self, $context ) = @_;
109                   $context->response->body('Hello World!');
110               }
111
112       ·   Support for CGI, mod_perl, Apache::Request, FastCGI
113
114           Use Catalyst::Engine::Apache or Catalyst::Engine::CGI. Another
115           interesting engine is Catalyst::Engine::HTTP::Prefork - available
116           from CPAN separately - which will turn the built server into a
117           fully fledged production ready server (although you'll probably
118           want to run it behind a front end proxy if you end up using it).
119
120       Simplicity
121
122       The best part is that Catalyst implements all this flexibility in a
123       very simple way.
124
125       ·   Building Block Interface
126
127           Components interoperate very smoothly. For example, Catalyst
128           automatically makes a "Context" object available to every
129           component. Via the context, you can access the request object,
130           share data between components, and control the flow of your
131           application. Building a Catalyst application feels a lot like
132           snapping together toy building blocks, and everything just works.
133
134       ·   Component Auto-Discovery
135
136           No need to "use" all of your components. Catalyst automatically
137           finds and loads them.
138
139       ·   Pre-Built Components for Popular Modules
140
141           See Catalyst::Model::DBIC::Schema for DBIx::Class, or
142           Catalyst::View::TT for Template Toolkit.
143
144       ·   Built-in Test Framework
145
146           Catalyst comes with a built-in, lightweight http server and test
147           framework, making it easy to test applications from the web
148           browser, and the command line.
149
150       ·   Helper Scripts
151
152           Catalyst provides helper scripts to quickly generate running
153           starter code for components and unit tests. Install Catalyst::Devel
154           and see Catalyst::Helper.
155
156   Quickstart
157       Here's how to install Catalyst and get a simple application up and
158       running, using the helper scripts described above.
159
160       Install
161
162       Installation of Catalyst should be straightforward:
163
164           # perl -MCPAN -e 'install Catalyst::Runtime'
165           # perl -MCPAN -e 'install Catalyst::Devel'
166
167       Setup
168
169           $ catalyst.pl MyApp
170           # output omitted
171           $ cd MyApp
172           $ script/myapp_create.pl controller Library::Login
173
174       Frank Speiser's Amazon EC2 Catalyst SDK
175
176       There are currently two flavors of publicly available Amazon Machine
177       Images (AMI) that include all the elements you'd need to begin
178       developing in a fully functional Catalyst environment within minutes.
179       See Catalyst::Manual::Installation for more details.
180
181       Run
182
183           $ script/myapp_server.pl
184
185       Now visit these locations with your favorite browser or user agent to
186       see Catalyst in action:
187
188       (NOTE: Although we create a controller here, we don't actually use it.
189       Both of these URLs should take you to the welcome page.)
190
191       http://localhost:3000/
192       http://localhost:3000/library/login/
193
194   How It Works
195       Let's see how Catalyst works, by taking a closer look at the components
196       and other parts of a Catalyst application.
197
198       Components
199
200       Catalyst has an uncommonly flexible component system. You can define as
201       many "Models", "Views", and "Controllers" as you like. As discussed
202       previously, the general idea is that the View is responsible for the
203       output of data to the user (typically via a web browser, but a View can
204       also generate PDFs or e-mails, for example); the Model is responsible
205       for providing data (typically from a relational database); and the
206       Controller is responsible for interacting with the user and deciding
207       how user input determines what actions the application takes.
208
209       In the world of MVC, there are frequent discussions and disagreements
210       about the nature of each element - whether certain types of logic
211       belong in the Model or the Controller, etc. Catalyst's flexibility
212       means that this decision is entirely up to you, the programmer;
213       Catalyst doesn't enforce anything. See Catalyst::Manual::About for a
214       general discussion of these issues.
215
216       Model, View and Controller components must inherit from
217       Catalyst::Model, Catalyst::View and Catalyst::Controller, respectively.
218       These, in turn, inherit from Catalyst::Component which provides a
219       simple class structure and some common class methods like "config" and
220       "new" (constructor).
221
222           package MyApp::Controller::Catalog;
223           use Moose;
224           use namespace::autoclean;
225
226           BEGIN { extends 'Catalyst::Controller' }
227
228           __PACKAGE__->config( foo => 'bar' );
229
230           1;
231
232       You don't have to "use" or otherwise register Models, Views, and
233       Controllers.  Catalyst automatically discovers and instantiates them
234       when you call "setup" in the main application. All you need to do is
235       put them in directories named for each Component type. You can use a
236       short alias for each one.
237
238       ·   MyApp/Model/
239
240       ·   MyApp/M/
241
242       ·   MyApp/View/
243
244       ·   MyApp/V/
245
246       ·   MyApp/Controller/
247
248       ·   MyApp/C/
249
250       In older versions of Catalyst, the recommended practice (and the one
251       automatically created by helper scripts) was to name the directories
252       "M/", "V/", and "C/". Though these still work, they are deprecated and
253       we now recommend the use of the full names.
254
255       Views
256
257       To show how to define views, we'll use an already-existing base class
258       for the Template Toolkit, Catalyst::View::TT. All we need to do is
259       inherit from this class:
260
261           package MyApp::View::TT;
262
263           use strict;
264           use base 'Catalyst::View::TT';
265
266           1;
267
268       (You can also generate this automatically by using the helper script:
269
270           script/myapp_create.pl view TT TT
271
272       where the first "TT" tells the script that the name of the view should
273       be "TT", and the second that it should be a Template Toolkit view.)
274
275       This gives us a process() method and we can now just do
276       $c->forward('MyApp::View::TT') to render our templates. The base class
277       makes process() implicit, so we don't have to say
278       "$c->forward(qw/MyApp::View::TT process/)".
279
280           sub hello : Global {
281               my ( $self, $c ) = @_;
282               $c->stash->{template} = 'hello.tt';
283           }
284
285           sub end : Private {
286               my ( $self, $c ) = @_;
287               $c->forward( $c->view('TT') );
288           }
289
290       You normally render templates at the end of a request, so it's a
291       perfect use for the global "end" action.
292
293       In practice, however, you would use a default "end" action as supplied
294       by Catalyst::Action::RenderView.
295
296       Also, be sure to put the template under the directory specified in
297       "$c->config->{root}", or you'll end up looking at the debug screen.
298
299       Models
300
301       Models are providers of data. This data could come from anywhere - a
302       search engine index, a spreadsheet, the file system - but typically a
303       Model represents a database table. The data source does not
304       intrinsically have much to do with web applications or Catalyst - it
305       could just as easily be used to write an offline report generator or a
306       command-line tool.
307
308       To show how to define models, again we'll use an already-existing base
309       class, this time for DBIx::Class: Catalyst::Model::DBIC::Schema.  We'll
310       also need DBIx::Class::Schema::Loader.
311
312       But first, we need a database.
313
314           -- myapp.sql
315           CREATE TABLE foo (
316               id INTEGER PRIMARY KEY,
317               data TEXT
318           );
319
320           CREATE TABLE bar (
321               id INTEGER PRIMARY KEY,
322               foo INTEGER REFERENCES foo,
323               data TEXT
324           );
325
326           INSERT INTO foo (data) VALUES ('TEST!');
327
328           % sqlite3 /tmp/myapp.db < myapp.sql
329
330       Now we can create a DBIC::Schema model for this database.
331
332           script/myapp_create.pl model MyModel DBIC::Schema MySchema create=static 'dbi:SQLite:/tmp/myapp.db'
333
334       DBIx::Class::Schema::Loader can automatically load table layouts and
335       relationships, and convert them into a static schema definition
336       "MySchema", which you can edit later.
337
338       Use the stash to pass data to your templates.
339
340       We add the following to MyApp/Controller/Root.pm
341
342           sub view : Global {
343               my ( $self, $c, $id ) = @_;
344
345               $c->stash->{item} = $c->model('MyModel::Foo')->find($id);
346           }
347
348           1;
349
350           sub end : Private {
351               my ( $self, $c ) = @_;
352
353               $c->stash->{template} ||= 'index.tt';
354               $c->forward( $c->view('TT') );
355           }
356
357       We then create a new template file "root/index.tt" containing:
358
359           The Id's data is [% item.data %]
360
361       Models do not have to be part of your Catalyst application; you can
362       always call an outside module that serves as your Model:
363
364           # in a Controller
365           sub list : Local {
366             my ( $self, $c ) = @_;
367
368             $c->stash->{template} = 'list.tt';
369
370             use Some::Outside::Database::Module;
371             my @records = Some::Outside::Database::Module->search({
372               artist => 'Led Zeppelin',
373               });
374
375             $c->stash->{records} = \@records;
376           }
377
378       But by using a Model that is part of your Catalyst application, you
379       gain several things: you don't have to "use" each component, Catalyst
380       will find and load it automatically at compile-time; you can "forward"
381       to the module, which can only be done to Catalyst components.  Only
382       Catalyst components can be fetched with "$c->model('SomeModel')".
383
384       Happily, since many people have existing Model classes that they would
385       like to use with Catalyst (or, conversely, they want to write Catalyst
386       models that can be used outside of Catalyst, e.g.  in a cron job), it's
387       trivial to write a simple component in Catalyst that slurps in an
388       outside Model:
389
390           package MyApp::Model::DB;
391           use base qw/Catalyst::Model::DBIC::Schema/;
392           __PACKAGE__->config(
393               schema_class => 'Some::DBIC::Schema',
394               connect_info => ['dbi:SQLite:foo.db', '', '', {AutoCommit=>1}]
395           );
396           1;
397
398       and that's it! Now "Some::DBIC::Schema" is part of your Cat app as
399       "MyApp::Model::DB".
400
401       Within Catalyst, the common approach to writing a model for your
402       application is wrapping a generic model (e.g. DBIx::Class::Schema, a
403       bunch of XMLs, or anything really) with an object that contains
404       configuration data, convenience methods, and so forth. Thus you will in
405       effect have two models - a wrapper model that knows something about
406       Catalyst and your web application, and a generic model that is totally
407       independent of these needs.
408
409       Technically, within Catalyst a model is a component - an instance of
410       the model's class belonging to the application. It is important to
411       stress that the lifetime of these objects is per application, not per
412       request.
413
414       While the model base class (Catalyst::Model) provides things like
415       "config" to better integrate the model into the application, sometimes
416       this is not enough, and the model requires access to $c itself.
417
418       Situations where this need might arise include:
419
420       ·   Interacting with another model
421
422       ·   Using per-request data to control behavior
423
424       ·   Using plugins from a Model (for example Catalyst::Plugin::Cache).
425
426       From a style perspective it's usually considered bad form to make your
427       model "too smart" about things - it should worry about business logic
428       and leave the integration details to the controllers. If, however, you
429       find that it does not make sense at all to use an auxillary controller
430       around the model, and the model's need to access $c cannot be
431       sidestepped, there exists a power tool called "ACCEPT_CONTEXT".
432
433       Controllers
434
435       Multiple controllers are a good way to separate logical domains of your
436       application.
437
438           package MyApp::Controller::Login;
439
440           use base qw/Catalyst::Controller/;
441
442           sub login : Path("login") { }
443           sub new_password : Path("new-password") { }
444           sub logout : Path("logout") { }
445
446           package MyApp::Controller::Catalog;
447
448           use base qw/Catalyst::Controller/;
449
450           sub view : Local { }
451           sub list : Local { }
452
453           package MyApp::Controller::Cart;
454
455           use base qw/Catalyst::Controller/;
456
457           sub add : Local { }
458           sub update : Local { }
459           sub order : Local { }
460
461       Note that you can also supply attributes via the Controller's config so
462       long as you have at least one attribute on a subref to be exported
463       (:Action is commonly used for this) - for example the following is
464       equivalent to the same controller above:
465
466           package MyApp::Controller::Login;
467
468           use base qw/Catalyst::Controller/;
469
470           __PACKAGE__->config(
471             actions => {
472               'sign_in' => { Path => 'sign-in' },
473               'new_password' => { Path => 'new-password' },
474               'sign_out' => { Path => 'sign-out' },
475             },
476           );
477
478           sub sign_in : Action { }
479           sub new_password : Action { }
480           sub sign_out : Action { }
481
482       ACCEPT_CONTEXT
483
484       Whenever you call $c->component("Foo") you get back an object - the
485       instance of the model. If the component supports the "ACCEPT_CONTEXT"
486       method instead of returning the model itself, the return value of
487       "$model->ACCEPT_CONTEXT( $c )" will be used.
488
489       This means that whenever your model/view/controller needs to talk to $c
490       it gets a chance to do this when it's needed.
491
492       A typical "ACCEPT_CONTEXT" method will either clone the model and
493       return one with the context object set, or it will return a thin
494       wrapper that contains $c and delegates to the per-application model
495       object.
496
497       Generally it's a bad idea to expose the context object ($c) in your
498       model or view code.  Instead you use the "ACCEPT_CONTEXT" subroutine to
499       grab the bits of the context object that you need, and provide
500       accessors to them in the model.  This ensures that $c is only in scope
501       where it is neaded which reduces maintenance and debugging headaches.
502       So, if for example you needed two Catalyst::Model::DBIC::Schema models
503       in the same Catalyst model code, you might do something like this:
504
505        __PACKAGE__->mk_accessors(qw(model1_schema model2_schema));
506        sub ACCEPT_CONTEXT {
507            my ( $self, $c, @extra_arguments ) = @_;
508            $self = bless({ %$self,
509                    model1_schema  => $c->model('Model1')->schema,
510                    model2_schema => $c->model('Model2')->schema
511                }, ref($self));
512            return $self;
513        }
514
515       This effectively treats $self as a prototype object that gets a new
516       parameter.  @extra_arguments comes from any trailing arguments to
517       "$c->component( $bah, @extra_arguments )" (or "$c->model(...)",
518       "$c->view(...)" etc).
519
520       In a subroutine in the  model code, we can then do this:
521
522        sub whatever {
523            my ($self) = @_;
524            my $schema1 = $self->model1_schema;
525            my $schema2 = $self->model2_schema;
526            ...
527        }
528
529       Note that we still want the Catalyst models to be a thin wrapper around
530       classes that will work independently of the Catalyst application to
531       promote reusability of code.  Here we might just want to grab the
532       $c->model('DB')->schema so as to get the connection information from
533       the Catalyst application's configuration for example.
534
535       The life time of this value is per usage, and not per request. To make
536       this per request you can use the following technique:
537
538       Add a field to $c, like "my_model_instance". Then write your
539       "ACCEPT_CONTEXT" method to look like this:
540
541           sub ACCEPT_CONTEXT {
542             my ( $self, $c ) = @_;
543
544             if ( my $per_request = $c->my_model_instance ) {
545               return $per_request;
546             } else {
547               my $new_instance = bless { %$self, c => $c }, ref($self);
548               Scalar::Util::weaken($new_instance->{c}); # or we have a circular reference
549               $c->my_model_instance( $new_instance );
550               return $new_instance;
551             }
552           }
553
554       For a similar technique to grab a new component instance on each
555       request, see Catalyst::Component::InstancePerContext.
556
557       Application Class
558
559       In addition to the Model, View, and Controller components, there's a
560       single class that represents your application itself. This is where you
561       configure your application, load plugins, and extend Catalyst.
562
563           package MyApp;
564
565           use strict;
566           use parent qw/Catalyst/;
567           use Catalyst qw/-Debug ConfigLoader Static::Simple/;
568           MyApp->config(
569               name => 'My Application',
570
571               # You can put anything else you want in here:
572               my_configuration_variable => 'something',
573           );
574           1;
575
576       In older versions of Catalyst, the application class was where you put
577       global actions. However, as of version 5.66, the recommended practice
578       is to place such actions in a special Root controller (see "Actions",
579       below), to avoid namespace collisions.
580
581       ·   name
582
583           The name of your application.
584
585       Optionally, you can specify a root parameter for templates and static
586       data.  If omitted, Catalyst will try to auto-detect the directory's
587       location. You can define as many parameters as you want for plugins or
588       whatever you need. You can access them anywhere in your application via
589       "$context->config->{$param_name}".
590
591       Context
592
593       Catalyst automatically blesses a Context object into your application
594       class and makes it available everywhere in your application. Use the
595       Context to directly interact with Catalyst and glue your "Components"
596       together. For example, if you need to use the Context from within a
597       Template Toolkit template, it's already there:
598
599           <h1>Welcome to [% c.config.name %]!</h1>
600
601       As illustrated in our URL-to-Action dispatching example, the Context is
602       always the second method parameter, behind the Component object
603       reference or class name itself. Previously we called it $context for
604       clarity, but most Catalyst developers just call it $c:
605
606           sub hello : Global {
607               my ( $self, $c ) = @_;
608               $c->res->body('Hello World!');
609           }
610
611       The Context contains several important objects:
612
613       ·   Catalyst::Request
614
615               $c->request
616               $c->req # alias
617
618           The request object contains all kinds of request-specific
619           information, like query parameters, cookies, uploads, headers, and
620           more.
621
622               $c->req->params->{foo};
623               $c->req->cookies->{sessionid};
624               $c->req->headers->content_type;
625               $c->req->base;
626               $c->req->uri_with( { page = $pager->next_page } );
627
628       ·   Catalyst::Response
629
630               $c->response
631               $c->res # alias
632
633           The response is like the request, but contains just response-
634           specific information.
635
636               $c->res->body('Hello World');
637               $c->res->status(404);
638               $c->res->redirect('http://oook.de');
639
640       ·   config
641
642               $c->config
643               $c->config->{root};
644               $c->config->{name};
645
646       ·   Catalyst::Log
647
648               $c->log
649               $c->log->debug('Something happened');
650               $c->log->info('Something you should know');
651
652       ·   Stash
653
654               $c->stash
655               $c->stash->{foo} = 'bar';
656               $c->stash->{baz} = {baz => 'qox'};
657               $c->stash->{fred} = [qw/wilma pebbles/];
658
659           and so on.
660
661       The last of these, the stash, is a universal hash for sharing data
662       among application components. For an example, we return to our 'hello'
663       action:
664
665           sub hello : Global {
666               my ( $self, $c ) = @_;
667               $c->stash->{message} = 'Hello World!';
668               $c->forward('show_message');
669           }
670
671           sub show_message : Private {
672               my ( $self, $c ) = @_;
673               $c->res->body( $c->stash->{message} );
674           }
675
676       Note that the stash should be used only for passing data in an
677       individual request cycle; it gets cleared at a new request. If you need
678       to maintain persistent data, use a session. See
679       Catalyst::Plugin::Session for a comprehensive set of Catalyst-friendly
680       session-handling tools.
681
682       Actions
683
684       You've already seen some examples of actions in this document:
685       subroutines with ":Path" and ":Local" attributes attached.  Here, we
686       explain what actions are and how these attributes affect what's
687       happening.
688
689       When Catalyst processes a webpage request, it looks for actions to take
690       that will deal with the incoming request and produce a response such as
691       a webpage.  You create these actions for your application by writing
692       subroutines within your controller and marking them with special
693       attributes.  The attributes, the namespace, and the function name
694       determine when Catalyst will call the subroutine.
695
696       These action subroutines call certain functions to say what response
697       the webserver will give to the web request.  They can also tell
698       Catalyst to run other actions on the request (one example of this is
699       called forwarding the request; this is discussed later).
700
701       Action subroutines must have a special attribute on to show that they
702       are actions - as well as marking when to call them, this shows that
703       they take a specific set of arguments and behave in a specific way.  At
704       startup, Catalyst looks for all the actions in controllers, registers
705       them and creates Catalyst::Action objects describing them.  When
706       requests come in, Catalyst chooses which actions should be called to
707       handle the request.
708
709       (Occasionally, you might use the action objects directly, but in
710       general, when we talk about actions, we're talking about the
711       subroutines in your application that do things to process a request.)
712
713       You can choose one of several attributes for action subroutines; these
714       specify which requests are processed by that subroutine.  Catalyst will
715       look at the URL it is processing, and the actions that it has found,
716       and automatically call the actions it finds that match the
717       circumstances of the request.
718
719       The URL (for example http://localhost.3000/foo/bar) consists of two
720       parts, the base, describing how to connect to the server
721       (http://localhost:3000/ in this example) and the path, which the server
722       uses to decide what to return (foo/bar).  Please note that the trailing
723       slash after the hostname[:port] always belongs to base and not to the
724       path.  Catalyst uses only the path part when trying to find actions to
725       process.
726
727       Depending on the type of action used, the URLs may match a combination
728       of the controller namespace, the arguments passed to the action
729       attribute, and the name of the subroutine.
730
731       ·   Controller namespaces
732
733           The namespace is a modified form of the component's class (package)
734           name. This modified class name excludes the parts that have a pre-
735           defined meaning in Catalyst ("MyApp::Controller" in the above
736           example), replaces "::" with "/", and converts the name to lower
737           case.  See "Components" for a full explanation of the pre-defined
738           meaning of Catalyst component class names.
739
740       ·   Overriding the namespace
741
742           Note that __PACKAGE__->config->{namespace} can be used to override
743           the current namespace when matching.  So:
744
745               package MyApp::Controller::Example;
746
747           would normally use 'example' as its namespace for matching, but if
748           this is specially overridden with
749
750               __PACKAGE__->config->{namespace}='thing';
751
752           it matches using the namespace 'thing' instead.
753
754       ·   Application Wide Actions
755
756           MyApp::Controller::Root, as created by the catalyst.pl script, will
757           typically contain actions which are called for the top level of the
758           application (e.g. http://localhost:3000/ ):
759
760               package MyApp::Controller::Root;
761               use base 'Catalyst::Controller';
762               # Sets the actions in this controller to be registered with no prefix
763               # so they function identically to actions created in MyApp.pm
764               __PACKAGE__->config->{namespace} = '';
765               sub default : Path  {
766                   my ( $self, $context ) = @_;
767                   $context->response->status(404);
768                   $context->response->body('404 not found');
769               }
770               1;
771
772           The code
773
774               __PACKAGE__->config->{namespace} = '';
775
776           makes the controller act as if its namespace is empty.  As you'll
777           see below, an empty namespace makes many of the URL-matching
778           attributes, such as :Path, :Local and :Global matches, match at the
779           start of the URL path.
780
781       Action types
782
783       Catalyst supports several types of actions.  These mainly correspond to
784       ways of matching a URL to an action subroutine.  Internally, these
785       matching types are implemented by Catalyst::DispatchType-derived
786       classes; the documentation there can be helpful in seeing how they
787       work.
788
789       They will all attempt to match the start of the path.  The remainder of
790       the path is passed as arguments.
791
792       ·   Namespace-prefixed (":Local")
793
794               package MyApp::Controller::My::Controller;
795               sub foo : Local { }
796
797           Matches any URL beginning with>
798           http://localhost:3000/my/controller/foo. The namespace and
799           subroutine name together determine the path.
800
801       ·   Root-level (":Global")
802
803               package MyApp::Controller::Foo;
804               sub foo : Global { }
805
806           Matches http://localhost:3000/foo - that is, the action is mapped
807           directly to the controller namespace, ignoring the function name.
808
809           ":Global" always matches from root: it is sugar for
810           ":Path('/methodname')".  ":Local" is simply sugar for
811           ":Path('methodname')", which takes the package namespace as
812           described above.
813
814               package MyApp::Controller::Root;
815               __PACKAGE__->config->{namespace}='';
816               sub foo : Local { }
817
818           Use whichever makes the most sense for your application.
819
820       ·   Changing handler behaviour: eating arguments (":Args")
821
822           Args is not an action type per se, but an action modifier - it adds
823           a match restriction to any action it's provided to, additionally
824           requiring as many path parts as are specified for the action to be
825           matched. For example, in MyApp::Controller::Foo,
826
827             sub bar :Local
828
829           would match any URL starting /foo/bar. To restrict this you can do
830
831             sub bar :Local :Args(1)
832
833           to only match URLs starting /foo/bar/* - with one additional path
834           element required after 'bar'.
835
836           NOTE that adding :Args(0) and missing out :Args completely are not
837           the same thing.
838
839           :Args(0) means that no arguments are taken.  Thus, the URL and path
840           must match precisely.
841
842           No :Args at all means that any number of arguments are taken.
843           Thus, any URL that starts with the controller's path will match.
844           Obviously, this means you cannot chain from an action that does not
845           specify args, as the next action in the chain will be swallowed as
846           an arg to the first!
847
848       ·   Literal match (":Path")
849
850           "Path" actions match things starting with a precise specified path,
851           and nothing else.
852
853           "Path" actions without a leading forward slash match a specified
854           path relative to their current namespace. This example matches URLs
855           starting http://localhost:3000/my/controller/foo/bar :
856
857               package MyApp::Controller::My::Controller;
858               sub bar : Path('foo/bar') { }
859
860           "Path" actions with a leading slash ignore their namespace, and
861           match from the start of the URL path. Example:
862
863               package MyApp::Controller::My::Controller;
864               sub bar : Path('/foo/bar') { }
865
866           This matches URLs beginning http://localhost:3000/foo/bar.
867
868           Empty "Path" definitions match on the namespace only, exactly like
869           ":Global".
870
871               package MyApp::Controller::My::Controller;
872               sub bar : Path { }
873
874           The above code matches http://localhost:3000/my/controller.
875
876           Actions with the ":Local" attribute are similarly equivalent to
877           ":Path('action_name')":
878
879               sub foo : Local { }
880
881           is equivalent to
882
883               sub foo : Path('foo') { }
884
885       ·   Pattern-match (":Regex" and ":LocalRegex")
886
887               package MyApp::Controller::My::Controller;
888               sub bar : Regex('^item(\d+)/order(\d+)$') { }
889
890           This matches any URL that matches the pattern in the action key,
891           e.g.  http://localhost:3000/item23/order42. The '' around the
892           regexp is optional, but perltidy likes it. :)
893
894           ":Regex" matches act globally, i.e. without reference to the
895           namespace from which they are called.  So the above will not match
896           http://localhost:3000/my/controller/item23/order42 - use a
897           ":LocalRegex" action instead.
898
899               package MyApp::Controller::My::Controller;
900               sub bar : LocalRegex('^widget(\d+)$') { }
901
902           ":LocalRegex" actions act locally, i.e. the namespace is matched
903           first. The above example would match urls like
904           http://localhost:3000/my/controller/widget23.
905
906           If you omit the ""^"" from either sort of regex, then it will match
907           any depth from the base path:
908
909               package MyApp::Controller::Catalog;
910               sub bar : LocalRegex('widget(\d+)$') { }
911
912           This differs from the previous example in that it will match
913           http://localhost:3000/my/controller/foo/widget23 - and a number of
914           other paths.
915
916           For both ":LocalRegex" and ":Regex" actions, if you use capturing
917           parentheses to extract values within the matching URL, those values
918           are available in the "$c->req->captures" array. In the above
919           example, "widget23" would capture "23" in the above example, and
920           "$c->req->captures->[0]" would be "23". If you want to pass
921           arguments at the end of your URL, you must use regex action keys.
922           See "URL Path Handling" below.
923
924       ·   Chained handlers (":Chained")
925
926           Catalyst also provides a method to build and dispatch chains of
927           actions, like
928
929               sub catalog : Chained : CaptureArgs(1) {
930                   my ( $self, $c, $arg ) = @_;
931                   ...
932               }
933
934               sub item : Chained('catalog') : Args(1) {
935                   my ( $self, $c, $arg ) = @_;
936                   ...
937               }
938
939           to handle a "/catalog/*/item/*" path.  Matching actions are called
940           one after another - "catalog()" gets called and handed one path
941           element, then "item()" gets called with another one.  For further
942           information about this dispatch type, please see
943           Catalyst::DispatchType::Chained.
944
945       ·   Private
946
947               sub foo : Private { }
948
949           This will never match a URL - it provides a private action which
950           can be called programmatically from within Catalyst, but is never
951           called automatically due to the URL being requested.
952
953           Catalyst's ":Private" attribute is exclusive and doesn't work with
954           other attributes (so will not work combined with ":Path" or
955           ":Chained" attributes, for instance).
956
957           Private actions can only be executed explicitly from inside a
958           Catalyst application.  You might do this in your controllers by
959           calling catalyst methods such as "forward" or "detach" to fire
960           them:
961
962               $c->forward('foo');
963               # or
964               $c->detach('foo');
965
966           See "Flow Control" for a full explanation of how you can pass
967           requests on to other actions. Note that, as discussed there, when
968           forwarding from another component, you must use the absolute path
969           to the method, so that a private "bar" method in your
970           "MyApp::Controller::Catalog::Order::Process" controller must, if
971           called from elsewhere, be reached with
972           "$c->forward('/catalog/order/process/bar')".
973
974       Note: After seeing these examples, you probably wonder what the point
975       is of defining subroutine names for regex and path actions. However,
976       every public action is also a private one with a path corresponding to
977       its namespace and subroutine name, so you have one unified way of
978       addressing components in your "forward"s.
979
980       Built-in special actions
981
982       If present, the special actions " index ", " auto ", "begin", "end" and
983       " default " are called at certain points in the request cycle.
984
985       In response to specific application states, Catalyst will automatically
986       call these built-in actions in your application class:
987
988       ·   default : Path
989
990           This is called when no other action matches. It could be used, for
991           example, for displaying a generic frontpage for the main app, or an
992           error page for individual controllers. Note: in older Catalyst
993           applications you will see "default : Private" which is roughly
994           speaking equivalent.
995
996       ·   index : Path : Args (0)
997
998           "index" is much like "default" except that it takes no arguments
999           and it is weighted slightly higher in the matching process. It is
1000           useful as a static entry point to a controller, e.g. to have a
1001           static welcome page. Note that it's also weighted higher than Path.
1002           Actually the sub name "index" can be called anything you want.  The
1003           sub attributes are what determines the behaviour of the action.
1004           Note: in older Catalyst applications, you will see "index :
1005           Private" used, which is roughly speaking equivalent.
1006
1007       ·   begin : Private
1008
1009           Called at the beginning of a request, once the controller that will
1010           run has been identified, but before any URL-matching actions are
1011           called.  Catalyst will call the "begin" function in the controller
1012           which contains the action matching the URL.
1013
1014       ·   end : Private
1015
1016           Called at the end of a request, after all URL-matching actions are
1017           called.  Catalyst will call the "end" function in the controller
1018           which contains the action matching the URL.
1019
1020       ·   auto : Private
1021
1022           In addition to the normal built-in actions, you have a special
1023           action for making chains, "auto". "auto" actions will be run after
1024           any "begin", but before your URL-matching action is processed.
1025           Unlike the other built-ins, multiple "auto" actions can be called;
1026           they will be called in turn, starting with the application class
1027           and going through to the most specific class.
1028
1029       Built-in actions in controllers/autochaining
1030
1031           package MyApp::Controller::Foo;
1032           sub begin : Private { }
1033           sub default : Path  { }
1034           sub end : Path  { }
1035
1036       You can define built-in actions within your controllers as well as on
1037       your application class. In other words, for each of the three built-in
1038       actions above, only one will be run in any request cycle. Thus, if
1039       "MyApp::Controller::Catalog::begin" exists, it will be run in place of
1040       "MyApp::begin" if you're in the "catalog" namespace, and
1041       "MyApp::Controller::Catalog::Order::begin" would override this in turn.
1042
1043           sub auto : Private { }
1044
1045       "auto", however, doesn't override like this: providing they exist,
1046       "MyApp::auto", "MyApp::Controller::Catalog::auto" and
1047       "MyApp::Catalog::Order::auto" would be called in turn.
1048
1049       Here are some examples of the order in which the various built-ins
1050       would be called:
1051
1052       for a request for "/foo/foo"
1053             MyApp::Controller::Foo::auto
1054             MyApp::Controller::Foo::default # in the absence of MyApp::Controller::Foo::Foo
1055             MyApp::Controller::Foo::end
1056
1057       for a request for "/foo/bar/foo"
1058             MyApp::Controller::Foo::Bar::begin
1059             MyApp::Controller::Foo::auto
1060             MyApp::Controller::Foo::Bar::auto
1061             MyApp::Controller::Foo::Bar::default # for MyApp::Controller::Foo::Bar::foo
1062             MyApp::Controller::Foo::Bar::end
1063
1064       The "auto" action is also distinguished by the fact that you can break
1065       out of the processing chain by returning 0. If an "auto" action returns
1066       0, any remaining actions will be skipped, except for "end". So, for the
1067       request above, if the first auto returns false, the chain would look
1068       like this:
1069
1070       for a request for "/foo/bar/foo" where first "auto" returns false
1071             MyApp::Controller::Foo::Bar::begin
1072             MyApp::Controller::Foo::auto # returns false, skips some calls:
1073             # MyApp::Controller::Foo::Bar::auto - never called
1074             # MyApp::Controller::Foo::Bar::foo - never called
1075             MyApp::Controller::Foo::Bar::end
1076
1077           You can also "die" in the auto action; in that case, the request
1078           will go straight to the finalize stage, without processing further
1079           actions. So in the above example,
1080           "MyApp::Controller::Foo::Bar::end" is skipped as well.
1081
1082       An example of why one might use "auto" is an authentication action: you
1083       could set up a "auto" action to handle authentication in your
1084       application class (which will always be called first), and if
1085       authentication fails, returning 0 would skip any remaining methods for
1086       that URL.
1087
1088       Note: Looking at it another way, "auto" actions have to return a true
1089       value to continue processing!
1090
1091       URL Path Handling
1092
1093       You can pass arguments as part of the URL path, separated with forward
1094       slashes (/). If the action is a Regex or LocalRegex, the '$' anchor
1095       must be used. For example, suppose you want to handle "/foo/$bar/$baz",
1096       where $bar and $baz may vary:
1097
1098           sub foo : Regex('^foo$') { my ($self, $context, $bar, $baz) = @_; }
1099
1100       But what if you also defined actions for "/foo/boo" and "/foo/boo/hoo"?
1101
1102           sub boo : Path('foo/boo') { .. }
1103           sub hoo : Path('foo/boo/hoo') { .. }
1104
1105       Catalyst matches actions in most specific to least specific order -
1106       that is, whatever matches the most pieces of the path wins:
1107
1108           /foo/boo/hoo
1109           /foo/boo
1110           /foo # might be /foo/bar/baz but won't be /foo/boo/hoo
1111
1112       So Catalyst would never mistakenly dispatch the first two URLs to the
1113       '^foo$' action.
1114
1115       If a Regex or LocalRegex action doesn't use the '$' anchor, the action
1116       will still match a URL containing arguments; however the arguments
1117       won't be available via @_, because the Regex will 'eat' them.
1118
1119       Beware!  If you write two matchers, that match the same path, with the
1120       same specificity (that is, they match the same quantity of the path),
1121       there's no guarantee which will actually get called.  Non-regex
1122       matchers get tried first, followed by regex ones, but if you have, for
1123       instance:
1124
1125          package MyApp::Controller::Root;
1126
1127          sub match1 :Path('/a/b') { }
1128
1129          package MyApp::Controller::A;
1130
1131          sub b :Local { } # Matches /a/b
1132
1133       then Catalyst will call the one it finds first.  In summary, Don't Do
1134       This.
1135
1136       Query Parameter Processing
1137
1138       Parameters passed in the URL query string are handled with methods in
1139       the Catalyst::Request class. The "param" method is functionally
1140       equivalent to the "param" method of "CGI.pm" and can be used in modules
1141       that require this.
1142
1143           # http://localhost:3000/catalog/view/?category=hardware&page=3
1144           my $category = $c->req->param('category');
1145           my $current_page = $c->req->param('page') || 1;
1146
1147           # multiple values for single parameter name
1148           my @values = $c->req->param('scrolling_list');
1149
1150           # DFV requires a CGI.pm-like input hash
1151           my $results = Data::FormValidator->check($c->req->params, \%dfv_profile);
1152
1153       Flow Control
1154
1155       You control the application flow with the "forward" method, which
1156       accepts the key of an action to execute. This can be an action in the
1157       same or another Catalyst controller, or a Class name, optionally
1158       followed by a method name. After a "forward", the control flow will
1159       return to the method from which the "forward" was issued.
1160
1161       A "forward" is similar to a method call. The main differences are that
1162       it wraps the call in an "eval" to allow exception handling; it
1163       automatically passes along the context object ($c or $context); and it
1164       allows profiling of each call (displayed in the log with debugging
1165       enabled).
1166
1167           sub hello : Global {
1168               my ( $self, $c ) = @_;
1169               $c->stash->{message} = 'Hello World!';
1170               $c->forward('check_message'); # $c is automatically included
1171           }
1172
1173           sub check_message : Private {
1174               my ( $self, $c ) = @_;
1175               return unless $c->stash->{message};
1176               $c->forward('show_message');
1177           }
1178
1179           sub show_message : Private {
1180               my ( $self, $c ) = @_;
1181               $c->res->body( $c->stash->{message} );
1182           }
1183
1184       A "forward" does not create a new request, so your request object
1185       ("$c->req") will remain unchanged. This is a key difference between
1186       using "forward" and issuing a redirect.
1187
1188       You can pass new arguments to a "forward" by adding them in an
1189       anonymous array. In this case "$c->req->args" will be changed for the
1190       duration of the "forward" only; upon return, the original value of
1191       "$c->req->args" will be reset.
1192
1193           sub hello : Global {
1194               my ( $self, $c ) = @_;
1195               $c->stash->{message} = 'Hello World!';
1196               $c->forward('check_message',[qw/test1/]);
1197               # now $c->req->args is back to what it was before
1198           }
1199
1200           sub check_message : Action {
1201               my ( $self, $c, $first_argument ) = @_;
1202               my $also_first_argument = $c->req->args->[0]; # now = 'test1'
1203               # do something...
1204           }
1205
1206       As you can see from these examples, you can just use the method name as
1207       long as you are referring to methods in the same controller. If you
1208       want to forward to a method in another controller, or the main
1209       application, you will have to refer to the method by absolute path.
1210
1211         $c->forward('/my/controller/action');
1212         $c->forward('/default'); # calls default in main application
1213
1214       You can also forward to classes and methods.
1215
1216           sub hello : Global {
1217               my ( $self, $c ) = @_;
1218               $c->forward(qw/MyApp::View:Hello say_hello/);
1219           }
1220
1221           sub bye : Global {
1222               my ( $self, $c ) = @_;
1223               $c->forward('MyApp::Model::Hello'); # no method: will try 'process'
1224           }
1225
1226           package MyApp::View::Hello;
1227
1228           sub say_hello {
1229               my ( $self, $c ) = @_;
1230               $c->res->body('Hello World!');
1231           }
1232
1233           sub process {
1234               my ( $self, $c ) = @_;
1235               $c->res->body('Goodbye World!');
1236           }
1237
1238       This mechanism is used by Catalyst::Action::RenderView to forward to
1239       the "process" method in a view class.
1240
1241       It should be noted that whilst forward is useful, it is not the only
1242       way of calling other code in Catalyst. Forward just gives you stats in
1243       the debug screen, wraps the code you're calling in an exception handler
1244       and localises "$c->request->args".
1245
1246       If you don't want or need these features then it's perfectly acceptable
1247       (and faster) to do something like this:
1248
1249           sub hello : Global {
1250               my ( $self, $c ) = @_;
1251               $c->stash->{message} = 'Hello World!';
1252               $self->check_message( $c, 'test1' );
1253           }
1254
1255           sub check_message {
1256               my ( $self, $c, $first_argument ) = @_;
1257               # do something...
1258           }
1259
1260       Note that "forward" returns to the calling action and continues
1261       processing after the action finishes. If you want all further
1262       processing in the calling action to stop, use "detach" instead, which
1263       will execute the "detach"ed action and not return to the calling sub.
1264       In both cases, Catalyst will automatically try to call process() if you
1265       omit the method.
1266
1267       Testing
1268
1269       Catalyst has a built-in http server for testing or local deployment.
1270       (Later, you can easily use a more powerful server, for example
1271       Apache/mod_perl or FastCGI, in a production environment.)
1272
1273       Start your application on the command line...
1274
1275           script/myapp_server.pl
1276
1277       ...then visit http://localhost:3000/ in a browser to view the output.
1278
1279       You can also do it all from the command line:
1280
1281           script/myapp_test.pl http://localhost/
1282
1283       Catalyst has a number of tools for actual regression testing of
1284       applications. The helper scripts will automatically generate basic
1285       tests that can be extended as you develop your project. To write your
1286       own comprehensive test scripts, Test::WWW::Mechanize::Catalyst is an
1287       invaluable tool.
1288
1289       For more testing ideas, see Catalyst::Manual::Tutorial::Testing.
1290
1291       Have fun!
1292

SEE ALSO

1294       ·   Catalyst::Manual::About
1295
1296       ·   Catalyst::Manual::Tutorial
1297
1298       ·   Catalyst
1299

SUPPORT

1301       IRC:
1302
1303           Join #catalyst on irc.perl.org.
1304           Join #catalyst-dev on irc.perl.org to help with development.
1305
1306       Mailing lists:
1307
1308           http://lists.scsys.co.uk/mailman/listinfo/catalyst
1309           http://lists.scsys.co.uk/mailman/listinfo/catalyst-dev
1310
1311       Wiki:
1312
1313           http://dev.catalystframework.org/wiki
1314
1315       FAQ:
1316
1317           http://dev.catalystframework.org/wiki/faq
1318

AUTHORS

1320       Catalyst Contributors, see Catalyst.pm
1321
1323       This library is free software. You can redistribute it and/or modify it
1324       under the same terms as Perl itself.
1325
1326
1327
1328perl v5.12.0                      2010-02-17        Catalyst::Manual::Intro(3)
Impressum