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

SEE ALSO

1308       •   Catalyst::Manual::About
1309
1310       •   Catalyst::Manual::Tutorial
1311
1312       •   Catalyst
1313

SUPPORT

1315       IRC:
1316
1317           Join #catalyst on irc.perl.org.
1318           Join #catalyst-dev on irc.perl.org to help with development.
1319
1320       Mailing lists:
1321
1322           http://lists.scsys.co.uk/mailman/listinfo/catalyst
1323           http://lists.scsys.co.uk/mailman/listinfo/catalyst-dev
1324
1325       Wiki:
1326
1327           http://dev.catalystframework.org/wiki
1328
1329       FAQ:
1330
1331           http://dev.catalystframework.org/wiki/faq
1332

AUTHORS

1334       Catalyst Contributors, see Catalyst.pm
1335
1337       This library is free software. You can redistribute it and/or modify it
1338       under the same terms as Perl itself.
1339
1340
1341
1342perl v5.36.0                      2022-07-22        Catalyst::Manual::Intro(3)
Impressum