convert to Distar
[catagits/Catalyst-Runtime.git] / README.mkdn
CommitLineData
9e7f288e 1# NAME
2
3Catalyst - The Elegant MVC Web Application Framework
4
9e7f288e 5# SYNOPSIS
6
7See the [Catalyst::Manual](https://metacpan.org/pod/Catalyst::Manual) distribution for comprehensive
8documentation and tutorials.
9
10 # Install Catalyst::Devel for helpers and other development tools
11 # use the helper to create a new application
12 catalyst.pl MyApp
13
14 # add models, views, controllers
15 script/myapp_create.pl model MyDatabase DBIC::Schema create=static dbi:SQLite:/path/to/db
16 script/myapp_create.pl view MyTemplate TT
17 script/myapp_create.pl controller Search
18
19 # built in testserver -- use -r to restart automatically on changes
20 # --help to see all available options
21 script/myapp_server.pl
22
23 # command line testing interface
24 script/myapp_test.pl /yada
25
26 ### in lib/MyApp.pm
27 use Catalyst qw/-Debug/; # include plugins here as well
28
29 ### In lib/MyApp/Controller/Root.pm (autocreated)
30 sub foo : Chained('/') Args() { # called for /foo, /foo/1, /foo/1/2, etc.
31 my ( $self, $c, @args ) = @_; # args are qw/1 2/ for /foo/1/2
32 $c->stash->{template} = 'foo.tt'; # set the template
33 # lookup something from db -- stash vars are passed to TT
34 $c->stash->{data} =
35 $c->model('Database::Foo')->search( { country => $args[0] } );
36 if ( $c->req->params->{bar} ) { # access GET or POST parameters
37 $c->forward( 'bar' ); # process another action
38 # do something else after forward returns
39 }
40 }
41
42 # The foo.tt TT template can use the stash data from the database
43 [% WHILE (item = data.next) %]
44 [% item.foo %]
45 [% END %]
46
47 # called for /bar/of/soap, /bar/of/soap/10, etc.
48 sub bar : Chained('/') PathPart('/bar/of/soap') Args() { ... }
49
50 # called after all actions are finished
51 sub end : Action {
52 my ( $self, $c ) = @_;
53 if ( scalar @{ $c->error } ) { ... } # handle errors
54 return if $c->res->body; # already have a response
55 $c->forward( 'MyApp::View::TT' ); # render template
56 }
57
58See [Catalyst::Manual::Intro](https://metacpan.org/pod/Catalyst::Manual::Intro) for additional information.
59
60# DESCRIPTION
61
62Catalyst is a modern framework for making web applications without the
63pain usually associated with this process. This document is a reference
64to the main Catalyst application. If you are a new user, we suggest you
65start with [Catalyst::Manual::Tutorial](https://metacpan.org/pod/Catalyst::Manual::Tutorial) or [Catalyst::Manual::Intro](https://metacpan.org/pod/Catalyst::Manual::Intro).
66
67See [Catalyst::Manual](https://metacpan.org/pod/Catalyst::Manual) for more documentation.
68
69Catalyst plugins can be loaded by naming them as arguments to the "use
70Catalyst" statement. Omit the `Catalyst::Plugin::` prefix from the
71plugin name, i.e., `Catalyst::Plugin::My::Module` becomes
72`My::Module`.
73
74 use Catalyst qw/My::Module/;
75
76If your plugin starts with a name other than `Catalyst::Plugin::`, you can
77fully qualify the name by using a unary plus:
78
79 use Catalyst qw/
80 My::Module
81 +Fully::Qualified::Plugin::Name
82 /;
83
84Special flags like `-Debug` can also be specified as
85arguments when Catalyst is loaded:
86
87 use Catalyst qw/-Debug My::Module/;
88
89The position of plugins and flags in the chain is important, because
90they are loaded in the order in which they appear.
91
92The following flags are supported:
93
94## -Debug
95
96Enables debug output. You can also force this setting from the system
97environment with CATALYST\_DEBUG or <MYAPP>\_DEBUG. The environment
98settings override the application, with <MYAPP>\_DEBUG having the highest
99priority.
100
101This sets the log level to 'debug' and enables full debug output on the
102error screen. If you only want the latter, see [$c->debug](https://metacpan.org/pod/$c->debug).
103
104## -Home
105
106Forces Catalyst to use a specific home directory, e.g.:
107
108 use Catalyst qw[-Home=/usr/mst];
109
110This can also be done in the shell environment by setting either the
111`CATALYST_HOME` environment variable or `MYAPP_HOME`; where `MYAPP`
112is replaced with the uppercased name of your application, any "::" in
113the name will be replaced with underscores, e.g. MyApp::Web should use
114MYAPP\_WEB\_HOME. If both variables are set, the MYAPP\_HOME one will be used.
115
116If none of these are set, Catalyst will attempt to automatically detect the
117home directory. If you are working in a development environment, Catalyst
118will try and find the directory containing either Makefile.PL, Build.PL,
119dist.ini, or cpanfile. If the application has been installed into the system
120(i.e. you have done `make install`), then Catalyst will use the path to your
121application module, without the .pm extension (e.g., /foo/MyApp if your
122application was installed at /foo/MyApp.pm)
123
124## -Log
125
126 use Catalyst '-Log=warn,fatal,error';
127
128Specifies a comma-delimited list of log levels.
129
130## -Stats
131
132Enables statistics collection and reporting.
133
134 use Catalyst qw/-Stats=1/;
135
136You can also force this setting from the system environment with CATALYST\_STATS
137or <MYAPP>\_STATS. The environment settings override the application, with
138<MYAPP>\_STATS having the highest priority.
139
140Stats are also enabled if [debugging ](#debug) is enabled.
141
142# METHODS
143
144## INFORMATION ABOUT THE CURRENT REQUEST
145
146## $c->action
147
148Returns a [Catalyst::Action](https://metacpan.org/pod/Catalyst::Action) object for the current action, which
149stringifies to the action name. See [Catalyst::Action](https://metacpan.org/pod/Catalyst::Action).
150
151## $c->namespace
152
153Returns the namespace of the current action, i.e., the URI prefix
154corresponding to the controller of the current action. For example:
155
156 # in Controller::Foo::Bar
157 $c->namespace; # returns 'foo/bar';
158
159## $c->request
160
161## $c->req
162
163Returns the current [Catalyst::Request](https://metacpan.org/pod/Catalyst::Request) object, giving access to
164information about the current client request (including parameters,
165cookies, HTTP headers, etc.). See [Catalyst::Request](https://metacpan.org/pod/Catalyst::Request).
166
167## REQUEST FLOW HANDLING
168
169## $c->forward( $action \[, \\@arguments \] )
170
171## $c->forward( $class, $method, \[, \\@arguments \] )
172
173This is one way of calling another action (method) in the same or
174a different controller. You can also use `$self->my_method($c, @args)`
175in the same controller or `$c->controller('MyController')->my_method($c, @args)`
176in a different controller.
177The main difference is that 'forward' uses some of the Catalyst request
178cycle overhead, including debugging, which may be useful to you. On the
179other hand, there are some complications to using 'forward', restrictions
180on values returned from 'forward', and it may not handle errors as you prefer.
181Whether you use 'forward' or not is up to you; it is not considered superior to
182the other ways to call a method.
183
184'forward' calls another action, by its private name. If you give a
185class name but no method, `process()` is called. You may also optionally
186pass arguments in an arrayref. The action will receive the arguments in
187`@_` and `$c->req->args`. Upon returning from the function,
188`$c->req->args` will be restored to the previous values.
189
190Any data `return`ed from the action forwarded to, will be returned by the
191call to forward.
192
193 my $foodata = $c->forward('/foo');
194 $c->forward('index');
195 $c->forward(qw/Model::DBIC::Foo do_stuff/);
196 $c->forward('View::TT');
197
198Note that [forward](#c-forward-action-arguments) implies
199an `eval { }` around the call (actually
200[execute](#c-execute-class-coderef) does), thus rendering all
201exceptions thrown by the called action non-fatal and pushing them onto
202$c->error instead. If you want `die` to propagate you need to do something
203like:
204
205 $c->forward('foo');
206 die join "\n", @{ $c->error } if @{ $c->error };
207
208Or make sure to always return true values from your actions and write
209your code like this:
210
211 $c->forward('foo') || return;
212
213Another note is that `$c->forward` always returns a scalar because it
214actually returns $c->state which operates in a scalar context.
215Thus, something like:
216
217 return @array;
218
219in an action that is forwarded to is going to return a scalar,
220i.e. how many items are in that array, which is probably not what you want.
221If you need to return an array then return a reference to it,
222or stash it like so:
223
224 $c->stash->{array} = \@array;
225
226and access it from the stash.
227
228Keep in mind that the `end` method used is that of the caller action. So a `$c->detach` inside a forwarded action would run the `end` method from the original action requested.
229
230## $c->detach( $action \[, \\@arguments \] )
231
232## $c->detach( $class, $method, \[, \\@arguments \] )
233
234## $c->detach()
235
236The same as [forward](#c-forward-action-arguments), but
237doesn't return to the previous action when processing is finished.
238
239When called with no arguments it escapes the processing chain entirely.
240
241## $c->visit( $action \[, \\@arguments \] )
242
243## $c->visit( $action \[, \\@captures, \\@arguments \] )
244
245## $c->visit( $class, $method, \[, \\@arguments \] )
246
247## $c->visit( $class, $method, \[, \\@captures, \\@arguments \] )
248
249Almost the same as [forward](#c-forward-action-arguments),
250but does a full dispatch, instead of just calling the new `$action` /
251`$class->$method`. This means that `begin`, `auto` and the method
252you go to are called, just like a new request.
253
254In addition both `$c->action` and `$c->namespace` are localized.
255This means, for example, that `$c->action` methods such as
256[name](https://metacpan.org/pod/Catalyst::Action#name), [class](https://metacpan.org/pod/Catalyst::Action#class) and
257[reverse](https://metacpan.org/pod/Catalyst::Action#reverse) return information for the visited action
258when they are invoked within the visited action. This is different from the
259behavior of [forward](#c-forward-action-arguments), which
260continues to use the $c->action object from the caller action even when
261invoked from the called action.
262
263`$c->stash` is kept unchanged.
264
265In effect, [visit](#c-visit-action-captures-arguments)
266allows you to "wrap" another action, just as it would have been called by
267dispatching from a URL, while the analogous
268[go](#c-go-action-captures-arguments) allows you to
269transfer control to another action as if it had been reached directly from a URL.
270
271## $c->go( $action \[, \\@arguments \] )
272
273## $c->go( $action \[, \\@captures, \\@arguments \] )
274
275## $c->go( $class, $method, \[, \\@arguments \] )
276
277## $c->go( $class, $method, \[, \\@captures, \\@arguments \] )
278
279The relationship between `go` and
280[visit](#c-visit-action-captures-arguments) is the same as
281the relationship between
282[forward](#c-forward-class-method-arguments) and
283[detach](#c-detach-action-arguments). Like `$c->visit`,
284`$c->go` will perform a full dispatch on the specified action or method,
285with localized `$c->action` and `$c->namespace`. Like `detach`,
286`go` escapes the processing of the current request chain on completion, and
6bd163d1 287does not return to its caller.
9e7f288e 288
289@arguments are arguments to the final destination of $action. @captures are
290arguments to the intermediate steps, if any, on the way to the final sub of
291$action.
292
293## $c->response
294
295## $c->res
296
297Returns the current [Catalyst::Response](https://metacpan.org/pod/Catalyst::Response) object, see there for details.
298
299## $c->stash
300
301Returns a hashref to the stash, which may be used to store data and pass
302it between components during a request. You can also set hash keys by
303passing arguments. The stash is automatically sent to the view. The
304stash is cleared at the end of a request; it cannot be used for
305persistent storage (for this you must use a session; see
306[Catalyst::Plugin::Session](https://metacpan.org/pod/Catalyst::Plugin::Session) for a complete system integrated with
307Catalyst).
308
309 $c->stash->{foo} = $bar;
310 $c->stash( { moose => 'majestic', qux => 0 } );
311 $c->stash( bar => 1, gorch => 2 ); # equivalent to passing a hashref
312
313 # stash is automatically passed to the view for use in a template
314 $c->forward( 'MyApp::View::TT' );
315
316The stash hash is currently stored in the PSGI `$env` and is managed by
317[Catalyst::Middleware::Stash](https://metacpan.org/pod/Catalyst::Middleware::Stash). Since it's part of the `$env` items in
318the stash can be accessed in sub applications mounted under your main
319[Catalyst](https://metacpan.org/pod/Catalyst) application. For example if you delegate the response of an
320action to another [Catalyst](https://metacpan.org/pod/Catalyst) application, that sub application will have
321access to all the stash keys of the main one, and if can of course add
322more keys of its own. However those new keys will not 'bubble' back up
323to the main application.
324
325For more information the best thing to do is to review the test case:
326t/middleware-stash.t in the distribution /t directory.
327
328## $c->error
329
330## $c->error($error, ...)
331
332## $c->error($arrayref)
333
334Returns an arrayref containing error messages. If Catalyst encounters an
335error while processing a request, it stores the error in $c->error. This
336method should only be used to store fatal error messages.
337
338 my @error = @{ $c->error };
339
340Add a new error.
341
342 $c->error('Something bad happened');
343
344Calling this will always return an arrayref (if there are no errors it
345will be an empty arrayref.
346
347## $c->state
348
349Contains the return value of the last executed action.
350Note that << $c->state >> operates in a scalar context which means that all
351values it returns are scalar.
352
6bd163d1 353Please note that if an action throws an exception, the value of state
354should no longer be considered the return if the last action. It is generally
355going to be 0, which indicates an error state. Examine $c->error for error
356details.
357
9e7f288e 358## $c->clear\_errors
359
360Clear errors. You probably don't want to clear the errors unless you are
361implementing a custom error screen.
362
363This is equivalent to running
364
365 $c->error(0);
366
367## $c->has\_errors
368
369Returns true if you have errors
370
371## $c->last\_error
372
373Returns the most recent error in the stack (the one most recently added...)
6bd163d1 374or nothing if there are no errors. This does not modify the contents of the
375error stack.
9e7f288e 376
377## shift\_errors
378
6bd163d1 379shifts the most recently added error off the error stack and returns it. Returns
380nothing if there are no more errors.
381
382## pop\_errors
383
384pops the most recently added error off the error stack and returns it. Returns
9e7f288e 385nothing if there are no more errors.
386
387## COMPONENT ACCESSORS
388
389## $c->controller($name)
390
391Gets a [Catalyst::Controller](https://metacpan.org/pod/Catalyst::Controller) instance by name.
392
393 $c->controller('Foo')->do_stuff;
394
395If the name is omitted, will return the controller for the dispatched
396action.
397
398If you want to search for controllers, pass in a regexp as the argument.
399
400 # find all controllers that start with Foo
401 my @foo_controllers = $c->controller(qr{^Foo});
402
403## $c->model($name)
404
405Gets a [Catalyst::Model](https://metacpan.org/pod/Catalyst::Model) instance by name.
406
407 $c->model('Foo')->do_stuff;
408
409Any extra arguments are directly passed to ACCEPT\_CONTEXT, if the model
410defines ACCEPT\_CONTEXT. If it does not, the args are discarded.
411
412If the name is omitted, it will look for
413 - a model object in $c->stash->{current\_model\_instance}, then
414 - a model name in $c->stash->{current\_model}, then
415 - a config setting 'default\_model', or
416 - check if there is only one model, and return it if that's the case.
417
418If you want to search for models, pass in a regexp as the argument.
419
420 # find all models that start with Foo
421 my @foo_models = $c->model(qr{^Foo});
422
423## $c->view($name)
424
425Gets a [Catalyst::View](https://metacpan.org/pod/Catalyst::View) instance by name.
426
427 $c->view('Foo')->do_stuff;
428
429Any extra arguments are directly passed to ACCEPT\_CONTEXT.
430
431If the name is omitted, it will look for
432 - a view object in $c->stash->{current\_view\_instance}, then
433 - a view name in $c->stash->{current\_view}, then
434 - a config setting 'default\_view', or
435 - check if there is only one view, and return it if that's the case.
436
437If you want to search for views, pass in a regexp as the argument.
438
439 # find all views that start with Foo
440 my @foo_views = $c->view(qr{^Foo});
441
442## $c->controllers
443
444Returns the available names which can be passed to $c->controller
445
446## $c->models
447
448Returns the available names which can be passed to $c->model
449
450## $c->views
451
452Returns the available names which can be passed to $c->view
453
454## $c->comp($name)
455
456## $c->component($name)
457
458Gets a component object by name. This method is not recommended,
459unless you want to get a specific component by full
460class. `$c->controller`, `$c->model`, and `$c->view`
461should be used instead.
462
463If `$name` is a regexp, a list of components matched against the full
464component name will be returned.
465
466If Catalyst can't find a component by name, it will fallback to regex
467matching by default. To disable this behaviour set
468disable\_component\_resolution\_regex\_fallback to a true value.
469
470 __PACKAGE__->config( disable_component_resolution_regex_fallback => 1 );
471
472## CLASS DATA AND HELPER CLASSES
473
474## $c->config
475
476Returns or takes a hashref containing the application's configuration.
477
478 __PACKAGE__->config( { db => 'dsn:SQLite:foo.db' } );
479
480You can also use a `YAML`, `XML` or [Config::General](https://metacpan.org/pod/Config::General) config file
481like `myapp.conf` in your applications home directory. See
482[Catalyst::Plugin::ConfigLoader](https://metacpan.org/pod/Catalyst::Plugin::ConfigLoader).
483
484### Cascading configuration
485
486The config method is present on all Catalyst components, and configuration
487will be merged when an application is started. Configuration loaded with
488[Catalyst::Plugin::ConfigLoader](https://metacpan.org/pod/Catalyst::Plugin::ConfigLoader) takes precedence over other configuration,
489followed by configuration in your top level `MyApp` class. These two
490configurations are merged, and then configuration data whose hash key matches a
491component name is merged with configuration for that component.
492
493The configuration for a component is then passed to the `new` method when a
494component is constructed.
495
496For example:
497
498 MyApp->config({ 'Model::Foo' => { bar => 'baz', overrides => 'me' } });
499 MyApp::Model::Foo->config({ quux => 'frob', overrides => 'this' });
500
501will mean that `MyApp::Model::Foo` receives the following data when
502constructed:
503
504 MyApp::Model::Foo->new({
505 bar => 'baz',
506 quux => 'frob',
507 overrides => 'me',
508 });
509
510It's common practice to use a Moose attribute
511on the receiving component to access the config value.
512
513 package MyApp::Model::Foo;
514
515 use Moose;
516
517 # this attr will receive 'baz' at construction time
518 has 'bar' => (
519 is => 'rw',
520 isa => 'Str',
521 );
522
523You can then get the value 'baz' by calling $c->model('Foo')->bar
524(or $self->bar inside code in the model).
525
526**NOTE:** you MUST NOT call `$self->config` or `__PACKAGE__->config`
527as a way of reading config within your code, as this **will not** give you the
528correctly merged config back. You **MUST** take the config values supplied to
529the constructor and use those instead.
530
531## $c->log
532
533Returns the logging object instance. Unless it is already set, Catalyst
534sets this up with a [Catalyst::Log](https://metacpan.org/pod/Catalyst::Log) object. To use your own log class,
535set the logger with the `__PACKAGE__->log` method prior to calling
536`__PACKAGE__->setup`.
537
538 __PACKAGE__->log( MyLogger->new );
539 __PACKAGE__->setup;
540
541And later:
542
543 $c->log->info( 'Now logging with my own logger!' );
544
545Your log class should implement the methods described in
546[Catalyst::Log](https://metacpan.org/pod/Catalyst::Log).
547
548## has\_encoding
549
550Returned True if there's a valid encoding
551
552## clear\_encoding
553
554Clears the encoding for the current context
555
556## encoding
557
558Sets or gets the application encoding. Setting encoding takes either an
559Encoding object or a string that we try to resolve via [Encode::find\_encoding](https://metacpan.org/pod/Encode::find_encoding).
560
561You would expect to get the encoding object back if you attempt to set it. If
562there is a failure you will get undef returned and an error message in the log.
563
564## $c->debug
565
566Returns 1 if debug mode is enabled, 0 otherwise.
567
568You can enable debug mode in several ways:
569
570- By calling myapp\_server.pl with the -d flag
571- With the environment variables MYAPP\_DEBUG, or CATALYST\_DEBUG
572- The -Debug option in your MyApp.pm
573- By declaring `sub debug { 1 }` in your MyApp.pm.
574
575The first three also set the log level to 'debug'.
576
577Calling `$c->debug(1)` has no effect.
578
579## $c->dispatcher
580
581Returns the dispatcher instance. See [Catalyst::Dispatcher](https://metacpan.org/pod/Catalyst::Dispatcher).
582
583## $c->engine
584
585Returns the engine instance. See [Catalyst::Engine](https://metacpan.org/pod/Catalyst::Engine).
586
587## UTILITY METHODS
588
589## $c->path\_to(@path)
590
591Merges `@path` with `$c->config->{home}` and returns a
592[Path::Class::Dir](https://metacpan.org/pod/Path::Class::Dir) object. Note you can usually use this object as
593a filename, but sometimes you will have to explicitly stringify it
594yourself by calling the `->stringify` method.
595
596For example:
597
598 $c->path_to( 'db', 'sqlite.db' );
599
600## MyApp->setup
601
602Initializes the dispatcher and engine, loads any plugins, and loads the
603model, view, and controller components. You may also specify an array
604of plugins to load here, if you choose to not load them in the `use
605Catalyst` line.
606
607 MyApp->setup;
608 MyApp->setup( qw/-Debug/ );
609
610**Note:** You **should not** wrap this method with method modifiers
611or bad things will happen - wrap the `setup_finalize` method instead.
612
613**Note:** You can create a custom setup stage that will execute when the
614application is starting. Use this to customize setup.
615
616 MyApp->setup(-Custom=value);
617
618 sub setup_custom {
619 my ($class, $value) = @_;
620 }
621
622Can be handy if you want to hook into the setup phase.
623
624## $app->setup\_finalize
625
626A hook to attach modifiers to. This method does not do anything except set the
627`setup_finished` accessor.
628
629Applying method modifiers to the `setup` method doesn't work, because of quirky things done for plugin setup.
630
631Example:
632
633 after setup_finalize => sub {
634 my $app = shift;
635
636 ## do stuff here..
637 };
638
6bd163d1 639## $c->uri\_for( $path?, @args?, \\%query\_values?, \\$fragment? )
9e7f288e 640
6bd163d1 641## $c->uri\_for( $action, \\@captures?, @args?, \\%query\_values?, \\$fragment? )
9e7f288e 642
6bd163d1 643## $c->uri\_for( $action, \[@captures, @args\], \\%query\_values?, \\$fragment? )
9e7f288e 644
645Constructs an absolute [URI](https://metacpan.org/pod/URI) object based on the application root, the
646provided path, and the additional arguments and query parameters provided.
647When used as a string, provides a textual URI. If you need more flexibility
648than this (i.e. the option to provide relative URIs etc.) see
649[Catalyst::Plugin::SmartURI](https://metacpan.org/pod/Catalyst::Plugin::SmartURI).
650
651If no arguments are provided, the URI for the current action is returned.
652To return the current action and also provide @args, use
653`$c->uri_for( $c->action, @args )`.
654
655If the first argument is a string, it is taken as a public URI path relative
656to `$c->namespace` (if it doesn't begin with a forward slash) or
657relative to the application root (if it does). It is then merged with
658`$c->request->base`; any `@args` are appended as additional path
659components; and any `%query_values` are appended as `?foo=bar` parameters.
660
6bd163d1 661**NOTE** If you are using this 'stringy' first argument, we skip encoding and
662allow you to declare something like:
663
664 $c->uri_for('/foo/bar#baz')
665
666Where 'baz' is a URI fragment. We consider this first argument string to be
667'expert' mode where you are expected to create a valid URL and we for the most
668part just pass it through without a lot of internal effort to escape and encode.
669
9e7f288e 670If the first argument is a [Catalyst::Action](https://metacpan.org/pod/Catalyst::Action) it represents an action which
671will have its path resolved using `$c->dispatcher->uri_for_action`. The
672optional `\@captures` argument (an arrayref) allows passing the captured
673variables that are needed to fill in the paths of Chained and Regex actions;
674once the path is resolved, `uri_for` continues as though a path was
675provided, appending any arguments or parameters and creating an absolute
676URI.
677
678The captures for the current request can be found in
679`$c->request->captures`, and actions can be resolved using
680`Catalyst::Controller->action_for($name)`. If you have a private action
681path, use `$c->uri_for_action` instead.
682
683 # Equivalent to $c->req->uri
684 $c->uri_for($c->action, $c->req->captures,
685 @{ $c->req->args }, $c->req->params);
686
687 # For the Foo action in the Bar controller
688 $c->uri_for($c->controller('Bar')->action_for('Foo'));
689
690 # Path to a static resource
691 $c->uri_for('/static/images/logo.png');
692
693In general the scheme of the generated URI object will follow the incoming request
694however if your targeted action or action chain has the Scheme attribute it will
695use that instead.
696
697Also, if the targeted Action or Action chain declares Args/CaptureArgs that have
698type constraints, we will require that your proposed URL verify on those declared
699constraints.
700
701## $c->uri\_for\_action( $path, \\@captures\_and\_args?, @args?, \\%query\_values? )
702
703## $c->uri\_for\_action( $action, \\@captures\_and\_args?, @args?, \\%query\_values? )
704
705- $path
706
707 A private path to the Catalyst action you want to create a URI for.
708
709 This is a shortcut for calling `$c->dispatcher->get_action_by_path($path)` and passing the resulting `$action` and the remaining arguments to `$c->uri_for`.
710
711 You can also pass in a Catalyst::Action object, in which case it is passed to
712 `$c->uri_for`.
713
714 Note that although the path looks like a URI that dispatches to the wanted action, it is not a URI, but an internal path to that action.
715
716 For example, if the action looks like:
717
718 package MyApp::Controller::Users;
719
720 sub lst : Path('the-list') {}
721
722 You can use:
723
724 $c->uri_for_action('/users/lst')
725
726 and it will create the URI /users/the-list.
727
728- \\@captures\_and\_args?
729
730 Optional array reference of Captures (i.e. `<CaptureArgs or $c-`req->captures>)
731 and arguments to the request. Usually used with [Catalyst::DispatchType::Chained](https://metacpan.org/pod/Catalyst::DispatchType::Chained)
732 to interpolate all the parameters in the URI.
733
734- @args?
735
736 Optional list of extra arguments - can be supplied in the
737 `\@captures_and_args?` array ref, or here - whichever is easier for your
738 code.
739
740 Your action can have zero, a fixed or a variable number of args (e.g.
741 `Args(1)` for a fixed number or `Args()` for a variable number)..
742
743- \\%query\_values?
744
745 Optional array reference of query parameters to append. E.g.
746
747 { foo => 'bar' }
748
749 will generate
750
751 /rest/of/your/uri?foo=bar
752
753## $c->welcome\_message
754
755Returns the Catalyst welcome HTML page.
756
757## run\_options
758
759Contains a hash of options passed from the application script, including
760the original ARGV the script received, the processed values from that
761ARGV and any extra arguments to the script which were not processed.
762
763This can be used to add custom options to your application's scripts
764and setup your application differently depending on the values of these
765options.
766
767# INTERNAL METHODS
768
769These methods are not meant to be used by end users.
770
771## $c->components
772
773Returns a hash of components.
774
775## $c->context\_class
776
777Returns or sets the context class.
778
779## $c->counter
780
781Returns a hashref containing coderefs and execution counts (needed for
782deep recursion detection).
783
784## $c->depth
785
786Returns the number of actions on the current internal execution stack.
787
788## $c->dispatch
789
790Dispatches a request to actions.
791
792## $c->dispatcher\_class
793
794Returns or sets the dispatcher class.
795
796## $c->dump\_these
797
798Returns a list of 2-element array references (name, structure) pairs
799that will be dumped on the error page in debug mode.
800
801## $c->engine\_class
802
803Returns or sets the engine class.
804
805## $c->execute( $class, $coderef )
806
807Execute a coderef in given class and catch exceptions. Errors are available
808via $c->error.
809
810## $c->finalize
811
812Finalizes the request.
813
814## $c->finalize\_body
815
816Finalizes body.
817
818## $c->finalize\_cookies
819
820Finalizes cookies.
821
822## $c->finalize\_error
823
824Finalizes error. If there is only one error in ["error"](#error) and it is an object that
825does `as_psgi` or `code` we rethrow the error and presume it caught by middleware
826up the ladder. Otherwise we return the debugging error page (in debug mode) or we
827return the default error page (production mode).
828
829## $c->finalize\_headers
830
831Finalizes headers.
832
833## $c->finalize\_encoding
834
835Make sure your body is encoded properly IF you set an encoding. By
836default the encoding is UTF-8 but you can disable it by explicitly setting the
837encoding configuration value to undef.
838
839We can only encode when the body is a scalar. Methods for encoding via the
840streaming interfaces (such as `write` and `write_fh` on [Catalyst::Response](https://metacpan.org/pod/Catalyst::Response)
841are available).
842
843See ["ENCODING"](#encoding).
844
845## $c->finalize\_output
846
847An alias for finalize\_body.
848
849## $c->finalize\_read
850
851Finalizes the input after reading is complete.
852
853## $c->finalize\_uploads
854
855Finalizes uploads. Cleans up any temporary files.
856
857## $c->get\_action( $action, $namespace )
858
859Gets an action in a given namespace.
860
861## $c->get\_actions( $action, $namespace )
862
863Gets all actions of a given name in a namespace and all parent
864namespaces.
865
866## $app->handle\_request( @arguments )
867
868Called to handle each HTTP request.
869
870## $class->prepare( @arguments )
871
872Creates a Catalyst context from an engine-specific request (Apache, CGI,
873etc.).
874
875## $c->prepare\_action
876
877Prepares action. See [Catalyst::Dispatcher](https://metacpan.org/pod/Catalyst::Dispatcher).
878
879## $c->prepare\_body
880
881Prepares message body.
882
883## $c->prepare\_body\_chunk( $chunk )
884
885Prepares a chunk of data before sending it to [HTTP::Body](https://metacpan.org/pod/HTTP::Body).
886
887See [Catalyst::Engine](https://metacpan.org/pod/Catalyst::Engine).
888
889## $c->prepare\_body\_parameters
890
891Prepares body parameters.
892
893## $c->prepare\_connection
894
895Prepares connection.
896
897## $c->prepare\_cookies
898
899Prepares cookies by ensuring that the attribute on the request
900object has been built.
901
902## $c->prepare\_headers
903
904Prepares request headers by ensuring that the attribute on the request
905object has been built.
906
907## $c->prepare\_parameters
908
909Prepares parameters.
910
911## $c->prepare\_path
912
913Prepares path and base.
914
915## $c->prepare\_query\_parameters
916
917Prepares query parameters.
918
919## $c->log\_request
920
921Writes information about the request to the debug logs. This includes:
922
923- Request method, path, and remote IP address
924- Query keywords (see ["query\_keywords" in Catalyst::Request](https://metacpan.org/pod/Catalyst::Request#query_keywords))
925- Request parameters
926- File uploads
927
928## $c->log\_response
929
930Writes information about the response to the debug logs by calling
931`$c->log_response_status_line` and `$c->log_response_headers`.
932
933## $c->log\_response\_status\_line($response)
934
935Writes one line of information about the response to the debug logs. This includes:
936
937- Response status code
938- Content-Type header (if present)
939- Content-Length header (if present)
940
941## $c->log\_response\_headers($headers);
942
943Hook method which can be wrapped by plugins to log the response headers.
944No-op in the default implementation.
945
946## $c->log\_request\_parameters( query => {}, body => {} )
947
948Logs request parameters to debug logs
949
950## $c->log\_request\_uploads
951
952Logs file uploads included in the request to the debug logs.
953The parameter name, filename, file type, and file size are all included in
954the debug logs.
955
956## $c->log\_request\_headers($headers);
957
958Hook method which can be wrapped by plugins to log the request headers.
959No-op in the default implementation.
960
961## $c->log\_headers($type => $headers)
962
963Logs [HTTP::Headers](https://metacpan.org/pod/HTTP::Headers) (either request or response) to the debug logs.
964
965## $c->prepare\_read
966
967Prepares the input for reading.
968
969## $c->prepare\_request
970
971Prepares the engine request.
972
973## $c->prepare\_uploads
974
975Prepares uploads.
976
977## $c->prepare\_write
978
979Prepares the output for writing.
980
981## $c->request\_class
982
983Returns or sets the request class. Defaults to [Catalyst::Request](https://metacpan.org/pod/Catalyst::Request).
984
985## $app->request\_class\_traits
986
6bd163d1 987An arrayref of [Moose::Role](https://metacpan.org/pod/Moose::Role)s which are applied to the request class. You can
988name the full namespace of the role, or a namespace suffix, which will then
989be tried against the following standard namespace prefixes.
990
991 $MyApp::TraitFor::Request::$trait_suffix
992 Catalyst::TraitFor::Request::$trait_suffix
993
994So for example if you set:
995
996 MyApp->request_class_traits(['Foo']);
997
998We try each possible role in turn (and throw an error if none load)
999
1000 Foo
1001 MyApp::TraitFor::Request::Foo
1002 Catalyst::TraitFor::Request::Foo
1003
1004The namespace part 'TraitFor::Request' was chosen to assist in backwards
1005compatibility with [CatalystX::RoleApplicator](https://metacpan.org/pod/CatalystX::RoleApplicator) which previously provided
1006these features in a stand alone package.
9e7f288e 1007
1008## $app->composed\_request\_class
1009
1010This is the request class which has been composed with any request\_class\_traits.
1011
1012## $c->response\_class
1013
1014Returns or sets the response class. Defaults to [Catalyst::Response](https://metacpan.org/pod/Catalyst::Response).
1015
1016## $app->response\_class\_traits
1017
6bd163d1 1018An arrayref of [Moose::Role](https://metacpan.org/pod/Moose::Role)s which are applied to the response class. You can
1019name the full namespace of the role, or a namespace suffix, which will then
1020be tried against the following standard namespace prefixes.
1021
1022 $MyApp::TraitFor::Response::$trait_suffix
1023 Catalyst::TraitFor::Response::$trait_suffix
1024
1025So for example if you set:
1026
1027 MyApp->response_class_traits(['Foo']);
1028
1029We try each possible role in turn (and throw an error if none load)
1030
1031 Foo
1032 MyApp::TraitFor::Response::Foo
1033 Catalyst::TraitFor::Responset::Foo
1034
1035The namespace part 'TraitFor::Response' was chosen to assist in backwards
1036compatibility with [CatalystX::RoleApplicator](https://metacpan.org/pod/CatalystX::RoleApplicator) which previously provided
1037these features in a stand alone package.
9e7f288e 1038
1039## $app->composed\_response\_class
1040
1041This is the request class which has been composed with any response\_class\_traits.
1042
1043## $c->read( \[$maxlength\] )
1044
1045Reads a chunk of data from the request body. This method is designed to
1046be used in a while loop, reading `$maxlength` bytes on every call.
1047`$maxlength` defaults to the size of the request if not specified.
1048
1049You have to set `MyApp->config(parse_on_demand => 1)` to use this
1050directly.
1051
1052Warning: If you use read(), Catalyst will not process the body,
1053so you will not be able to access POST parameters or file uploads via
1054$c->request. You must handle all body parsing yourself.
1055
1056## $c->run
1057
1058Starts the engine.
1059
1060## $c->set\_action( $action, $code, $namespace, $attrs )
1061
1062Sets an action in a given namespace.
1063
1064## $c->setup\_actions($component)
1065
1066Sets up actions for a component.
1067
1068## $c->setup\_components
1069
1070This method is called internally to set up the application's components.
1071
1072It finds modules by calling the [locate\_components](https://metacpan.org/pod/locate_components) method, expands them to
1073package names with the [expand\_component\_module](https://metacpan.org/pod/expand_component_module) method, and then installs
1074each component into the application.
1075
1076The `setup_components` config option is passed to both of the above methods.
1077
1078Installation of each component is performed by the [setup\_component](https://metacpan.org/pod/setup_component) method,
1079below.
1080
1081## $app->setup\_injected\_components
1082
1083Called by setup\_compoents to setup components that are injected.
1084
1085## $app->setup\_injected\_component( $injected\_component\_name, $config )
1086
1087Setup a given injected component.
1088
1089## $app->inject\_component($MyApp\_Component\_name => \\%args);
1090
1091Add a component that is injected at setup:
1092
1093 MyApp->inject_component( 'Model::Foo' => { from_component => 'Common::Foo' } );
1094
1095Must be called before ->setup. Expects a component name for your
1096current application and \\%args where
1097
1098- from\_component
1099
1100 The target component being injected into your application
1101
1102- roles
1103
1104 An arrayref of [Moose::Role](https://metacpan.org/pod/Moose::Role)s that are applied to your component.
1105
1106Example
1107
1108 MyApp->inject_component(
1109 'Model::Foo' => {
1110 from_component => 'Common::Model::Foo',
1111 roles => ['Role1', 'Role2'],
1112 });
1113
1114## $app->inject\_components
1115
1116Inject a list of components:
1117
1118 MyApp->inject_components(
1119 'Model::FooOne' => {
1120 from_component => 'Common::Model::Foo',
1121 roles => ['Role1', 'Role2'],
1122 },
1123 'Model::FooTwo' => {
1124 from_component => 'Common::Model::Foo',
1125 roles => ['Role1', 'Role2'],
1126 });
1127
1128## $c->locate\_components( $setup\_component\_config )
1129
1130This method is meant to provide a list of component modules that should be
1131setup for the application. By default, it will use [Module::Pluggable](https://metacpan.org/pod/Module::Pluggable).
1132
1133Specify a `setup_components` config option to pass additional options directly
1134to [Module::Pluggable](https://metacpan.org/pod/Module::Pluggable). To add additional search paths, specify a key named
1135`search_extra` as an array reference. Items in the array beginning with `::`
1136will have the application class name prepended to them.
1137
1138## $c->expand\_component\_module( $component, $setup\_component\_config )
1139
1140Components found by `locate_components` will be passed to this method, which
1141is expected to return a list of component (package) names to be set up.
1142
1143## $app->delayed\_setup\_component
1144
1145Returns a coderef that points to a setup\_component instance. Used
1146internally for when you want to delay setup until the first time
1147the component is called.
1148
1149## $c->setup\_component
1150
1151## $app->config\_for( $component\_name )
1152
1153Return the application level configuration (which is not yet merged with any
1154local component configuration, via $component\_class->config) for the named
1155component or component object. Example:
1156
1157 MyApp->config(
1158 'Model::Foo' => { a => 1, b => 2},
1159 );
1160
1161 my $config = MyApp->config_for('MyApp::Model::Foo');
1162
1163In this case $config is the hashref ` {a=`1, b=>2} >.
1164
1165This is also handy for looking up configuration for a plugin, to make sure you follow
1166existing [Catalyst](https://metacpan.org/pod/Catalyst) standards for where a plugin should put its configuration.
1167
1168## $c->setup\_dispatcher
1169
1170Sets up dispatcher.
1171
1172## $c->setup\_engine
1173
1174Sets up engine.
1175
1176## $c->apply\_default\_middlewares
1177
1178Adds the following [Plack](https://metacpan.org/pod/Plack) middlewares to your application, since they are
1179useful and commonly needed:
1180
1181[Plack::Middleware::LighttpdScriptNameFix](https://metacpan.org/pod/Plack::Middleware::LighttpdScriptNameFix) (if you are using Lighttpd),
1182[Plack::Middleware::IIS6ScriptNameFix](https://metacpan.org/pod/Plack::Middleware::IIS6ScriptNameFix) (always applied since this middleware
1183is smart enough to conditionally apply itself).
1184
1185We will also automatically add [Plack::Middleware::ReverseProxy](https://metacpan.org/pod/Plack::Middleware::ReverseProxy) if we notice
1186that your HTTP $env variable `REMOTE_ADDR` is '127.0.0.1'. This is usually
1187an indication that your server is running behind a proxy frontend. However in
11882014 this is often not the case. We preserve this code for backwards compatibility
1189however I **highly** recommend that if you are running the server behind a front
1190end proxy that you clearly indicate so with the `using_frontend_proxy` configuration
1191setting to true for your environment configurations that run behind a proxy. This
1192way if you change your front end proxy address someday your code would inexplicably
1193stop working as expected.
1194
1195Additionally if we detect we are using Nginx, we add a bit of custom middleware
1196to solve some problems with the way that server handles $ENV{PATH\_INFO} and
1197$ENV{SCRIPT\_NAME}.
1198
1199Please **NOTE** that if you do use `using_frontend_proxy` the middleware is now
1200adding via `registered_middleware` rather than this method.
1201
1202If you are using Lighttpd or IIS6 you may wish to apply these middlewares. In
1203general this is no longer a common case but we have this here for backward
1204compatibility.
1205
1206## App->psgi\_app
1207
1208## App->to\_app
1209
1210Returns a PSGI application code reference for the catalyst application
1211`$c`. This is the bare application created without the `apply_default_middlewares`
1212method called. We do however apply `registered_middleware` since those are
1213integral to how [Catalyst](https://metacpan.org/pod/Catalyst) functions. Also, unlike starting your application
1214with a generated server script (via [Catalyst::Devel](https://metacpan.org/pod/Catalyst::Devel) and `catalyst.pl`) we do
1215not attempt to return a valid [PSGI](https://metacpan.org/pod/PSGI) application using any existing `${myapp}.psgi`
1216scripts in your $HOME directory.
1217
1218**NOTE** `apply_default_middlewares` was originally created when the first PSGI
1219port was done for v5.90000. These are middlewares that are added to achieve
1220backward compatibility with older applications. If you start your application
1221using one of the supplied server scripts (generated with [Catalyst::Devel](https://metacpan.org/pod/Catalyst::Devel) and
1222the project skeleton script `catalyst.pl`) we apply `apply_default_middlewares`
1223automatically. This was done so that pre and post PSGI port applications would
1224work the same way.
1225
1226This is what you want to be using to retrieve the PSGI application code
1227reference of your Catalyst application for use in a custom `.psgi` or in your
1228own created server modules.
1229
1230## $c->setup\_home
1231
1232Sets up the home directory.
1233
1234## $c->setup\_encoding
1235
1236Sets up the input/output encoding. See [ENCODING](https://metacpan.org/pod/ENCODING)
1237
1238## handle\_unicode\_encoding\_exception
1239
6bd163d1 1240Hook to let you customize how encoding errors are handled. By default
1241we just throw an exception and the default error page will pick it up.
1242Receives a hashref of debug information. Example of call (from the
1243Catalyst internals):
9e7f288e 1244
6bd163d1 1245 my $decoded_after_fail = $c->handle_unicode_encoding_exception({
1246 param_value => $value,
1247 error_msg => $_,
1248 encoding_step => 'params',
1249 });
1250
1251The calling code expects to receive a decoded string or an exception.
1252
1253You can override this for custom handling of unicode errors. By
1254default we just die. If you want a custom response here, one approach
1255is to throw an HTTP style exception, instead of returning a decoded
1256string or throwing a generic exception.
1257
1258 sub handle_unicode_encoding_exception {
1259 my ($c, $params) = @_;
1260 HTTP::Exception::BAD_REQUEST->throw(status_message=>$params->{error_msg});
1261 }
1262
1263Alternatively you can 'catch' the error, stash it and write handling code later
1264in your application:
1265
1266 sub handle_unicode_encoding_exception {
1267 my ($c, $params) = @_;
1268 $c->stash(BAD_UNICODE_DATA=>$params);
1269 # return a dummy string.
1270 return 1;
1271 }
1272
1273<B>NOTE:&lt;/b> Please keep in mind that once an error like this occurs,
1274the request setup is still ongoing, which means the state of `$c` and
1275related context parts like the request and response may not be setup
1276up correctly (since we haven't finished the setup yet). If you throw
1277an exception the setup is aborted.
9e7f288e 1278
1279## $c->setup\_log
1280
1281Sets up log by instantiating a [Catalyst::Log](https://metacpan.org/pod/Catalyst::Log) object and
1282passing it to `log()`. Pass in a comma-delimited list of levels to set the
1283log to.
1284
1285This method also installs a `debug` method that returns a true value into the
1286catalyst subclass if the "debug" level is passed in the comma-delimited list,
1287or if the `$CATALYST_DEBUG` environment variable is set to a true value.
1288
1289Note that if the log has already been setup, by either a previous call to
1290`setup_log` or by a call such as `__PACKAGE__->log( MyLogger->new )`,
1291that this method won't actually set up the log object.
1292
1293## $c->setup\_plugins
1294
1295Sets up plugins.
1296
1297## $c->setup\_stats
1298
1299Sets up timing statistics class.
1300
1301## $c->registered\_plugins
1302
1303Returns a sorted list of the plugins which have either been stated in the
1304import list.
1305
1306If passed a given plugin name, it will report a boolean value indicating
1307whether or not that plugin is loaded. A fully qualified name is required if
1308the plugin name does not begin with `Catalyst::Plugin::`.
1309
1310 if ($c->registered_plugins('Some::Plugin')) {
1311 ...
1312 }
1313
1314## default\_middleware
1315
1316Returns a list of instantiated PSGI middleware objects which is the default
1317middleware that is active for this application (taking any configuration
1318options into account, excluding your custom added middleware via the `psgi_middleware`
1319configuration option). You can override this method if you wish to change
1320the default middleware (although do so at risk since some middleware is vital
1321to application function.)
1322
1323The current default middleware list is:
1324
1325 Catalyst::Middleware::Stash
1326 Plack::Middleware::HTTPExceptions
1327 Plack::Middleware::RemoveRedundantBody
1328 Plack::Middleware::FixMissingBodyInRedirect
1329 Plack::Middleware::ContentLength
1330 Plack::Middleware::MethodOverride
1331 Plack::Middleware::Head
1332
1333If the configuration setting `using_frontend_proxy` is true we add:
1334
1335 Plack::Middleware::ReverseProxy
1336
1337If the configuration setting `using_frontend_proxy_path` is true we add:
1338
1339 Plack::Middleware::ReverseProxyPath
1340
1341But **NOTE** that [Plack::Middleware::ReverseProxyPath](https://metacpan.org/pod/Plack::Middleware::ReverseProxyPath) is not a dependency of the
1342[Catalyst](https://metacpan.org/pod/Catalyst) distribution so if you want to use this option you should add it to
1343your project distribution file.
1344
1345These middlewares will be added at ["setup\_middleware"](#setup_middleware) during the
1346["setup"](#setup) phase of application startup.
1347
1348## registered\_middlewares
1349
1350Read only accessor that returns an array of all the middleware in the order
1351that they were added (which is the REVERSE of the order they will be applied).
1352
1353The values returned will be either instances of [Plack::Middleware](https://metacpan.org/pod/Plack::Middleware) or of a
1354compatible interface, or a coderef, which is assumed to be inlined middleware
1355
1356## setup\_middleware (?@middleware)
1357
1358Read configuration information stored in configuration key `psgi_middleware` or
1359from passed @args.
1360
1361See under ["CONFIGURATION"](#configuration) information regarding `psgi_middleware` and how
1362to use it to enable [Plack::Middleware](https://metacpan.org/pod/Plack::Middleware)
1363
1364This method is automatically called during 'setup' of your application, so
1365you really don't need to invoke it. However you may do so if you find the idea
1366of loading middleware via configuration weird :). For example:
1367
1368 package MyApp;
1369
1370 use Catalyst;
1371
1372 __PACKAGE__->setup_middleware('Head');
1373 __PACKAGE__->setup;
1374
1375When we read middleware definitions from configuration, we reverse the list
1376which sounds odd but is likely how you expect it to work if you have prior
1377experience with [Plack::Builder](https://metacpan.org/pod/Plack::Builder) or if you previously used the plugin
1378[Catalyst::Plugin::EnableMiddleware](https://metacpan.org/pod/Catalyst::Plugin::EnableMiddleware) (which is now considered deprecated)
1379
1380So basically your middleware handles an incoming request from the first
1381registered middleware, down and handles the response from the last middleware
1382up.
1383
1384## registered\_data\_handlers
1385
1386A read only copy of registered Data Handlers returned as a Hash, where each key
1387is a content type and each value is a subref that attempts to decode that content
1388type.
1389
1390## setup\_data\_handlers (?@data\_handler)
1391
1392Read configuration information stored in configuration key `data_handlers` or
1393from passed @args.
1394
1395See under ["CONFIGURATION"](#configuration) information regarding `data_handlers`.
1396
1397This method is automatically called during 'setup' of your application, so
1398you really don't need to invoke it.
1399
1400## default\_data\_handlers
1401
1402Default Data Handlers that come bundled with [Catalyst](https://metacpan.org/pod/Catalyst). Currently there are
1403only two default data handlers, for 'application/json' and an alternative to
1404'application/x-www-form-urlencoded' which supposed nested form parameters via
1405[CGI::Struct](https://metacpan.org/pod/CGI::Struct) or via [CGI::Struct::XS](https://metacpan.org/pod/CGI::Struct::XS) IF you've installed it.
1406
1407The 'application/json' data handler is used to parse incoming JSON into a Perl
1408data structure. It used either [JSON::MaybeXS](https://metacpan.org/pod/JSON::MaybeXS) or [JSON](https://metacpan.org/pod/JSON), depending on which
1409is installed. This allows you to fail back to [JSON:PP](JSON:PP), which is a Pure Perl
1410JSON decoder, and has the smallest dependency impact.
1411
1412Because we don't wish to add more dependencies to [Catalyst](https://metacpan.org/pod/Catalyst), if you wish to
1413use this new feature we recommend installing [JSON](https://metacpan.org/pod/JSON) or [JSON::MaybeXS](https://metacpan.org/pod/JSON::MaybeXS) in
1414order to get the best performance. You should add either to your dependency
1415list (Makefile.PL, dist.ini, cpanfile, etc.)
1416
1417## $c->stack
1418
1419Returns an arrayref of the internal execution stack (actions that are
1420currently executing).
1421
1422## $c->stats
1423
1424Returns the current timing statistics object. By default Catalyst uses
1425[Catalyst::Stats](https://metacpan.org/pod/Catalyst::Stats), but can be set otherwise with
1426[stats\_class](#c-stats_class).
1427
1428Even if [-Stats](#stats) is not enabled, the stats object is still
1429available. By enabling it with ` $c-`stats->enabled(1) >, it can be used to
1430profile explicitly, although MyApp.pm still won't profile nor output anything
1431by itself.
1432
1433## $c->stats\_class
1434
1435Returns or sets the stats (timing statistics) class. [Catalyst::Stats](https://metacpan.org/pod/Catalyst::Stats) is used by default.
1436
1437## $app->stats\_class\_traits
1438
1439A arrayref of [Moose::Role](https://metacpan.org/pod/Moose::Role)s that are applied to the stats\_class before creating it.
1440
1441## $app->composed\_stats\_class
1442
6bd163d1 1443this is the stats\_class composed with any 'stats\_class\_traits'. You can
1444name the full namespace of the role, or a namespace suffix, which will then
1445be tried against the following standard namespace prefixes.
1446
1447 $MyApp::TraitFor::Stats::$trait_suffix
1448 Catalyst::TraitFor::Stats::$trait_suffix
1449
1450So for example if you set:
1451
1452 MyApp->stats_class_traits(['Foo']);
1453
1454We try each possible role in turn (and throw an error if none load)
1455
1456 Foo
1457 MyApp::TraitFor::Stats::Foo
1458 Catalyst::TraitFor::Stats::Foo
1459
1460The namespace part 'TraitFor::Stats' was chosen to assist in backwards
1461compatibility with [CatalystX::RoleApplicator](https://metacpan.org/pod/CatalystX::RoleApplicator) which previously provided
1462these features in a stand alone package.
9e7f288e 1463
1464## $c->use\_stats
1465
1466Returns 1 when [stats collection](#stats) is enabled.
1467
1468Note that this is a static method, not an accessor and should be overridden
1469by declaring `sub use_stats { 1 }` in your MyApp.pm, not by calling `$c->use_stats(1)`.
1470
1471## $c->write( $data )
1472
1473Writes $data to the output stream. When using this method directly, you
1474will need to manually set the `Content-Length` header to the length of
1475your output data, if known.
1476
1477## version
1478
1479Returns the Catalyst version number. Mostly useful for "powered by"
1480messages in template systems.
1481
1482# CONFIGURATION
1483
1484There are a number of 'base' config variables which can be set:
1485
1486- `always_catch_http_exceptions` - As of version 5.90060 Catalyst
1487rethrows errors conforming to the interface described by
1488[Plack::Middleware::HTTPExceptions](https://metacpan.org/pod/Plack::Middleware::HTTPExceptions) and lets the middleware deal with it.
1489Set true to get the deprecated behaviour and have Catalyst catch HTTP exceptions.
1490- `default_model` - The default model picked if you say `$c->model`. See ["$c->model($name)"](#c-model-name).
1491- `default_view` - The default view to be rendered or returned when `$c->view` is called. See ["$c->view($name)"](#c-view-name).
1492- `disable_component_resolution_regex_fallback` - Turns
1493off the deprecated component resolution functionality so
1494that if any of the component methods (e.g. `$c->controller('Foo')`)
1495are called then regex search will not be attempted on string values and
1496instead `undef` will be returned.
1497- `home` - The application home directory. In an uninstalled application,
1498this is the top level application directory. In an installed application,
1499this will be the directory containing `MyApp.pm`.
1500- `ignore_frontend_proxy` - See ["PROXY SUPPORT"](#proxy-support)
1501- `name` - The name of the application in debug messages and the debug and
1502welcome screens
1503- `parse_on_demand` - The request body (for example file uploads) will not be parsed
1504until it is accessed. This allows you to (for example) check authentication (and reject
1505the upload) before actually receiving all the data. See ["ON-DEMAND PARSER"](#on-demand-parser)
1506- `root` - The root directory for templates. Usually this is just a
1507subdirectory of the home directory, but you can set it to change the
1508templates to a different directory.
1509- `search_extra` - Array reference passed to Module::Pluggable to for additional
1510namespaces from which components will be loaded (and constructed and stored in
1511`$c->components`).
1512- `show_internal_actions` - If true, causes internal actions such as `_DISPATCH`
1513to be shown in hit debug tables in the test server.
1514- `use_request_uri_for_path` - Controls if the `REQUEST_URI` or `PATH_INFO` environment
1515variable should be used for determining the request path.
1516
1517 Most web server environments pass the requested path to the application using environment variables,
1518 from which Catalyst has to reconstruct the request base (i.e. the top level path to / in the application,
1519 exposed as `$c->request->base`) and the request path below that base.
1520
1521 There are two methods of doing this, both of which have advantages and disadvantages. Which method is used
1522 is determined by the `$c->config(use_request_uri_for_path)` setting (which can either be true or false).
1523
1524 - use\_request\_uri\_for\_path => 0
1525
1526 This is the default (and the) traditional method that Catalyst has used for determining the path information.
1527 The path is generated from a combination of the `PATH_INFO` and `SCRIPT_NAME` environment variables.
1528 The allows the application to behave correctly when `mod_rewrite` is being used to redirect requests
1529 into the application, as these variables are adjusted by mod\_rewrite to take account for the redirect.
1530
1531 However this method has the major disadvantage that it is impossible to correctly decode some elements
1532 of the path, as RFC 3875 says: "`Unlike a URI path, the PATH_INFO is not URL-encoded, and cannot
1533 contain path-segment parameters.`" This means PATH\_INFO is **always** decoded, and therefore Catalyst
1534 can't distinguish / vs %2F in paths (in addition to other encoded values).
1535
1536 - use\_request\_uri\_for\_path => 1
1537
1538 This method uses the `REQUEST_URI` and `SCRIPT_NAME` environment variables. As `REQUEST_URI` is never
1539 decoded, this means that applications using this mode can correctly handle URIs including the %2F character
1540 (i.e. with `AllowEncodedSlashes` set to `On` in Apache).
1541
6bd163d1 1542 Given that this method of path resolution is provably more correct, it is recommended that you use
9e7f288e 1543 this unless you have a specific need to deploy your application in a non-standard environment, and you are
1544 aware of the implications of not being able to handle encoded URI paths correctly.
1545
1546 However it also means that in a number of cases when the app isn't installed directly at a path, but instead
1547 is having paths rewritten into it (e.g. as a .cgi/fcgi in a public\_html directory, with mod\_rewrite in a
1548 .htaccess file, or when SSI is used to rewrite pages into the app, or when sub-paths of the app are exposed
1549 at other URIs than that which the app is 'normally' based at with `mod_rewrite`), the resolution of
1550 `$c->request->base` will be incorrect.
1551
1552- `using_frontend_proxy` - See ["PROXY SUPPORT"](#proxy-support).
1553- `using_frontend_proxy_path` - Enabled [Plack::Middleware::ReverseProxyPath](https://metacpan.org/pod/Plack::Middleware::ReverseProxyPath) on your application (if
1554installed, otherwise log an error). This is useful if your application is not running on the
1555'root' (or /) of your host server. **NOTE** if you use this feature you should add the required
6bd163d1 1556middleware to your project dependency list since its not automatically a dependency of [Catalyst](https://metacpan.org/pod/Catalyst).
9e7f288e 1557This has been done since not all people need this feature and we wish to restrict the growth of
1558[Catalyst](https://metacpan.org/pod/Catalyst) dependencies.
1559- `encoding` - See ["ENCODING"](#encoding)
1560
1561 This now defaults to 'UTF-8'. You my turn it off by setting this configuration
1562 value to undef.
1563
1564- `abort_chain_on_error_fix`
1565
6bd163d1 1566 Defaults to true.
9e7f288e 1567
6bd163d1 1568 When there is an error in an action chain, the default behavior is to
1569 abort the processing of the remaining actions to avoid running them
1570 when the application is in an unexpected state.
9e7f288e 1571
6bd163d1 1572 Before version 5.90070, the default used to be false. To keep the old
1e300b1c 1573 behaviour, you can explicitly set the value to false. E.g.
9e7f288e 1574
6bd163d1 1575 __PACKAGE__->config(abort_chain_on_error_fix => 0);
1576
1577 If this setting is set to false, then the remaining actions are
1578 performed and the error is caught at the end of the chain.
9e7f288e 1579
1580- `use_hash_multivalue_in_request`
1581
1582 In [Catalyst::Request](https://metacpan.org/pod/Catalyst::Request) the methods `query_parameters`, `body_parametes`
1583 and `parameters` return a hashref where values might be scalar or an arrayref
1584 depending on the incoming data. In many cases this can be undesirable as it
1585 leads one to writing defensive code like the following:
1586
1587 my ($val) = ref($c->req->parameters->{a}) ?
1588 @{$c->req->parameters->{a}} :
1589 $c->req->parameters->{a};
1590
1591 Setting this configuration item to true will make [Catalyst](https://metacpan.org/pod/Catalyst) populate the
1592 attributes underlying these methods with an instance of [Hash::MultiValue](https://metacpan.org/pod/Hash::MultiValue)
1593 which is used by [Plack::Request](https://metacpan.org/pod/Plack::Request) and others to solve this very issue. You
1594 may prefer this behavior to the default, if so enable this option (be warned
1595 if you enable it in a legacy application we are not sure if it is completely
1596 backwardly compatible).
1597
1598- `skip_complex_post_part_handling`
1599
79fb8f95 1600 When creating body parameters from a POST, if we run into a multipart POST
9e7f288e 1601 that does not contain uploads, but instead contains inlined complex data
1602 (very uncommon) we cannot reliably convert that into field => value pairs. So
1603 instead we create an instance of [Catalyst::Request::PartData](https://metacpan.org/pod/Catalyst::Request::PartData). If this causes
1604 issue for you, you can disable this by setting `skip_complex_post_part_handling`
1605 to true (default is false).
1606
1607- `skip_body_param_unicode_decoding`
1608
1609 Generally we decode incoming POST params based on your declared encoding (the
1610 default for this is to decode UTF-8). If this is causing you trouble and you
1611 do not wish to turn all encoding support off (with the `encoding` configuration
1612 parameter) you may disable this step atomically by setting this configuration
1613 parameter to true.
1614
1615- `do_not_decode_query`
1616
1617 If true, then do not try to character decode any wide characters in your
d1467830 1618 request URL query or keywords. Most readings of the relevant specifications
9e7f288e 1619 suggest these should be UTF-\* encoded, which is the default that [Catalyst](https://metacpan.org/pod/Catalyst)
79fb8f95 1620 will use, however if you are creating a lot of URLs manually or have external
9e7f288e 1621 evil clients, this might cause you trouble. If you find the changes introduced
1622 in Catalyst version 5.90080+ break some of your query code, you may disable
1623 the UTF-8 decoding globally using this configuration.
1624
6bd163d1 1625 This setting takes precedence over `default_query_encoding`
1626
1627- `do_not_check_query_encoding`
1628
1629 Catalyst versions 5.90080 - 5.90106 would decode query parts of an incoming
1630 request but would not raise an exception when the decoding failed due to
1631 incorrect unicode. It now does, but if this change is giving you trouble
1632 you may disable it by setting this configuration to true.
9e7f288e 1633
1634- `default_query_encoding`
1635
1636 By default we decode query and keywords in your request URL using UTF-8, which
79fb8f95 1637 is our reading of the relevant specifications. This setting allows one to
9e7f288e 1638 specify a fixed value for how to decode your query. You might need this if
1639 you are doing a lot of custom encoding of your URLs and not using UTF-8.
1640
9e7f288e 1641- `use_chained_args_0_special_case`
1642
1643 In older versions of Catalyst, when more than one action matched the same path
1644 AND all those matching actions declared Args(0), we'd break the tie by choosing
1645 the first action defined. We now normalized how Args(0) works so that it
1646 follows the same rule as Args(N), which is to say when we need to break a tie
1647 we choose the LAST action defined. If this breaks your code and you don't
1648 have time to update to follow the new normalized approach, you may set this
1649 value to true and it will globally revert to the original chaining behavior.
1650
1651- `psgi_middleware` - See ["PSGI MIDDLEWARE"](#psgi-middleware).
1652- `data_handlers` - See ["DATA HANDLERS"](#data-handlers).
1653- `stats_class_traits`
1654
79fb8f95 1655 An arrayref of [Moose::Role](https://metacpan.org/pod/Moose::Role)s that get composed into your stats class.
9e7f288e 1656
1657- `request_class_traits`
1658
79fb8f95 1659 An arrayref of [Moose::Role](https://metacpan.org/pod/Moose::Role)s that get composed into your request class.
9e7f288e 1660
1661- `response_class_traits`
1662
79fb8f95 1663 An arrayref of [Moose::Role](https://metacpan.org/pod/Moose::Role)s that get composed into your response class.
9e7f288e 1664
1665- `inject_components`
1666
1667 A Hashref of [Catalyst::Component](https://metacpan.org/pod/Catalyst::Component) subclasses that are 'injected' into configuration.
1668 For example:
1669
1670 MyApp->config({
1671 inject_components => {
1672 'Controller::Err' => { from_component => 'Local::Controller::Errors' },
1673 'Model::Zoo' => { from_component => 'Local::Model::Foo' },
1674 'Model::Foo' => { from_component => 'Local::Model::Foo', roles => ['TestRole'] },
1675 },
1676 'Controller::Err' => { a => 100, b=>200, namespace=>'error' },
1677 'Model::Zoo' => { a => 2 },
1678 'Model::Foo' => { a => 100 },
1679 });
1680
1681 Generally [Catalyst](https://metacpan.org/pod/Catalyst) looks for components in your Model/View or Controller directories.
1682 However for cases when you which to use an existing component and you don't need any
1683 customization (where for when you can apply a role to customize it) you may inject those
1684 components into your application. Please note any configuration should be done 'in the
1685 normal way', with a key under configuration named after the component affix, as in the
1686 above example.
1687
1688 Using this type of injection allows you to construct significant amounts of your application
1689 with only configuration!. This may or may not lead to increased code understanding.
1690
1691 Please not you may also call the ->inject\_components application method as well, although
1692 you must do so BEFORE setup.
1693
1694# EXCEPTIONS
1695
1696Generally when you throw an exception inside an Action (or somewhere in
1697your stack, such as in a model that an Action is calling) that exception
1698is caught by Catalyst and unless you either catch it yourself (via eval
1699or something like [Try::Tiny](https://metacpan.org/pod/Try::Tiny) or by reviewing the ["error"](#error) stack, it
1700will eventually reach ["finalize\_errors"](#finalize_errors) and return either the debugging
1701error stack page, or the default error page. However, if your exception
1702can be caught by [Plack::Middleware::HTTPExceptions](https://metacpan.org/pod/Plack::Middleware::HTTPExceptions), [Catalyst](https://metacpan.org/pod/Catalyst) will
1703instead rethrow it so that it can be handled by that middleware (which
1704is part of the default middleware). For example this would allow
1705
1706 use HTTP::Throwable::Factory 'http_throw';
1707
1708 sub throws_exception :Local {
1709 my ($self, $c) = @_;
1710
1711 http_throw(SeeOther => { location =>
1712 $c->uri_for($self->action_for('redirect')) });
1713
1714 }
1715
1716# INTERNAL ACTIONS
1717
1718Catalyst uses internal actions like `_DISPATCH`, `_BEGIN`, `_AUTO`,
1719`_ACTION`, and `_END`. These are by default not shown in the private
1720action table, but you can make them visible with a config parameter.
1721
1722 MyApp->config(show_internal_actions => 1);
1723
1724# ON-DEMAND PARSER
1725
1726The request body is usually parsed at the beginning of a request,
1727but if you want to handle input yourself, you can enable on-demand
1728parsing with a config parameter.
1729
1730 MyApp->config(parse_on_demand => 1);
1731
1732# PROXY SUPPORT
1733
1734Many production servers operate using the common double-server approach,
1735with a lightweight frontend web server passing requests to a larger
1736backend server. An application running on the backend server must deal
1737with two problems: the remote user always appears to be `127.0.0.1` and
1738the server's hostname will appear to be `localhost` regardless of the
1739virtual host that the user connected through.
1740
1741Catalyst will automatically detect this situation when you are running
1742the frontend and backend servers on the same machine. The following
1743changes are made to the request.
1744
1745 $c->req->address is set to the user's real IP address, as read from
1746 the HTTP X-Forwarded-For header.
1747
1748 The host value for $c->req->base and $c->req->uri is set to the real
1749 host, as read from the HTTP X-Forwarded-Host header.
1750
1751Additionally, you may be running your backend application on an insecure
1752connection (port 80) while your frontend proxy is running under SSL. If there
1753is a discrepancy in the ports, use the HTTP header `X-Forwarded-Port` to
1754tell Catalyst what port the frontend listens on. This will allow all URIs to
1755be created properly.
1756
1757In the case of passing in:
1758
1759 X-Forwarded-Port: 443
1760
1761All calls to `uri_for` will result in an https link, as is expected.
1762
1763Obviously, your web server must support these headers for this to work.
1764
1765In a more complex server farm environment where you may have your
1766frontend proxy server(s) on different machines, you will need to set a
1767configuration option to tell Catalyst to read the proxied data from the
1768headers.
1769
1770 MyApp->config(using_frontend_proxy => 1);
1771
1772If you do not wish to use the proxy support at all, you may set:
1773
1774 MyApp->config(ignore_frontend_proxy => 0);
1775
1776## Note about psgi files
1777
1778Note that if you supply your own .psgi file, calling
1779`MyApp->psgi_app(@_);`, then **this will not happen automatically**.
1780
1781You either need to apply [Plack::Middleware::ReverseProxy](https://metacpan.org/pod/Plack::Middleware::ReverseProxy) yourself
1782in your psgi, for example:
1783
1784 builder {
1785 enable "Plack::Middleware::ReverseProxy";
1786 MyApp->psgi_app
1787 };
1788
1789This will unconditionally add the ReverseProxy support, or you need to call
1790`$app = MyApp->apply_default_middlewares($app)` (to conditionally
1791apply the support depending upon your config).
1792
1793See [Catalyst::PSGI](https://metacpan.org/pod/Catalyst::PSGI) for more information.
1794
1795# THREAD SAFETY
1796
1797Catalyst has been tested under Apache 2's threading `mpm_worker`,
1798`mpm_winnt`, and the standalone forking HTTP server on Windows. We
1799believe the Catalyst core to be thread-safe.
1800
1801If you plan to operate in a threaded environment, remember that all other
1802modules you are using must also be thread-safe. Some modules, most notably
1803[DBD::SQLite](https://metacpan.org/pod/DBD::SQLite), are not thread-safe.
1804
1805# DATA HANDLERS
1806
1807The [Catalyst::Request](https://metacpan.org/pod/Catalyst::Request) object uses [HTTP::Body](https://metacpan.org/pod/HTTP::Body) to populate 'classic' HTML
1808form parameters and URL search query fields. However it has become common
1809for various alternative content types to be PUT or POSTed to your controllers
1810and actions. People working on RESTful APIs, or using AJAX often use JSON,
1811XML and other content types when communicating with an application server. In
1812order to better support this use case, [Catalyst](https://metacpan.org/pod/Catalyst) defines a global configuration
1813option, `data_handlers`, which lets you associate a content type with a coderef
1814that parses that content type into something Perl can readily access.
1815
1816 package MyApp::Web;
1817
1818 use Catalyst;
1819 use JSON::Maybe;
1820
1821 __PACKAGE__->config(
1822 data_handlers => {
1823 'application/json' => sub { local $/; decode_json $_->getline },
1824 },
1825 ## Any other configuration.
1826 );
1827
1828 __PACKAGE__->setup;
1829
1830By default [Catalyst](https://metacpan.org/pod/Catalyst) comes with a generic JSON data handler similar to the
1831example given above, which uses [JSON::Maybe](https://metacpan.org/pod/JSON::Maybe) to provide either [JSON::PP](https://metacpan.org/pod/JSON::PP)
1832(a pure Perl, dependency free JSON parser) or [Cpanel::JSON::XS](https://metacpan.org/pod/Cpanel::JSON::XS) if you have
1833it installed (if you want the faster XS parser, add it to you project Makefile.PL
1834or dist.ini, cpanfile, etc.)
1835
1836The `data_handlers` configuration is a hashref whose keys are HTTP Content-Types
1837(matched against the incoming request type using a regexp such as to be case
1838insensitive) and whose values are coderefs that receive a localized version of
1839`$_` which is a filehandle object pointing to received body.
1840
1841This feature is considered an early access release and we reserve the right
1842to alter the interface in order to provide a performant and secure solution to
1843alternative request body content. Your reports welcomed!
1844
1845# PSGI MIDDLEWARE
1846
1847You can define middleware, defined as [Plack::Middleware](https://metacpan.org/pod/Plack::Middleware) or a compatible
1848interface in configuration. Your middleware definitions are in the form of an
1849arrayref under the configuration key `psgi_middleware`. Here's an example
1850with details to follow:
1851
1852 package MyApp::Web;
1853
1854 use Catalyst;
1855 use Plack::Middleware::StackTrace;
1856
1857 my $stacktrace_middleware = Plack::Middleware::StackTrace->new;
1858
1859 __PACKAGE__->config(
1860 'psgi_middleware', [
1861 'Debug',
1862 '+MyApp::Custom',
1863 $stacktrace_middleware,
1864 'Session' => {store => 'File'},
1865 sub {
1866 my $app = shift;
1867 return sub {
1868 my $env = shift;
1869 $env->{myapp.customkey} = 'helloworld';
1870 $app->($env);
1871 },
1872 },
1873 ],
1874 );
1875
1876 __PACKAGE__->setup;
1877
1878So the general form is:
1879
1880 __PACKAGE__->config(psgi_middleware => \@middleware_definitions);
1881
1882Where `@middleware` is one or more of the following, applied in the REVERSE of
1883the order listed (to make it function similarly to [Plack::Builder](https://metacpan.org/pod/Plack::Builder):
1884
1885Alternatively, you may also define middleware by calling the ["setup\_middleware"](#setup_middleware)
1886package method:
1887
1888 package MyApp::Web;
1889
1890 use Catalyst;
1891
1892 __PACKAGE__->setup_middleware( \@middleware_definitions);
1893 __PACKAGE__->setup;
1894
1895In the case where you do both (use 'setup\_middleware' and configuration) the
1896package call to setup\_middleware will be applied earlier (in other words its
1897middleware will wrap closer to the application). Keep this in mind since in
1898some cases the order of middleware is important.
1899
1900The two approaches are not exclusive.
1901
1902- Middleware Object
1903
1904 An already initialized object that conforms to the [Plack::Middleware](https://metacpan.org/pod/Plack::Middleware)
1905 specification:
1906
1907 my $stacktrace_middleware = Plack::Middleware::StackTrace->new;
1908
1909 __PACKAGE__->config(
1910 'psgi_middleware', [
1911 $stacktrace_middleware,
1912 ]);
1913
1914
1915
1916- coderef
1917
1918 A coderef that is an inlined middleware:
1919
1920 __PACKAGE__->config(
1921 'psgi_middleware', [
1922 sub {
1923 my $app = shift;
1924 return sub {
1925 my $env = shift;
1926 if($env->{PATH_INFO} =~m/forced/) {
1927 Plack::App::File
1928 ->new(file=>TestApp->path_to(qw/share static forced.txt/))
1929 ->call($env);
1930 } else {
1931 return $app->($env);
1932 }
1933 },
1934 },
1935 ]);
1936
1937
1938
1939
1940- a scalar
1941
1942 We assume the scalar refers to a namespace after normalizing it using the
1943 following rules:
1944
1945 (1) If the scalar is prefixed with a "+" (as in `+MyApp::Foo`) then the full string
1946 is assumed to be 'as is', and we just install and use the middleware.
1947
1948 (2) If the scalar begins with "Plack::Middleware" or your application namespace
1949 (the package name of your Catalyst application subclass), we also assume then
1950 that it is a full namespace, and use it.
1951
1952 (3) Lastly, we then assume that the scalar is a partial namespace, and attempt to
1953 resolve it first by looking for it under your application namespace (for example
1954 if you application is "MyApp::Web" and the scalar is "MyMiddleware", we'd look
1955 under "MyApp::Web::Middleware::MyMiddleware") and if we don't find it there, we
1956 will then look under the regular [Plack::Middleware](https://metacpan.org/pod/Plack::Middleware) namespace (i.e. for the
1957 previous we'd try "Plack::Middleware::MyMiddleware"). We look under your application
1958 namespace first to let you 'override' common [Plack::Middleware](https://metacpan.org/pod/Plack::Middleware) locally, should
1959 you find that a good idea.
1960
1961 Examples:
1962
1963 package MyApp::Web;
1964
1965 __PACKAGE__->config(
1966 'psgi_middleware', [
1967 'Debug', ## MyAppWeb::Middleware::Debug->wrap or Plack::Middleware::Debug->wrap
1968 'Plack::Middleware::Stacktrace', ## Plack::Middleware::Stacktrace->wrap
1969 '+MyApp::Custom', ## MyApp::Custom->wrap
1970 ],
1971 );
1972
1973
1974- a scalar followed by a hashref
1975
1976 Just like the previous, except the following `HashRef` is used as arguments
1977 to initialize the middleware object.
1978
1979 __PACKAGE__->config(
1980 'psgi_middleware', [
1981 'Session' => {store => 'File'},
1982 ]);
1983
1984Please see [PSGI](https://metacpan.org/pod/PSGI) for more on middleware.
1985
1986# ENCODING
1987
1988Starting in [Catalyst](https://metacpan.org/pod/Catalyst) version 5.90080 encoding is automatically enabled
1989and set to encode all body responses to UTF8 when possible and applicable.
1990Following is documentation on this process. If you are using an older
1991version of [Catalyst](https://metacpan.org/pod/Catalyst) you should review documentation for that version since
1992a lot has changed.
1993
1994By default encoding is now 'UTF-8'. You may turn it off by setting
1995the encoding configuration to undef.
1996
1997 MyApp->config(encoding => undef);
1998
1999This is recommended for temporary backwards compatibility only.
2000
6bd163d1 2001To turn it off for a single request use the [clear\_encoding](https://metacpan.org/pod/clear_encoding)
2002method to turn off encoding for this request. This can be useful
2003when you are setting the body to be an arbitrary block of bytes,
2004especially if that block happens to be a block of UTF8 text.
2005
9e7f288e 2006Encoding is automatically applied when the content-type is set to
2007a type that can be encoded. Currently we encode when the content type
2008matches the following regular expression:
2009
2010 $content_type =~ /^text|xml$|javascript$/
2011
2012Encoding is set on the application, but it is copied to the context object
2013so that you can override it on a request basis.
2014
2015Be default we don't automatically encode 'application/json' since the most
2016common approaches to generating this type of response (Either via [Catalyst::View::JSON](https://metacpan.org/pod/Catalyst::View::JSON)
2017or [Catalyst::Action::REST](https://metacpan.org/pod/Catalyst::Action::REST)) will do so already and we want to avoid double
2018encoding issues.
2019
2020If you are producing JSON response in an unconventional manner (such
2021as via a template or manual strings) you should perform the UTF8 encoding
2022manually as well such as to conform to the JSON specification.
2023
2024NOTE: We also examine the value of $c->response->content\_encoding. If
2025you set this (like for example 'gzip', and manually gzipping the body)
2026we assume that you have done all the necessary encoding yourself, since
2027we cannot encode the gzipped contents. If you use a plugin like
2028[Catalyst::Plugin::Compress](https://metacpan.org/pod/Catalyst::Plugin::Compress) you need to update to a modern version in order
2029to have this function correctly with the new UTF8 encoding code, or you
2030can use [Plack::Middleware::Deflater](https://metacpan.org/pod/Plack::Middleware::Deflater) or (probably best) do your compression on
2031a front end proxy.
2032
2033## Methods
2034
2035- encoding
2036
2037 Returns an instance of an `Encode` encoding
2038
2039 print $c->encoding->name
2040
2041- handle\_unicode\_encoding\_exception ($exception\_context)
2042
2043 Method called when decoding process for a request fails.
2044
2045 An `$exception_context` hashref is provided to allow you to override the
2046 behaviour of your application when given data with incorrect encodings.
2047
2048 The default method throws exceptions in the case of invalid request parameters
2049 (resulting in a 500 error), but ignores errors in upload filenames.
2050
2051 The keys passed in the `$exception_context` hash are:
2052
2053 - param\_value
2054
2055 The value which was not able to be decoded.
2056
2057 - error\_msg
2058
2059 The exception received from [Encode](https://metacpan.org/pod/Encode).
2060
2061 - encoding\_step
2062
2063 What type of data was being decoded. Valid values are (currently)
2064 `params` - for request parameters / arguments / captures
2065 and `uploads` - for request upload filenames.
2066
2067# SUPPORT
2068
2069IRC:
2070
2071 Join #catalyst on irc.perl.org.
2072
2073Mailing Lists:
2074
2075 http://lists.scsys.co.uk/cgi-bin/mailman/listinfo/catalyst
2076 http://lists.scsys.co.uk/cgi-bin/mailman/listinfo/catalyst-dev
2077
2078Web:
2079
2080 http://catalyst.perl.org
2081
2082Wiki:
2083
2084 http://dev.catalyst.perl.org
2085
2086# SEE ALSO
2087
2088## [Task::Catalyst](https://metacpan.org/pod/Task::Catalyst) - All you need to start with Catalyst
2089
2090## [Catalyst::Manual](https://metacpan.org/pod/Catalyst::Manual) - The Catalyst Manual
2091
2092## [Catalyst::Component](https://metacpan.org/pod/Catalyst::Component), [Catalyst::Controller](https://metacpan.org/pod/Catalyst::Controller) - Base classes for components
2093
2094## [Catalyst::Engine](https://metacpan.org/pod/Catalyst::Engine) - Core engine
2095
2096## [Catalyst::Log](https://metacpan.org/pod/Catalyst::Log) - Log class.
2097
2098## [Catalyst::Request](https://metacpan.org/pod/Catalyst::Request) - Request object
2099
2100## [Catalyst::Response](https://metacpan.org/pod/Catalyst::Response) - Response object
2101
2102## [Catalyst::Test](https://metacpan.org/pod/Catalyst::Test) - The test suite.
2103
2104# PROJECT FOUNDER
2105
2106sri: Sebastian Riedel <sri@cpan.org>
2107
2108# CONTRIBUTORS
2109
2110abw: Andy Wardley
2111
2112acme: Leon Brocard <leon@astray.com>
2113
2114abraxxa: Alexander Hartmaier <abraxxa@cpan.org>
2115
d1467830 2116andrewalker: André Walker <andre@cpan.org>
9e7f288e 2117
2118Andrew Bramble
2119
2120Andrew Ford <A.Ford@ford-mason.co.uk>
2121
2122Andrew Ruthven
2123
2124andyg: Andy Grundman <andy@hybridized.org>
2125
2126audreyt: Audrey Tang
2127
2128bricas: Brian Cassidy <bricas@cpan.org>
2129
2130Caelum: Rafael Kitover <rkitover@io.com>
2131
2132chansen: Christian Hansen
2133
6bd163d1 2134Chase Venters `chase.venters@gmail.com`
68b4caec 2135
9e7f288e 2136chicks: Christopher Hicks
2137
2138Chisel Wright `pause@herlpacker.co.uk`
2139
2140Danijel Milicevic `me@danijel.de`
2141
2142davewood: David Schmidt <davewood@cpan.org>
2143
2144David Kamholz <dkamholz@cpan.org>
2145
2146David Naughton, `naughton@umn.edu`
2147
2148David E. Wheeler
2149
2150dhoss: Devin Austin <dhoss@cpan.org>
2151
2152dkubb: Dan Kubb <dan.kubb-cpan@onautopilot.com>
2153
2154Drew Taylor
2155
2156dwc: Daniel Westermann-Clark <danieltwc@cpan.org>
2157
2158esskar: Sascha Kiefer
2159
2160fireartist: Carl Franks <cfranks@cpan.org>
2161
2162frew: Arthur Axel "fREW" Schmidt <frioux@gmail.com>
2163
2164gabb: Danijel Milicevic
2165
2166Gary Ashton Jones
2167
2168Gavin Henry `ghenry@perl.me.uk`
2169
2170Geoff Richards
2171
2172groditi: Guillermo Roditi <groditi@gmail.com>
2173
2174hobbs: Andrew Rodland <andrew@cleverdomain.org>
2175
d1467830 2176ilmari: Dagfinn Ilmari Mannsåker <ilmari@ilmari.org>
9e7f288e 2177
2178jcamacho: Juan Camacho
2179
2180jester: Jesse Sheidlower `jester@panix.com`
2181
2182jhannah: Jay Hannah <jay@jays.net>
2183
2184Jody Belka
2185
2186Johan Lindstrom
2187
2188jon: Jon Schutz <jjschutz@cpan.org>
2189
2190Jonathan Rockway `<jrockway@cpan.org>`
2191
2192Kieren Diment `kd@totaldatasolution.com`
2193
2194konobi: Scott McWhirter <konobi@cpan.org>
2195
2196marcus: Marcus Ramberg <mramberg@cpan.org>
2197
2198miyagawa: Tatsuhiko Miyagawa <miyagawa@bulknews.net>
2199
2200mgrimes: Mark Grimes <mgrimes@cpan.org>
2201
2202mst: Matt S. Trout <mst@shadowcatsystems.co.uk>
2203
2204mugwump: Sam Vilain
2205
2206naughton: David Naughton
2207
2208ningu: David Kamholz <dkamholz@cpan.org>
2209
2210nothingmuch: Yuval Kogman <nothingmuch@woobling.org>
2211
2212numa: Dan Sully <daniel@cpan.org>
2213
2214obra: Jesse Vincent
2215
2216Octavian Rasnita
2217
2218omega: Andreas Marienborg
2219
2220Oleg Kostyuk <cub.uanic@gmail.com>
2221
2222phaylon: Robert Sedlacek <phaylon@dunkelheit.at>
2223
2224rafl: Florian Ragwitz <rafl@debian.org>
2225
2226random: Roland Lammel <lammel@cpan.org>
2227
2228Robert Sedlacek `<rs@474.at>`
2229
2230SpiceMan: Marcel Montes
2231
2232sky: Arthur Bergman
2233
2234szbalint: Balint Szilakszi <szbalint@cpan.org>
2235
2236t0m: Tomas Doran <bobtfish@bobtfish.net>
2237
2238Ulf Edvinsson
2239
2240vanstyn: Henry Van Styn <vanstyn@cpan.org>
2241
2242Viljo Marrandi `vilts@yahoo.com`
2243
2244Will Hawes `info@whawes.co.uk`
2245
2246willert: Sebastian Willert <willert@cpan.org>
2247
2248wreis: Wallace Reis <wreis@cpan.org>
2249
2250Yuval Kogman, `nothingmuch@woobling.org`
2251
2252rainboxx: Matthias Dietrich, `perl@rainboxx.de`
2253
2254dd070: Dhaval Dhanani <dhaval070@gmail.com>
2255
2256Upasana <me@upasana.me>
2257
2258John Napiorkowski (jnap) <jjnapiork@cpan.org>
2259
2260# COPYRIGHT
2261
2262Copyright (c) 2005-2015, the above named PROJECT FOUNDER and CONTRIBUTORS.
2263
2264# LICENSE
2265
2266This library is free software. You can redistribute it and/or modify it under
2267the same terms as Perl itself.