042e786489c8da53694d6690ea016b9b4e6bfc2d
[catagits/Catalyst-Runtime.git] / lib / Catalyst.pm
1 package Catalyst;
2
3 use Moose;
4 use Moose::Meta::Class ();
5 extends 'Catalyst::Component';
6 use Moose::Util qw/find_meta/;
7 use namespace::clean -except => 'meta';
8 use Catalyst::Exception;
9 use Catalyst::Exception::Detach;
10 use Catalyst::Exception::Go;
11 use Catalyst::Log;
12 use Catalyst::Request;
13 use Catalyst::Request::Upload;
14 use Catalyst::Response;
15 use Catalyst::Utils;
16 use Catalyst::Controller;
17 use Data::OptList;
18 use File::stat;
19 use Text::SimpleTable ();
20 use Path::Class::Dir ();
21 use Path::Class::File ();
22 use URI ();
23 use URI::http;
24 use URI::https;
25 use Tree::Simple qw/use_weak_refs/;
26 use Tree::Simple::Visitor::FindByUID;
27 use Class::C3::Adopt::NEXT;
28 use List::MoreUtils qw/uniq/;
29 use attributes;
30 use String::RewritePrefix;
31 use Catalyst::EngineLoader;
32 use utf8;
33 use Carp qw/croak carp shortmess/;
34 use Try::Tiny;
35 use Plack::Middleware::Conditional;
36 use Plack::Middleware::ReverseProxy;
37 use Plack::Middleware::IIS6ScriptNameFix;
38 use Plack::Middleware::LighttpdScriptNameFix;
39
40 BEGIN { require 5.008003; }
41
42 has stack => (is => 'ro', default => sub { [] });
43 has stash => (is => 'rw', default => sub { {} });
44 has state => (is => 'rw', default => 0);
45 has stats => (is => 'rw');
46 has action => (is => 'rw');
47 has counter => (is => 'rw', default => sub { {} });
48 has request => (
49     is => 'rw',
50     default => sub {
51         my $self = shift;
52         my %p = ( _log => $self->log );
53         $p{_uploadtmp} = $self->_uploadtmp if $self->_has_uploadtmp;
54         $self->request_class->new(\%p);
55     },
56     lazy => 1,
57 );
58 has response => (
59     is => 'rw',
60     default => sub {
61         my $self = shift;
62         $self->response_class->new({ _log => $self->log });
63     },
64     lazy => 1,
65 );
66 has namespace => (is => 'rw');
67
68 sub depth { scalar @{ shift->stack || [] }; }
69 sub comp { shift->component(@_) }
70
71 sub req {
72     my $self = shift; return $self->request(@_);
73 }
74 sub res {
75     my $self = shift; return $self->response(@_);
76 }
77
78 # For backwards compatibility
79 sub finalize_output { shift->finalize_body(@_) };
80
81 # For statistics
82 our $COUNT     = 1;
83 our $START     = time;
84 our $RECURSION = 1000;
85 our $DETACH    = Catalyst::Exception::Detach->new;
86 our $GO        = Catalyst::Exception::Go->new;
87
88 #I imagine that very few of these really need to be class variables. if any.
89 #maybe we should just make them attributes with a default?
90 __PACKAGE__->mk_classdata($_)
91   for qw/container arguments dispatcher engine log dispatcher_class
92   engine_loader context_class request_class response_class stats_class
93   setup_finished _psgi_app loading_psgi_file run_options/;
94
95 __PACKAGE__->dispatcher_class('Catalyst::Dispatcher');
96 __PACKAGE__->request_class('Catalyst::Request');
97 __PACKAGE__->response_class('Catalyst::Response');
98 __PACKAGE__->stats_class('Catalyst::Stats');
99
100 # Remember to update this in Catalyst::Runtime as well!
101
102 our $VERSION = '5.90015';
103
104 sub import {
105     my ( $class, @arguments ) = @_;
106
107     # We have to limit $class to Catalyst to avoid pushing Catalyst upon every
108     # callers @ISA.
109     return unless $class eq 'Catalyst';
110
111     my $caller = caller();
112     return if $caller eq 'main';
113
114     my $meta = Moose::Meta::Class->initialize($caller);
115
116     unless ( $caller->isa('Catalyst') ) { # XXX - Remove!
117         my @superclasses = ($meta->superclasses, $class, 'Catalyst::Component'); # XXX - Remove!
118         $meta->superclasses(@superclasses); # XXX - Remove!
119     } # XXX - Remove!
120
121     # Avoid possible C3 issues if 'Moose::Object' is already on RHS of MyApp
122     $meta->superclasses(grep { $_ ne 'Moose::Object' } $meta->superclasses);
123
124     unless( $meta->has_method('meta') ){
125         if ($Moose::VERSION >= 1.15) {
126             $meta->_add_meta_method('meta');
127         }
128         else {
129             $meta->add_method(meta => sub { Moose::Meta::Class->initialize("${caller}") } );
130         }
131     }
132
133     $caller->arguments( [@arguments] );
134     $caller->setup_home;
135 }
136
137 sub MODIFY_CODE_ATTRIBUTES {
138     Catalyst::Exception->throw(
139         "Catalyst applications (aka MyApp) cannot be controllers anymore. " .
140         "That has been deprecated and removed. You should create a " .
141         "controller class called Root.pm, and move relevant code to that class."
142     );
143 }
144
145
146 sub _application { $_[0] }
147
148 =encoding utf8
149
150 =head1 NAME
151
152 Catalyst - The Elegant MVC Web Application Framework
153
154 =head1 SYNOPSIS
155
156 See the L<Catalyst::Manual> distribution for comprehensive
157 documentation and tutorials.
158
159     # Install Catalyst::Devel for helpers and other development tools
160     # use the helper to create a new application
161     catalyst.pl MyApp
162
163     # add models, views, controllers
164     script/myapp_create.pl model MyDatabase DBIC::Schema create=static dbi:SQLite:/path/to/db
165     script/myapp_create.pl view MyTemplate TT
166     script/myapp_create.pl controller Search
167
168     # built in testserver -- use -r to restart automatically on changes
169     # --help to see all available options
170     script/myapp_server.pl
171
172     # command line testing interface
173     script/myapp_test.pl /yada
174
175     ### in lib/MyApp.pm
176     use Catalyst qw/-Debug/; # include plugins here as well
177
178     ### In lib/MyApp/Controller/Root.pm (autocreated)
179     sub foo : Chained('/') Args() { # called for /foo, /foo/1, /foo/1/2, etc.
180         my ( $self, $c, @args ) = @_; # args are qw/1 2/ for /foo/1/2
181         $c->stash->{template} = 'foo.tt'; # set the template
182         # lookup something from db -- stash vars are passed to TT
183         $c->stash->{data} =
184           $c->model('Database::Foo')->search( { country => $args[0] } );
185         if ( $c->req->params->{bar} ) { # access GET or POST parameters
186             $c->forward( 'bar' ); # process another action
187             # do something else after forward returns
188         }
189     }
190
191     # The foo.tt TT template can use the stash data from the database
192     [% WHILE (item = data.next) %]
193         [% item.foo %]
194     [% END %]
195
196     # called for /bar/of/soap, /bar/of/soap/10, etc.
197     sub bar : Chained('/') PathPart('/bar/of/soap') Args() { ... }
198
199     # called after all actions are finished
200     sub end : Action {
201         my ( $self, $c ) = @_;
202         if ( scalar @{ $c->error } ) { ... } # handle errors
203         return if $c->res->body; # already have a response
204         $c->forward( 'MyApp::View::TT' ); # render template
205     }
206
207 See L<Catalyst::Manual::Intro> for additional information.
208
209 =head1 DESCRIPTION
210
211 Catalyst is a modern framework for making web applications without the
212 pain usually associated with this process. This document is a reference
213 to the main Catalyst application. If you are a new user, we suggest you
214 start with L<Catalyst::Manual::Tutorial> or L<Catalyst::Manual::Intro>.
215
216 See L<Catalyst::Manual> for more documentation.
217
218 Catalyst plugins can be loaded by naming them as arguments to the "use
219 Catalyst" statement. Omit the C<Catalyst::Plugin::> prefix from the
220 plugin name, i.e., C<Catalyst::Plugin::My::Module> becomes
221 C<My::Module>.
222
223     use Catalyst qw/My::Module/;
224
225 If your plugin starts with a name other than C<Catalyst::Plugin::>, you can
226 fully qualify the name by using a unary plus:
227
228     use Catalyst qw/
229         My::Module
230         +Fully::Qualified::Plugin::Name
231     /;
232
233 Special flags like C<-Debug> can also be specified as
234 arguments when Catalyst is loaded:
235
236     use Catalyst qw/-Debug My::Module/;
237
238 The position of plugins and flags in the chain is important, because
239 they are loaded in the order in which they appear.
240
241 The following flags are supported:
242
243 =head2 -Debug
244
245 Enables debug output. You can also force this setting from the system
246 environment with CATALYST_DEBUG or <MYAPP>_DEBUG. The environment
247 settings override the application, with <MYAPP>_DEBUG having the highest
248 priority.
249
250 This sets the log level to 'debug' and enables full debug output on the
251 error screen. If you only want the latter, see L<< $c->debug >>.
252
253 =head2 -Home
254
255 Forces Catalyst to use a specific home directory, e.g.:
256
257     use Catalyst qw[-Home=/usr/mst];
258
259 This can also be done in the shell environment by setting either the
260 C<CATALYST_HOME> environment variable or C<MYAPP_HOME>; where C<MYAPP>
261 is replaced with the uppercased name of your application, any "::" in
262 the name will be replaced with underscores, e.g. MyApp::Web should use
263 MYAPP_WEB_HOME. If both variables are set, the MYAPP_HOME one will be used.
264
265 If none of these are set, Catalyst will attempt to automatically detect the
266 home directory. If you are working in a development environment, Catalyst
267 will try and find the directory containing either Makefile.PL, Build.PL or
268 dist.ini. If the application has been installed into the system (i.e.
269 you have done C<make install>), then Catalyst will use the path to your
270 application module, without the .pm extension (e.g., /foo/MyApp if your
271 application was installed at /foo/MyApp.pm)
272
273 =head2 -Log
274
275     use Catalyst '-Log=warn,fatal,error';
276
277 Specifies a comma-delimited list of log levels.
278
279 =head2 -Stats
280
281 Enables statistics collection and reporting.
282
283    use Catalyst qw/-Stats=1/;
284
285 You can also force this setting from the system environment with CATALYST_STATS
286 or <MYAPP>_STATS. The environment settings override the application, with
287 <MYAPP>_STATS having the highest priority.
288
289 Stats are also enabled if L<< debugging |/"-Debug" >> is enabled.
290
291 =head1 METHODS
292
293 =head2 INFORMATION ABOUT THE CURRENT REQUEST
294
295 =head2 $c->action
296
297 Returns a L<Catalyst::Action> object for the current action, which
298 stringifies to the action name. See L<Catalyst::Action>.
299
300 =head2 $c->namespace
301
302 Returns the namespace of the current action, i.e., the URI prefix
303 corresponding to the controller of the current action. For example:
304
305     # in Controller::Foo::Bar
306     $c->namespace; # returns 'foo/bar';
307
308 =head2 $c->request
309
310 =head2 $c->req
311
312 Returns the current L<Catalyst::Request> object, giving access to
313 information about the current client request (including parameters,
314 cookies, HTTP headers, etc.). See L<Catalyst::Request>.
315
316 =head2 REQUEST FLOW HANDLING
317
318 =head2 $c->forward( $action [, \@arguments ] )
319
320 =head2 $c->forward( $class, $method, [, \@arguments ] )
321
322 Forwards processing to another action, by its private name. If you give a
323 class name but no method, C<process()> is called. You may also optionally
324 pass arguments in an arrayref. The action will receive the arguments in
325 C<@_> and C<< $c->req->args >>. Upon returning from the function,
326 C<< $c->req->args >> will be restored to the previous values.
327
328 Any data C<return>ed from the action forwarded to, will be returned by the
329 call to forward.
330
331     my $foodata = $c->forward('/foo');
332     $c->forward('index');
333     $c->forward(qw/Model::DBIC::Foo do_stuff/);
334     $c->forward('View::TT');
335
336 Note that L<< forward|/"$c->forward( $action [, \@arguments ] )" >> implies
337 an C<< eval { } >> around the call (actually
338 L<< execute|/"$c->execute( $class, $coderef )" >> does), thus rendering all
339 exceptions thrown by the called action non-fatal and pushing them onto
340 $c->error instead. If you want C<die> to propagate you need to do something
341 like:
342
343     $c->forward('foo');
344     die join "\n", @{ $c->error } if @{ $c->error };
345
346 Or make sure to always return true values from your actions and write
347 your code like this:
348
349     $c->forward('foo') || return;
350
351 Another note is that C<< $c->forward >> always returns a scalar because it
352 actually returns $c->state which operates in a scalar context.
353 Thus, something like:
354
355     return @array;
356
357 in an action that is forwarded to is going to return a scalar,
358 i.e. how many items are in that array, which is probably not what you want.
359 If you need to return an array then return a reference to it,
360 or stash it like so:
361
362     $c->stash->{array} = \@array;
363
364 and access it from the stash.
365
366 Keep in mind that the C<end> method used is that of the caller action. So a C<$c-E<gt>detach> inside a forwarded action would run the C<end> method from the original action requested.
367
368 =cut
369
370 sub forward { my $c = shift; no warnings 'recursion'; $c->dispatcher->forward( $c, @_ ) }
371
372 =head2 $c->detach( $action [, \@arguments ] )
373
374 =head2 $c->detach( $class, $method, [, \@arguments ] )
375
376 =head2 $c->detach()
377
378 The same as L<< forward|/"$c->forward( $action [, \@arguments ] )" >>, but
379 doesn't return to the previous action when processing is finished.
380
381 When called with no arguments it escapes the processing chain entirely.
382
383 =cut
384
385 sub detach { my $c = shift; $c->dispatcher->detach( $c, @_ ) }
386
387 =head2 $c->visit( $action [, \@arguments ] )
388
389 =head2 $c->visit( $action [, \@captures, \@arguments ] )
390
391 =head2 $c->visit( $class, $method, [, \@arguments ] )
392
393 =head2 $c->visit( $class, $method, [, \@captures, \@arguments ] )
394
395 Almost the same as L<< forward|/"$c->forward( $action [, \@arguments ] )" >>,
396 but does a full dispatch, instead of just calling the new C<$action> /
397 C<< $class->$method >>. This means that C<begin>, C<auto> and the method
398 you go to are called, just like a new request.
399
400 In addition both C<< $c->action >> and C<< $c->namespace >> are localized.
401 This means, for example, that C<< $c->action >> methods such as
402 L<name|Catalyst::Action/name>, L<class|Catalyst::Action/class> and
403 L<reverse|Catalyst::Action/reverse> return information for the visited action
404 when they are invoked within the visited action.  This is different from the
405 behavior of L<< forward|/"$c->forward( $action [, \@arguments ] )" >>, which
406 continues to use the $c->action object from the caller action even when
407 invoked from the called action.
408
409 C<< $c->stash >> is kept unchanged.
410
411 In effect, L<< visit|/"$c->visit( $action [, \@captures, \@arguments ] )" >>
412 allows you to "wrap" another action, just as it would have been called by
413 dispatching from a URL, while the analogous
414 L<< go|/"$c->go( $action [, \@captures, \@arguments ] )" >> allows you to
415 transfer control to another action as if it had been reached directly from a URL.
416
417 =cut
418
419 sub visit { my $c = shift; $c->dispatcher->visit( $c, @_ ) }
420
421 =head2 $c->go( $action [, \@arguments ] )
422
423 =head2 $c->go( $action [, \@captures, \@arguments ] )
424
425 =head2 $c->go( $class, $method, [, \@arguments ] )
426
427 =head2 $c->go( $class, $method, [, \@captures, \@arguments ] )
428
429 The relationship between C<go> and
430 L<< visit|/"$c->visit( $action [, \@captures, \@arguments ] )" >> is the same as
431 the relationship between
432 L<< forward|/"$c->forward( $class, $method, [, \@arguments ] )" >> and
433 L<< detach|/"$c->detach( $action [, \@arguments ] )" >>. Like C<< $c->visit >>,
434 C<< $c->go >> will perform a full dispatch on the specified action or method,
435 with localized C<< $c->action >> and C<< $c->namespace >>. Like C<detach>,
436 C<go> escapes the processing of the current request chain on completion, and
437 does not return to its caller.
438
439 @arguments are arguments to the final destination of $action. @captures are
440 arguments to the intermediate steps, if any, on the way to the final sub of
441 $action.
442
443 =cut
444
445 sub go { my $c = shift; $c->dispatcher->go( $c, @_ ) }
446
447 =head2 $c->response
448
449 =head2 $c->res
450
451 Returns the current L<Catalyst::Response> object, see there for details.
452
453 =head2 $c->stash
454
455 Returns a hashref to the stash, which may be used to store data and pass
456 it between components during a request. You can also set hash keys by
457 passing arguments. The stash is automatically sent to the view. The
458 stash is cleared at the end of a request; it cannot be used for
459 persistent storage (for this you must use a session; see
460 L<Catalyst::Plugin::Session> for a complete system integrated with
461 Catalyst).
462
463     $c->stash->{foo} = $bar;
464     $c->stash( { moose => 'majestic', qux => 0 } );
465     $c->stash( bar => 1, gorch => 2 ); # equivalent to passing a hashref
466
467     # stash is automatically passed to the view for use in a template
468     $c->forward( 'MyApp::View::TT' );
469
470 =cut
471
472 around stash => sub {
473     my $orig = shift;
474     my $c = shift;
475     my $stash = $orig->($c);
476     if (@_) {
477         my $new_stash = @_ > 1 ? {@_} : $_[0];
478         croak('stash takes a hash or hashref') unless ref $new_stash;
479         foreach my $key ( keys %$new_stash ) {
480           $stash->{$key} = $new_stash->{$key};
481         }
482     }
483
484     return $stash;
485 };
486
487
488 =head2 $c->error
489
490 =head2 $c->error($error, ...)
491
492 =head2 $c->error($arrayref)
493
494 Returns an arrayref containing error messages.  If Catalyst encounters an
495 error while processing a request, it stores the error in $c->error.  This
496 method should only be used to store fatal error messages.
497
498     my @error = @{ $c->error };
499
500 Add a new error.
501
502     $c->error('Something bad happened');
503
504 =cut
505
506 sub error {
507     my $c = shift;
508     if ( $_[0] ) {
509         my $error = ref $_[0] eq 'ARRAY' ? $_[0] : [@_];
510         croak @$error unless ref $c;
511         push @{ $c->{error} }, @$error;
512     }
513     elsif ( defined $_[0] ) { $c->{error} = undef }
514     return $c->{error} || [];
515 }
516
517
518 =head2 $c->state
519
520 Contains the return value of the last executed action.
521 Note that << $c->state >> operates in a scalar context which means that all
522 values it returns are scalar.
523
524 =head2 $c->clear_errors
525
526 Clear errors.  You probably don't want to clear the errors unless you are
527 implementing a custom error screen.
528
529 This is equivalent to running
530
531     $c->error(0);
532
533 =cut
534
535 sub clear_errors {
536     my $c = shift;
537     $c->error(0);
538 }
539
540 =head2 COMPONENT ACCESSORS
541
542 =head2 $c->controller($name)
543
544 Gets a L<Catalyst::Controller> instance by name.
545
546     $c->controller('Foo')->do_stuff;
547
548 If the name is omitted, will return the controller for the dispatched
549 action.
550
551 If you want to search for controllers, pass in a regexp as the argument.
552
553     # find all controllers that start with Foo
554     my @foo_controllers = $c->controller(qr{^Foo});
555
556
557 =cut
558
559 sub controller { shift->_lookup_mvc('controller', @_) }
560
561 =head2 $c->model($name)
562
563 Gets a L<Catalyst::Model> instance by name.
564
565     $c->model('Foo')->do_stuff;
566
567 Any extra arguments are directly passed to ACCEPT_CONTEXT.
568
569 If the name is omitted, it will look for
570  - a model object in $c->stash->{current_model_instance}, then
571  - a model name in $c->stash->{current_model}, then
572  - a config setting 'default_model', or
573  - check if there is only one model, and return it if that's the case.
574
575 If you want to search for models, pass in a regexp as the argument.
576
577     # find all models that start with Foo
578     my @foo_models = $c->model(qr{^Foo});
579
580 =cut
581
582 sub model { shift->_lookup_mvc('model', @_) }
583
584 =head2 $c->view($name)
585
586 Gets a L<Catalyst::View> instance by name.
587
588     $c->view('Foo')->do_stuff;
589
590 Any extra arguments are directly passed to ACCEPT_CONTEXT.
591
592 If the name is omitted, it will look for
593  - a view object in $c->stash->{current_view_instance}, then
594  - a view name in $c->stash->{current_view}, then
595  - a config setting 'default_view', or
596  - check if there is only one view, and return it if that's the case.
597
598 If you want to search for views, pass in a regexp as the argument.
599
600     # find all views that start with Foo
601     my @foo_views = $c->view(qr{^Foo});
602
603 =cut
604
605 sub view { shift->_lookup_mvc('view', @_) }
606
607 sub _lookup_mvc {
608     my ( $c, $type, $name, @args ) = @_;
609
610     if (ref $c && !$name) {
611         my $current_instance = $c->stash->{"current_${type}_instance"};
612         return $current_instance
613             if $current_instance && $type ne 'controller';
614
615         $name = $type eq 'controller'
616               ? Catalyst::Utils::class2classshortsuffix($c->action->class)
617               : $c->stash->{"current_${type}"}
618               ;
619     }
620
621     return $c->container->get_component_from_sub_container($type, $name, $c, @args);
622 }
623
624 =head2 $c->controllers
625
626 Returns the available names which can be passed to $c->controller
627
628 =cut
629
630 sub controllers {
631     my ( $c ) = @_;
632     return $c->container->get_sub_container('controller')->get_service_list;
633 }
634
635 =head2 $c->models
636
637 Returns the available names which can be passed to $c->model
638
639 =cut
640
641 sub models {
642     my ( $c ) = @_;
643     return $c->container->get_sub_container('model')->get_service_list;
644 }
645
646
647 =head2 $c->views
648
649 Returns the available names which can be passed to $c->view
650
651 =cut
652
653 sub views {
654     my ( $c ) = @_;
655     return $c->container->get_sub_container('view')->get_service_list;
656 }
657
658 =head2 $c->comp($name)
659
660 =head2 $c->component($name)
661
662 Gets a component object by name. This method is not recommended,
663 unless you want to get a specific component by full
664 class. C<< $c->controller >>, C<< $c->model >>, and C<< $c->view >>
665 should be used instead.
666
667 If C<$name> is a regexp, a list of components matched against the full
668 component name will be returned.
669
670 =cut
671
672 sub component {
673     my ( $c, $component, @args ) = @_;
674
675     unless ($component) {
676         $c->log->warn('Calling $c->component with no args is deprecated and ');
677         $c->log->warn('will be removed in a future release.');
678         $c->log->warn('Use $c->component_list instead.');
679         return $c->component_list;
680     }
681
682     my @result = $c->container->find_component( $component, $c, @args );
683
684     # list context for regexp searches
685     return @result if ref $component;
686
687     # only one component (if it's found) for string searches
688     return shift @result if @result;
689
690     if (ref $c eq $component) {
691         $c->log->warn('You are calling $c->comp("MyApp"). This behaviour is');
692         $c->log->warn('deprecated, and will be removed in a future release.');
693         return $c;
694     }
695
696     $c->log->warn("Looking for '$component', but nothing was found.");
697
698     # I would expect to return an empty list here, but that breaks back-compat
699     $c->log->warn('Component not found, returning the list of existing');
700     $c->log->warn('components. This behavior is deprecated and will be');
701     $c->log->warn('removed in a future release. Use $c->component_list');
702     $c->log->warn('instead.');
703
704     return $c->component_list;
705 }
706
707 =head2 $c->component_list
708
709 Returns the sorted list of the component names of the application.
710
711 =cut
712
713 sub component_list { sort keys %{ shift->components } }
714
715 =head2 CLASS DATA AND HELPER CLASSES
716
717 =head2 $c->config
718
719 Returns or takes a hashref containing the application's configuration.
720
721     __PACKAGE__->config( { db => 'dsn:SQLite:foo.db' } );
722
723 You can also use a C<YAML>, C<XML> or L<Config::General> config file
724 like C<myapp.conf> in your applications home directory. See
725 L<Catalyst::Plugin::ConfigLoader>.
726
727 =head3 Cascading configuration
728
729 The config method is present on all Catalyst components, and configuration
730 will be merged when an application is started. Configuration loaded with
731 L<Catalyst::Plugin::ConfigLoader> takes precedence over other configuration,
732 followed by configuration in your top level C<MyApp> class. These two
733 configurations are merged, and then configuration data whose hash key matches a
734 component name is merged with configuration for that component.
735
736 The configuration for a component is then passed to the C<new> method when a
737 component is constructed.
738
739 For example:
740
741     MyApp->config({ 'Model::Foo' => { bar => 'baz', overrides => 'me' } });
742     MyApp::Model::Foo->config({ quux => 'frob', overrides => 'this' });
743
744 will mean that C<MyApp::Model::Foo> receives the following data when
745 constructed:
746
747     MyApp::Model::Foo->new({
748         bar => 'baz',
749         quux => 'frob',
750         overrides => 'me',
751     });
752
753 It's common practice to use a Moose attribute
754 on the receiving component to access the config value.
755
756     package MyApp::Model::Foo;
757
758     use Moose;
759
760     # this attr will receive 'baz' at construction time
761     has 'bar' => (
762         is  => 'rw',
763         isa => 'Str',
764     );
765
766 You can then get the value 'baz' by calling $c->model('Foo')->bar
767 (or $self->bar inside code in the model).
768
769 B<NOTE:> you MUST NOT call C<< $self->config >> or C<< __PACKAGE__->config >>
770 as a way of reading config within your code, as this B<will not> give you the
771 correctly merged config back. You B<MUST> take the config values supplied to
772 the constructor and use those instead.
773
774 =cut
775
776 around config => sub {
777     my $orig = shift;
778     my $c = shift;
779
780     croak('Setting config after setup has been run is not allowed.')
781         if ( @_ and $c->setup_finished );
782
783     $c->$orig(@_);
784 };
785
786 =head2 $c->log
787
788 Returns the logging object instance. Unless it is already set, Catalyst
789 sets this up with a L<Catalyst::Log> object. To use your own log class,
790 set the logger with the C<< __PACKAGE__->log >> method prior to calling
791 C<< __PACKAGE__->setup >>.
792
793  __PACKAGE__->log( MyLogger->new );
794  __PACKAGE__->setup;
795
796 And later:
797
798     $c->log->info( 'Now logging with my own logger!' );
799
800 Your log class should implement the methods described in
801 L<Catalyst::Log>.
802
803
804 =head2 $c->debug
805
806 Returns 1 if debug mode is enabled, 0 otherwise.
807
808 You can enable debug mode in several ways:
809
810 =over
811
812 =item By calling myapp_server.pl with the -d flag
813
814 =item With the environment variables MYAPP_DEBUG, or CATALYST_DEBUG
815
816 =item The -Debug option in your MyApp.pm
817
818 =item By declaring C<sub debug { 1 }> in your MyApp.pm.
819
820 =back
821
822 The first three also set the log level to 'debug'.
823
824 Calling C<< $c->debug(1) >> has no effect.
825
826 =cut
827
828 sub debug { 0 }
829
830 =head2 $c->dispatcher
831
832 Returns the dispatcher instance. See L<Catalyst::Dispatcher>.
833
834 =head2 $c->engine
835
836 Returns the engine instance. See L<Catalyst::Engine>.
837
838
839 =head2 UTILITY METHODS
840
841 =head2 $c->path_to(@path)
842
843 Merges C<@path> with C<< $c->config->{home} >> and returns a
844 L<Path::Class::Dir> object. Note you can usually use this object as
845 a filename, but sometimes you will have to explicitly stringify it
846 yourself by calling the C<< ->stringify >> method.
847
848 For example:
849
850     $c->path_to( 'db', 'sqlite.db' );
851
852 =cut
853
854 sub path_to {
855     my ( $c, @path ) = @_;
856     my $path = Path::Class::Dir->new( $c->config->{home}, @path );
857     if ( -d $path ) { return $path }
858     else { return Path::Class::File->new( $c->config->{home}, @path ) }
859 }
860
861 sub plugin {
862     my ( $class, $name, $plugin, @args ) = @_;
863
864     # See block comment in t/aggregate/unit_core_plugin.t
865     # See block comment in t/unit_core_plugin.t
866     $class->log->warn(qq/Adding plugin using the ->plugin method is deprecated, and will be removed in a future release/);
867
868     $class->_register_plugin( $plugin, 1 );
869
870     eval { $plugin->import };
871     $class->mk_classdata($name);
872     my $obj;
873     eval { $obj = $plugin->new(@args) };
874
875     if ($@) {
876         Catalyst::Exception->throw( message =>
877               qq/Couldn't instantiate instant plugin "$plugin", "$@"/ );
878     }
879
880     $class->$name($obj);
881     $class->log->debug(qq/Initialized instant plugin "$plugin" as "$name"/)
882       if $class->debug;
883 }
884
885 =head2 MyApp->setup
886
887 Initializes the dispatcher and engine, loads any plugins, and loads the
888 model, view, and controller components. You may also specify an array
889 of plugins to load here, if you choose to not load them in the C<use
890 Catalyst> line.
891
892     MyApp->setup;
893     MyApp->setup( qw/-Debug/ );
894
895 B<Note:> You B<should not> wrap this method with method modifiers
896 or bad things will happen - wrap the C<setup_finalize> method instead.
897
898 =cut
899
900 sub setup {
901     my ( $class, @arguments ) = @_;
902     croak('Running setup more than once')
903         if ( $class->setup_finished );
904
905     unless ( $class->isa('Catalyst') ) {
906
907         Catalyst::Exception->throw(
908             message => qq/'$class' does not inherit from Catalyst/ );
909     }
910
911     if ( $class->arguments ) {
912         @arguments = ( @arguments, @{ $class->arguments } );
913     }
914
915     # Process options
916     my $flags = {};
917
918     foreach (@arguments) {
919
920         if (/^-Debug$/) {
921             $flags->{log} =
922               ( $flags->{log} ) ? 'debug,' . $flags->{log} : 'debug';
923         }
924         elsif (/^-(\w+)=?(.*)$/) {
925             $flags->{ lc $1 } = $2;
926         }
927         else {
928             push @{ $flags->{plugins} }, $_;
929         }
930     }
931
932     $class->setup_config();
933     $class->setup_home( delete $flags->{home} );
934
935     $class->setup_log( delete $flags->{log} );
936     $class->setup_plugins( delete $flags->{plugins} );
937     $class->setup_dispatcher( delete $flags->{dispatcher} );
938     if (my $engine = delete $flags->{engine}) {
939         $class->log->warn("Specifying the engine in ->setup is no longer supported, see Catalyst::Upgrading");
940     }
941     $class->setup_engine();
942     $class->setup_stats( delete $flags->{stats} );
943
944     for my $flag ( sort keys %{$flags} ) {
945
946         if ( my $code = $class->can( 'setup_' . $flag ) ) {
947             &$code( $class, delete $flags->{$flag} );
948         }
949         else {
950             $class->log->warn(qq/Unknown flag "$flag"/);
951         }
952     }
953
954     eval { require Catalyst::Devel; };
955     if( !$@ && $ENV{CATALYST_SCRIPT_GEN} && ( $ENV{CATALYST_SCRIPT_GEN} < $Catalyst::Devel::CATALYST_SCRIPT_GEN ) ) {
956         $class->log->warn(<<"EOF");
957 You are running an old script!
958
959   Please update by running (this will overwrite existing files):
960     catalyst.pl -force -scripts $class
961
962   or (this will not overwrite existing files):
963     catalyst.pl -scripts $class
964
965 EOF
966     }
967
968     if ( $class->debug ) {
969         my @plugins = map { "$_  " . ( $_->VERSION || '' ) } $class->registered_plugins;
970
971         if (@plugins) {
972             my $column_width = Catalyst::Utils::term_width() - 6;
973             my $t = Text::SimpleTable->new($column_width);
974             $t->row($_) for @plugins;
975             $class->log->debug( "Loaded plugins:\n" . $t->draw . "\n" );
976         }
977
978         my $dispatcher = $class->dispatcher;
979         my $engine     = $class->engine;
980         my $home       = $class->config->{home};
981
982         $class->log->debug(sprintf(q/Loaded dispatcher "%s"/, blessed($dispatcher)));
983         $class->log->debug(sprintf(q/Loaded engine "%s"/, blessed($engine)));
984
985         $home
986           ? ( -d $home )
987           ? $class->log->debug(qq/Found home "$home"/)
988           : $class->log->debug(qq/Home "$home" doesn't exist/)
989           : $class->log->debug(q/Couldn't find home/);
990     }
991
992     # Call plugins setup, this is stupid and evil.
993     # Also screws C3 badly on 5.10, hack to avoid.
994     {
995         no warnings qw/redefine/;
996         local *setup = sub { };
997         $class->setup unless $Catalyst::__AM_RESTARTING;
998     }
999
1000     $class->setup_components;
1001
1002     if (
1003         $class->debug and
1004         my $comps = $class->container->get_all_components($class)
1005     ) {
1006         my $column_width = Catalyst::Utils::term_width() - 8 - 9;
1007         my $t = Text::SimpleTable->new( [ $column_width, 'Class' ], [ 8, 'Type' ] );
1008         $t->row( $_ => ref($comps->{$_}) ? 'instance' : 'class' ) for keys %$comps;
1009
1010         $class->log->debug( "Loaded components:\n" . $t->draw . "\n" );
1011     }
1012
1013     $class->setup_actions;
1014
1015     if ( $class->debug ) {
1016         my $name = $class->config->{name} || 'Application';
1017         $class->log->info("$name powered by Catalyst $Catalyst::VERSION");
1018     }
1019
1020     if ($class->config->{case_sensitive}) {
1021         $class->log->warn($class . "->config->{case_sensitive} is set.");
1022         $class->log->warn("This setting is deprecated and planned to be removed in Catalyst 5.81.");
1023     }
1024
1025     $class->setup_finalize;
1026     # Should be the last thing we do so that user things hooking
1027     # setup_finalize can log..
1028     $class->log->_flush() if $class->log->can('_flush');
1029     return 1; # Explicit return true as people have __PACKAGE__->setup as the last thing in their class. HATE.
1030 }
1031
1032 =head2 $app->setup_finalize
1033
1034 A hook to attach modifiers to. This method does not do anything except set the
1035 C<setup_finished> accessor.
1036
1037 Applying method modifiers to the C<setup> method doesn't work, because of quirky things done for plugin setup.
1038
1039 Example:
1040
1041     after setup_finalize => sub {
1042         my $app = shift;
1043
1044         ## do stuff here..
1045     };
1046
1047 =cut
1048
1049 sub setup_finalize {
1050     my ($class) = @_;
1051     $class->setup_finished(1);
1052 }
1053
1054 =head2 $c->uri_for( $path?, @args?, \%query_values? )
1055
1056 =head2 $c->uri_for( $action, \@captures?, @args?, \%query_values? )
1057
1058 Constructs an absolute L<URI> object based on the application root, the
1059 provided path, and the additional arguments and query parameters provided.
1060 When used as a string, provides a textual URI.  If you need more flexibility
1061 than this (i.e. the option to provide relative URIs etc.) see
1062 L<Catalyst::Plugin::SmartURI>.
1063
1064 If no arguments are provided, the URI for the current action is returned.
1065 To return the current action and also provide @args, use
1066 C<< $c->uri_for( $c->action, @args ) >>.
1067
1068 If the first argument is a string, it is taken as a public URI path relative
1069 to C<< $c->namespace >> (if it doesn't begin with a forward slash) or
1070 relative to the application root (if it does). It is then merged with
1071 C<< $c->request->base >>; any C<@args> are appended as additional path
1072 components; and any C<%query_values> are appended as C<?foo=bar> parameters.
1073
1074 If the first argument is a L<Catalyst::Action> it represents an action which
1075 will have its path resolved using C<< $c->dispatcher->uri_for_action >>. The
1076 optional C<\@captures> argument (an arrayref) allows passing the captured
1077 variables that are needed to fill in the paths of Chained and Regex actions;
1078 once the path is resolved, C<uri_for> continues as though a path was
1079 provided, appending any arguments or parameters and creating an absolute
1080 URI.
1081
1082 The captures for the current request can be found in
1083 C<< $c->request->captures >>, and actions can be resolved using
1084 C<< Catalyst::Controller->action_for($name) >>. If you have a private action
1085 path, use C<< $c->uri_for_action >> instead.
1086
1087   # Equivalent to $c->req->uri
1088   $c->uri_for($c->action, $c->req->captures,
1089       @{ $c->req->args }, $c->req->params);
1090
1091   # For the Foo action in the Bar controller
1092   $c->uri_for($c->controller('Bar')->action_for('Foo'));
1093
1094   # Path to a static resource
1095   $c->uri_for('/static/images/logo.png');
1096
1097 =cut
1098
1099 sub uri_for {
1100     my ( $c, $path, @args ) = @_;
1101
1102     if (blessed($path) && $path->isa('Catalyst::Controller')) {
1103         $path = $path->path_prefix;
1104         $path =~ s{/+\z}{};
1105         $path .= '/';
1106     }
1107
1108     undef($path) if (defined $path && $path eq '');
1109
1110     my $params =
1111       ( scalar @args && ref $args[$#args] eq 'HASH' ? pop @args : {} );
1112
1113     carp "uri_for called with undef argument" if grep { ! defined $_ } @args;
1114     foreach my $arg (@args) {
1115         utf8::encode($arg) if utf8::is_utf8($arg);
1116         $arg =~ s/([^$URI::uric])/$URI::Escape::escapes{$1}/go;
1117     }
1118
1119     if ( blessed($path) ) { # action object
1120         s|/|%2F|g for @args;
1121         my $captures = [ map { s|/|%2F|g; $_; }
1122                         ( scalar @args && ref $args[0] eq 'ARRAY'
1123                          ? @{ shift(@args) }
1124                          : ()) ];
1125
1126         foreach my $capture (@$captures) {
1127             utf8::encode($capture) if utf8::is_utf8($capture);
1128             $capture =~ s/([^$URI::uric])/$URI::Escape::escapes{$1}/go;
1129         }
1130
1131         my $action = $path;
1132         # ->uri_for( $action, \@captures_and_args, \%query_values? )
1133         if( !@args && $action->number_of_args ) {
1134             my $expanded_action = $c->dispatcher->expand_action( $action );
1135
1136             my $num_captures = $expanded_action->number_of_captures;
1137             unshift @args, splice @$captures, $num_captures;
1138         }
1139
1140        $path = $c->dispatcher->uri_for_action($action, $captures);
1141         if (not defined $path) {
1142             $c->log->debug(qq/Can't find uri_for action '$action' @$captures/)
1143                 if $c->debug;
1144             return undef;
1145         }
1146         $path = '/' if $path eq '';
1147     }
1148
1149     unshift(@args, $path);
1150
1151     unless (defined $path && $path =~ s!^/!!) { # in-place strip
1152         my $namespace = $c->namespace;
1153         if (defined $path) { # cheesy hack to handle path '../foo'
1154            $namespace =~ s{(?:^|/)[^/]+$}{} while $args[0] =~ s{^\.\./}{};
1155         }
1156         unshift(@args, $namespace || '');
1157     }
1158
1159     # join args with '/', or a blank string
1160     my $args = join('/', grep { defined($_) } @args);
1161     $args =~ s/\?/%3F/g; # STUPID STUPID SPECIAL CASE
1162     $args =~ s!^/+!!;
1163     my $base = $c->req->base;
1164     my $class = ref($base);
1165     $base =~ s{(?<!/)$}{/};
1166
1167     my $query = '';
1168
1169     if (my @keys = keys %$params) {
1170       # somewhat lifted from URI::_query's query_form
1171       $query = '?'.join('&', map {
1172           my $val = $params->{$_};
1173           s/([;\/?:@&=+,\$\[\]%])/$URI::Escape::escapes{$1}/go;
1174           s/ /+/g;
1175           my $key = $_;
1176           $val = '' unless defined $val;
1177           (map {
1178               my $param = "$_";
1179               utf8::encode( $param ) if utf8::is_utf8($param);
1180               # using the URI::Escape pattern here so utf8 chars survive
1181               $param =~ s/([^A-Za-z0-9\-_.!~*'() ])/$URI::Escape::escapes{$1}/go;
1182               $param =~ s/ /+/g;
1183               "${key}=$param"; } ( ref $val eq 'ARRAY' ? @$val : $val ));
1184       } @keys);
1185     }
1186
1187     my $res = bless(\"${base}${args}${query}", $class);
1188     $res;
1189 }
1190
1191 =head2 $c->uri_for_action( $path, \@captures_and_args?, @args?, \%query_values? )
1192
1193 =head2 $c->uri_for_action( $action, \@captures_and_args?, @args?, \%query_values? )
1194
1195 =over
1196
1197 =item $path
1198
1199 A private path to the Catalyst action you want to create a URI for.
1200
1201 This is a shortcut for calling C<< $c->dispatcher->get_action_by_path($path)
1202 >> and passing the resulting C<$action> and the remaining arguments to C<<
1203 $c->uri_for >>.
1204
1205 You can also pass in a Catalyst::Action object, in which case it is passed to
1206 C<< $c->uri_for >>.
1207
1208 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.
1209
1210 For example, if the action looks like:
1211
1212  package MyApp::Controller::Users;
1213
1214  sub lst : Path('the-list') {}
1215
1216 You can use:
1217
1218  $c->uri_for_action('/users/lst')
1219
1220 and it will create the URI /users/the-list.
1221
1222 =item \@captures_and_args?
1223
1224 Optional array reference of Captures (i.e. C<<CaptureArgs or $c->req->captures>)
1225 and arguments to the request. Usually used with L<Catalyst::DispatchType::Chained>
1226 to interpolate all the parameters in the URI.
1227
1228 =item @args?
1229
1230 Optional list of extra arguments - can be supplied in the
1231 C<< \@captures_and_args? >> array ref, or here - whichever is easier for your
1232 code.
1233
1234 Your action can have zero, a fixed or a variable number of args (e.g.
1235 C<< Args(1) >> for a fixed number or C<< Args() >> for a variable number)..
1236
1237 =item \%query_values?
1238
1239 Optional array reference of query parameters to append. E.g.
1240
1241   { foo => 'bar' }
1242
1243 will generate
1244
1245   /rest/of/your/uri?foo=bar
1246
1247 =back
1248
1249 =cut
1250
1251 sub uri_for_action {
1252     my ( $c, $path, @args ) = @_;
1253     my $action = blessed($path)
1254       ? $path
1255       : $c->dispatcher->get_action_by_path($path);
1256     unless (defined $action) {
1257       croak "Can't find action for path '$path'";
1258     }
1259     return $c->uri_for( $action, @args );
1260 }
1261
1262 =head2 $c->welcome_message
1263
1264 Returns the Catalyst welcome HTML page.
1265
1266 =cut
1267
1268 sub welcome_message {
1269     my $c      = shift;
1270     my $name   = $c->config->{name};
1271     my $logo   = $c->uri_for('/static/images/catalyst_logo.png');
1272     my $prefix = Catalyst::Utils::appprefix( ref $c );
1273     $c->response->content_type('text/html; charset=utf-8');
1274     return <<"EOF";
1275 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
1276     "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
1277 <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
1278     <head>
1279     <meta http-equiv="Content-Language" content="en" />
1280     <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
1281         <title>$name on Catalyst $VERSION</title>
1282         <style type="text/css">
1283             body {
1284                 color: #000;
1285                 background-color: #eee;
1286             }
1287             div#content {
1288                 width: 640px;
1289                 margin-left: auto;
1290                 margin-right: auto;
1291                 margin-top: 10px;
1292                 margin-bottom: 10px;
1293                 text-align: left;
1294                 background-color: #ccc;
1295                 border: 1px solid #aaa;
1296             }
1297             p, h1, h2 {
1298                 margin-left: 20px;
1299                 margin-right: 20px;
1300                 font-family: verdana, tahoma, sans-serif;
1301             }
1302             a {
1303                 font-family: verdana, tahoma, sans-serif;
1304             }
1305             :link, :visited {
1306                     text-decoration: none;
1307                     color: #b00;
1308                     border-bottom: 1px dotted #bbb;
1309             }
1310             :link:hover, :visited:hover {
1311                     color: #555;
1312             }
1313             div#topbar {
1314                 margin: 0px;
1315             }
1316             pre {
1317                 margin: 10px;
1318                 padding: 8px;
1319             }
1320             div#answers {
1321                 padding: 8px;
1322                 margin: 10px;
1323                 background-color: #fff;
1324                 border: 1px solid #aaa;
1325             }
1326             h1 {
1327                 font-size: 0.9em;
1328                 font-weight: normal;
1329                 text-align: center;
1330             }
1331             h2 {
1332                 font-size: 1.0em;
1333             }
1334             p {
1335                 font-size: 0.9em;
1336             }
1337             p img {
1338                 float: right;
1339                 margin-left: 10px;
1340             }
1341             span#appname {
1342                 font-weight: bold;
1343                 font-size: 1.6em;
1344             }
1345         </style>
1346     </head>
1347     <body>
1348         <div id="content">
1349             <div id="topbar">
1350                 <h1><span id="appname">$name</span> on <a href="http://catalyst.perl.org">Catalyst</a>
1351                     $VERSION</h1>
1352              </div>
1353              <div id="answers">
1354                  <p>
1355                  <img src="$logo" alt="Catalyst Logo" />
1356                  </p>
1357                  <p>Welcome to the  world of Catalyst.
1358                     This <a href="http://en.wikipedia.org/wiki/MVC">MVC</a>
1359                     framework will make web development something you had
1360                     never expected it to be: Fun, rewarding, and quick.</p>
1361                  <h2>What to do now?</h2>
1362                  <p>That really depends  on what <b>you</b> want to do.
1363                     We do, however, provide you with a few starting points.</p>
1364                  <p>If you want to jump right into web development with Catalyst
1365                     you might want to start with a tutorial.</p>
1366 <pre>perldoc <a href="https://metacpan.org/module/Catalyst::Manual::Tutorial">Catalyst::Manual::Tutorial</a></code>
1367 </pre>
1368 <p>Afterwards you can go on to check out a more complete look at our features.</p>
1369 <pre>
1370 <code>perldoc <a href="https://metacpan.org/module/Catalyst::Manual::Intro">Catalyst::Manual::Intro</a>
1371 <!-- Something else should go here, but the Catalyst::Manual link seems unhelpful -->
1372 </code></pre>
1373                  <h2>What to do next?</h2>
1374                  <p>Next it's time to write an actual application. Use the
1375                     helper scripts to generate <a href="https://metacpan.org/search?q=Catalyst%3A%3AController">controllers</a>,
1376                     <a href="https://metacpan.org/search?q=Catalyst%3A%3AModel">models</a>, and
1377                     <a href="https://metacpan.org/search?q=Catalyst%3A%3AView">views</a>;
1378                     they can save you a lot of work.</p>
1379                     <pre><code>script/${prefix}_create.pl --help</code></pre>
1380                     <p>Also, be sure to check out the vast and growing
1381                     collection of <a href="http://search.cpan.org/search?query=Catalyst">plugins for Catalyst on CPAN</a>;
1382                     you are likely to find what you need there.
1383                     </p>
1384
1385                  <h2>Need help?</h2>
1386                  <p>Catalyst has a very active community. Here are the main places to
1387                     get in touch with us.</p>
1388                  <ul>
1389                      <li>
1390                          <a href="http://dev.catalyst.perl.org">Wiki</a>
1391                      </li>
1392                      <li>
1393                          <a href="http://lists.scsys.co.uk/cgi-bin/mailman/listinfo/catalyst">Mailing-List</a>
1394                      </li>
1395                      <li>
1396                          <a href="irc://irc.perl.org/catalyst">IRC channel #catalyst on irc.perl.org</a>
1397                      </li>
1398                  </ul>
1399                  <h2>In conclusion</h2>
1400                  <p>The Catalyst team hopes you will enjoy using Catalyst as much
1401                     as we enjoyed making it. Please contact us if you have ideas
1402                     for improvement or other feedback.</p>
1403              </div>
1404          </div>
1405     </body>
1406 </html>
1407 EOF
1408 }
1409
1410 =head2 run_options
1411
1412 Contains a hash of options passed from the application script, including
1413 the original ARGV the script received, the processed values from that
1414 ARGV and any extra arguments to the script which were not processed.
1415
1416 This can be used to add custom options to your application's scripts
1417 and setup your application differently depending on the values of these
1418 options.
1419
1420 =head1 INTERNAL METHODS
1421
1422 These methods are not meant to be used by end users.
1423
1424 =head2 $c->components
1425
1426 Returns a hash of components.
1427
1428 =cut
1429
1430 sub components {
1431     my ( $class, $comps ) = @_;
1432
1433     # people create components calling this sub directly, before setup
1434     $class->setup_config unless $class->container;
1435
1436     my $container = $class->container;
1437
1438     if ( $comps ) {
1439         $container->add_component( $_ ) for keys %$comps;
1440     }
1441
1442     return $container->get_all_components($class);
1443 }
1444
1445 =head2 $c->context_class
1446
1447 Returns or sets the context class.
1448
1449 =head2 $c->counter
1450
1451 Returns a hashref containing coderefs and execution counts (needed for
1452 deep recursion detection).
1453
1454 =head2 $c->depth
1455
1456 Returns the number of actions on the current internal execution stack.
1457
1458 =head2 $c->dispatch
1459
1460 Dispatches a request to actions.
1461
1462 =cut
1463
1464 sub dispatch { my $c = shift; $c->dispatcher->dispatch( $c, @_ ) }
1465
1466 =head2 $c->dispatcher_class
1467
1468 Returns or sets the dispatcher class.
1469
1470 =head2 $c->dump_these
1471
1472 Returns a list of 2-element array references (name, structure) pairs
1473 that will be dumped on the error page in debug mode.
1474
1475 =cut
1476
1477 sub dump_these {
1478     my $c = shift;
1479     [ Request => $c->req ],
1480     [ Response => $c->res ],
1481     [ Stash => $c->stash ],
1482     [ Config => $c->config ];
1483 }
1484
1485 =head2 $c->engine_class
1486
1487 Returns or sets the engine class.
1488
1489 =head2 $c->execute( $class, $coderef )
1490
1491 Execute a coderef in given class and catch exceptions. Errors are available
1492 via $c->error.
1493
1494 =cut
1495
1496 sub execute {
1497     my ( $c, $class, $code ) = @_;
1498     $class = $c->component($class) || $class;
1499     $c->state(0);
1500
1501     if ( $c->depth >= $RECURSION ) {
1502         my $action = $code->reverse();
1503         $action = "/$action" unless $action =~ /->/;
1504         my $error = qq/Deep recursion detected calling "${action}"/;
1505         $c->log->error($error);
1506         $c->error($error);
1507         $c->state(0);
1508         return $c->state;
1509     }
1510
1511     my $stats_info = $c->_stats_start_execute( $code ) if $c->use_stats;
1512
1513     push( @{ $c->stack }, $code );
1514
1515     no warnings 'recursion';
1516     # N.B. This used to be combined, but I have seen $c get clobbered if so, and
1517     #      I have no idea how, ergo $ret (which appears to fix the issue)
1518     eval { my $ret = $code->execute( $class, $c, @{ $c->req->args } ) || 0; $c->state( $ret ) };
1519
1520     $c->_stats_finish_execute( $stats_info ) if $c->use_stats and $stats_info;
1521
1522     my $last = pop( @{ $c->stack } );
1523
1524     if ( my $error = $@ ) {
1525         if ( blessed($error) and $error->isa('Catalyst::Exception::Detach') ) {
1526             $error->rethrow if $c->depth > 1;
1527         }
1528         elsif ( blessed($error) and $error->isa('Catalyst::Exception::Go') ) {
1529             $error->rethrow if $c->depth > 0;
1530         }
1531         else {
1532             unless ( ref $error ) {
1533                 no warnings 'uninitialized';
1534                 chomp $error;
1535                 my $class = $last->class;
1536                 my $name  = $last->name;
1537                 $error = qq/Caught exception in $class->$name "$error"/;
1538             }
1539             $c->error($error);
1540         }
1541         $c->state(0);
1542     }
1543     return $c->state;
1544 }
1545
1546 sub _stats_start_execute {
1547     my ( $c, $code ) = @_;
1548     my $appclass = ref($c) || $c;
1549     return if ( ( $code->name =~ /^_.*/ )
1550         && ( !$appclass->config->{show_internal_actions} ) );
1551
1552     my $action_name = $code->reverse();
1553     $c->counter->{$action_name}++;
1554
1555     my $action = $action_name;
1556     $action = "/$action" unless $action =~ /->/;
1557
1558     # determine if the call was the result of a forward
1559     # this is done by walking up the call stack and looking for a calling
1560     # sub of Catalyst::forward before the eval
1561     my $callsub = q{};
1562     for my $index ( 2 .. 11 ) {
1563         last
1564         if ( ( caller($index) )[0] eq 'Catalyst'
1565             && ( caller($index) )[3] eq '(eval)' );
1566
1567         if ( ( caller($index) )[3] =~ /forward$/ ) {
1568             $callsub = ( caller($index) )[3];
1569             $action  = "-> $action";
1570             last;
1571         }
1572     }
1573
1574     my $uid = $action_name . $c->counter->{$action_name};
1575
1576     # is this a root-level call or a forwarded call?
1577     if ( $callsub =~ /forward$/ ) {
1578         my $parent = $c->stack->[-1];
1579
1580         # forward, locate the caller
1581         if ( defined $parent && exists $c->counter->{"$parent"} ) {
1582             $c->stats->profile(
1583                 begin  => $action,
1584                 parent => "$parent" . $c->counter->{"$parent"},
1585                 uid    => $uid,
1586             );
1587         }
1588         else {
1589
1590             # forward with no caller may come from a plugin
1591             $c->stats->profile(
1592                 begin => $action,
1593                 uid   => $uid,
1594             );
1595         }
1596     }
1597     else {
1598
1599         # root-level call
1600         $c->stats->profile(
1601             begin => $action,
1602             uid   => $uid,
1603         );
1604     }
1605     return $action;
1606
1607 }
1608
1609 sub _stats_finish_execute {
1610     my ( $c, $info ) = @_;
1611     $c->stats->profile( end => $info );
1612 }
1613
1614 =head2 $c->finalize
1615
1616 Finalizes the request.
1617
1618 =cut
1619
1620 sub finalize {
1621     my $c = shift;
1622
1623     for my $error ( @{ $c->error } ) {
1624         $c->log->error($error);
1625     }
1626
1627     # Allow engine to handle finalize flow (for POE)
1628     my $engine = $c->engine;
1629     if ( my $code = $engine->can('finalize') ) {
1630         $engine->$code($c);
1631     }
1632     else {
1633
1634         $c->finalize_uploads;
1635
1636         # Error
1637         if ( $#{ $c->error } >= 0 ) {
1638             $c->finalize_error;
1639         }
1640
1641         $c->finalize_headers unless $c->response->finalized_headers;
1642
1643         # HEAD request
1644         if ( $c->request->method eq 'HEAD' ) {
1645             $c->response->body('');
1646         }
1647
1648         $c->finalize_body;
1649     }
1650
1651     $c->log_response;
1652
1653     if ($c->use_stats) {
1654         my $elapsed = sprintf '%f', $c->stats->elapsed;
1655         my $av = $elapsed == 0 ? '??' : sprintf '%.3f', 1 / $elapsed;
1656         $c->log->info(
1657             "Request took ${elapsed}s ($av/s)\n" . $c->stats->report . "\n" );
1658     }
1659
1660     return $c->response->status;
1661 }
1662
1663 =head2 $c->finalize_body
1664
1665 Finalizes body.
1666
1667 =cut
1668
1669 sub finalize_body { my $c = shift; $c->engine->finalize_body( $c, @_ ) }
1670
1671 =head2 $c->finalize_cookies
1672
1673 Finalizes cookies.
1674
1675 =cut
1676
1677 sub finalize_cookies { my $c = shift; $c->engine->finalize_cookies( $c, @_ ) }
1678
1679 =head2 $c->finalize_error
1680
1681 Finalizes error.
1682
1683 =cut
1684
1685 sub finalize_error { my $c = shift; $c->engine->finalize_error( $c, @_ ) }
1686
1687 =head2 $c->finalize_headers
1688
1689 Finalizes headers.
1690
1691 =cut
1692
1693 sub finalize_headers {
1694     my $c = shift;
1695
1696     my $response = $c->response; #accessor calls can add up?
1697
1698     # Check if we already finalized headers
1699     return if $response->finalized_headers;
1700
1701     # Handle redirects
1702     if ( my $location = $response->redirect ) {
1703         $c->log->debug(qq/Redirecting to "$location"/) if $c->debug;
1704         $response->header( Location => $location );
1705
1706         if ( !$response->has_body ) {
1707             # Add a default body if none is already present
1708             $response->body(<<"EOF");
1709 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
1710 <html xmlns="http://www.w3.org/1999/xhtml"> 
1711   <head>
1712     <title>Moved</title>
1713   </head>
1714   <body>
1715      <p>This item has moved <a href="$location">here</a>.</p>
1716   </body>
1717 </html>
1718 EOF
1719             $response->content_type('text/html; charset=utf-8');
1720         }
1721     }
1722
1723     # Content-Length
1724     if ( defined $response->body && length $response->body && !$response->content_length ) {
1725
1726         # get the length from a filehandle
1727         if ( blessed( $response->body ) && $response->body->can('read') || ref( $response->body ) eq 'GLOB' )
1728         {
1729             my $size = -s $response->body;
1730             if ( $size ) {
1731                 $response->content_length( $size );
1732             }
1733             else {
1734                 $c->log->warn('Serving filehandle without a content-length');
1735             }
1736         }
1737         else {
1738             # everything should be bytes at this point, but just in case
1739             $response->content_length( length( $response->body ) );
1740         }
1741     }
1742
1743     # Errors
1744     if ( $response->status =~ /^(1\d\d|[23]04)$/ ) {
1745         $response->headers->remove_header("Content-Length");
1746         $response->body('');
1747     }
1748
1749     $c->finalize_cookies;
1750
1751     $c->response->finalize_headers();
1752
1753     # Done
1754     $response->finalized_headers(1);
1755 }
1756
1757 =head2 $c->finalize_output
1758
1759 An alias for finalize_body.
1760
1761 =head2 $c->finalize_read
1762
1763 Finalizes the input after reading is complete.
1764
1765 =cut
1766
1767 sub finalize_read { my $c = shift; $c->engine->finalize_read( $c, @_ ) }
1768
1769 =head2 $c->finalize_uploads
1770
1771 Finalizes uploads. Cleans up any temporary files.
1772
1773 =cut
1774
1775 sub finalize_uploads { my $c = shift; $c->engine->finalize_uploads( $c, @_ ) }
1776
1777 =head2 $c->get_action( $action, $namespace )
1778
1779 Gets an action in a given namespace.
1780
1781 =cut
1782
1783 sub get_action { my $c = shift; $c->dispatcher->get_action(@_) }
1784
1785 =head2 $c->get_actions( $action, $namespace )
1786
1787 Gets all actions of a given name in a namespace and all parent
1788 namespaces.
1789
1790 =cut
1791
1792 sub get_actions { my $c = shift; $c->dispatcher->get_actions( $c, @_ ) }
1793
1794 =head2 $app->handle_request( @arguments )
1795
1796 Called to handle each HTTP request.
1797
1798 =cut
1799
1800 sub handle_request {
1801     my ( $class, @arguments ) = @_;
1802
1803     # Always expect worst case!
1804     my $status = -1;
1805     try {
1806         if ($class->debug) {
1807             my $secs = time - $START || 1;
1808             my $av = sprintf '%.3f', $COUNT / $secs;
1809             my $time = localtime time;
1810             $class->log->info("*** Request $COUNT ($av/s) [$$] [$time] ***");
1811         }
1812
1813         my $c = $class->prepare(@arguments);
1814         $c->dispatch;
1815         $status = $c->finalize;
1816     }
1817     catch {
1818         chomp(my $error = $_);
1819         $class->log->error(qq/Caught exception in engine "$error"/);
1820     };
1821
1822     $COUNT++;
1823
1824     if(my $coderef = $class->log->can('_flush')){
1825         $class->log->$coderef();
1826     }
1827     return $status;
1828 }
1829
1830 =head2 $class->prepare( @arguments )
1831
1832 Creates a Catalyst context from an engine-specific request (Apache, CGI,
1833 etc.).
1834
1835 =cut
1836
1837 has _uploadtmp => (
1838     is => 'ro',
1839     predicate => '_has_uploadtmp',
1840 );
1841
1842 sub prepare {
1843     my ( $class, @arguments ) = @_;
1844
1845     # XXX
1846     # After the app/ctxt split, this should become an attribute based on something passed
1847     # into the application.
1848     $class->context_class( ref $class || $class ) unless $class->context_class;
1849
1850     my $uploadtmp = $class->config->{uploadtmp};
1851     my $c = $class->context_class->new({ $uploadtmp ? (_uploadtmp => $uploadtmp) : ()});
1852
1853     $c->response->_context($c);
1854
1855     #surely this is not the most efficient way to do things...
1856     $c->stats($class->stats_class->new)->enable($c->use_stats);
1857     if ( $c->debug || $c->config->{enable_catalyst_header} ) {
1858         $c->res->headers->header( 'X-Catalyst' => $Catalyst::VERSION );
1859     }
1860
1861     try {
1862         # Allow engine to direct the prepare flow (for POE)
1863         if ( my $prepare = $c->engine->can('prepare') ) {
1864             $c->engine->$prepare( $c, @arguments );
1865         }
1866         else {
1867             $c->prepare_request(@arguments);
1868             $c->prepare_connection;
1869             $c->prepare_query_parameters;
1870             $c->prepare_headers; # Just hooks, no longer needed - they just
1871             $c->prepare_cookies; # cause the lazy attribute on req to build
1872             $c->prepare_path;
1873
1874             # Prepare the body for reading, either by prepare_body
1875             # or the user, if they are using $c->read
1876             $c->prepare_read;
1877
1878             # Parse the body unless the user wants it on-demand
1879             unless ( ref($c)->config->{parse_on_demand} ) {
1880                 $c->prepare_body;
1881             }
1882         }
1883         $c->prepare_action;
1884     }
1885     # VERY ugly and probably shouldn't rely on ->finalize actually working
1886     catch {
1887         # failed prepare is always due to an invalid request, right?
1888         $c->response->status(400);
1889         $c->response->content_type('text/plain');
1890         $c->response->body('Bad Request');
1891         # Note we call finalize and then die here, which escapes
1892         # finalize being called in the enclosing block..
1893         # It in fact couldn't be called, as we don't return $c..
1894         # This is a mess - but I'm unsure you can fix this without
1895         # breaking compat for people doing crazy things (we should set
1896         # the 400 and just return the ctx here IMO, letting finalize get called
1897         # above...
1898         $c->finalize;
1899         die $_;
1900     };
1901
1902     $c->log_request;
1903
1904     return $c;
1905 }
1906
1907 =head2 $c->prepare_action
1908
1909 Prepares action. See L<Catalyst::Dispatcher>.
1910
1911 =cut
1912
1913 sub prepare_action { my $c = shift; $c->dispatcher->prepare_action( $c, @_ ) }
1914
1915 =head2 $c->prepare_body
1916
1917 Prepares message body.
1918
1919 =cut
1920
1921 sub prepare_body {
1922     my $c = shift;
1923
1924     return if $c->request->_has_body;
1925
1926     # Initialize on-demand data
1927     $c->engine->prepare_body( $c, @_ );
1928     $c->prepare_parameters;
1929     $c->prepare_uploads;
1930 }
1931
1932 =head2 $c->prepare_body_chunk( $chunk )
1933
1934 Prepares a chunk of data before sending it to L<HTTP::Body>.
1935
1936 See L<Catalyst::Engine>.
1937
1938 =cut
1939
1940 sub prepare_body_chunk {
1941     my $c = shift;
1942     $c->engine->prepare_body_chunk( $c, @_ );
1943 }
1944
1945 =head2 $c->prepare_body_parameters
1946
1947 Prepares body parameters.
1948
1949 =cut
1950
1951 sub prepare_body_parameters {
1952     my $c = shift;
1953     $c->engine->prepare_body_parameters( $c, @_ );
1954 }
1955
1956 =head2 $c->prepare_connection
1957
1958 Prepares connection.
1959
1960 =cut
1961
1962 sub prepare_connection {
1963     my $c = shift;
1964     # XXX - This is called on the engine (not the request) to maintain
1965     #       Engine::PSGI back compat.
1966     $c->engine->prepare_connection($c);
1967 }
1968
1969 =head2 $c->prepare_cookies
1970
1971 Prepares cookies by ensuring that the attribute on the request
1972 object has been built.
1973
1974 =cut
1975
1976 sub prepare_cookies { my $c = shift; $c->request->cookies }
1977
1978 =head2 $c->prepare_headers
1979
1980 Prepares request headers by ensuring that the attribute on the request
1981 object has been built.
1982
1983 =cut
1984
1985 sub prepare_headers { my $c = shift; $c->request->headers }
1986
1987 =head2 $c->prepare_parameters
1988
1989 Prepares parameters.
1990
1991 =cut
1992
1993 sub prepare_parameters {
1994     my $c = shift;
1995     $c->prepare_body_parameters;
1996     $c->engine->prepare_parameters( $c, @_ );
1997 }
1998
1999 =head2 $c->prepare_path
2000
2001 Prepares path and base.
2002
2003 =cut
2004
2005 sub prepare_path { my $c = shift; $c->engine->prepare_path( $c, @_ ) }
2006
2007 =head2 $c->prepare_query_parameters
2008
2009 Prepares query parameters.
2010
2011 =cut
2012
2013 sub prepare_query_parameters {
2014     my $c = shift;
2015
2016     $c->engine->prepare_query_parameters( $c, @_ );
2017 }
2018
2019 =head2 $c->log_request
2020
2021 Writes information about the request to the debug logs.  This includes:
2022
2023 =over 4
2024
2025 =item * Request method, path, and remote IP address
2026
2027 =item * Query keywords (see L<Catalyst::Request/query_keywords>)
2028
2029 =item * Request parameters
2030
2031 =item * File uploads
2032
2033 =back
2034
2035 =cut
2036
2037 sub log_request {
2038     my $c = shift;
2039
2040     return unless $c->debug;
2041
2042     my($dump) = grep {$_->[0] eq 'Request' } $c->dump_these;
2043     my $request = $dump->[1];
2044
2045     my ( $method, $path, $address ) = ( $request->method, $request->path, $request->address );
2046     $method ||= '';
2047     $path = '/' unless length $path;
2048     $address ||= '';
2049     $c->log->debug(qq/"$method" request for "$path" from "$address"/);
2050
2051     $c->log_request_headers($request->headers);
2052
2053     if ( my $keywords = $request->query_keywords ) {
2054         $c->log->debug("Query keywords are: $keywords");
2055     }
2056
2057     $c->log_request_parameters( query => $request->query_parameters, $request->_has_body ? (body => $request->body_parameters) : () );
2058
2059     $c->log_request_uploads($request);
2060 }
2061
2062 =head2 $c->log_response
2063
2064 Writes information about the response to the debug logs by calling
2065 C<< $c->log_response_status_line >> and C<< $c->log_response_headers >>.
2066
2067 =cut
2068
2069 sub log_response {
2070     my $c = shift;
2071
2072     return unless $c->debug;
2073
2074     my($dump) = grep {$_->[0] eq 'Response' } $c->dump_these;
2075     my $response = $dump->[1];
2076
2077     $c->log_response_status_line($response);
2078     $c->log_response_headers($response->headers);
2079 }
2080
2081 =head2 $c->log_response_status_line($response)
2082
2083 Writes one line of information about the response to the debug logs.  This includes:
2084
2085 =over 4
2086
2087 =item * Response status code
2088
2089 =item * Content-Type header (if present)
2090
2091 =item * Content-Length header (if present)
2092
2093 =back
2094
2095 =cut
2096
2097 sub log_response_status_line {
2098     my ($c, $response) = @_;
2099
2100     $c->log->debug(
2101         sprintf(
2102             'Response Code: %s; Content-Type: %s; Content-Length: %s',
2103             $response->status                            || 'unknown',
2104             $response->headers->header('Content-Type')   || 'unknown',
2105             $response->headers->header('Content-Length') || 'unknown'
2106         )
2107     );
2108 }
2109
2110 =head2 $c->log_response_headers($headers);
2111
2112 Hook method which can be wrapped by plugins to log the response headers.
2113 No-op in the default implementation.
2114
2115 =cut
2116
2117 sub log_response_headers {}
2118
2119 =head2 $c->log_request_parameters( query => {}, body => {} )
2120
2121 Logs request parameters to debug logs
2122
2123 =cut
2124
2125 sub log_request_parameters {
2126     my $c          = shift;
2127     my %all_params = @_;
2128
2129     return unless $c->debug;
2130
2131     my $column_width = Catalyst::Utils::term_width() - 44;
2132     foreach my $type (qw(query body)) {
2133         my $params = $all_params{$type};
2134         next if ! keys %$params;
2135         my $t = Text::SimpleTable->new( [ 35, 'Parameter' ], [ $column_width, 'Value' ] );
2136         for my $key ( sort keys %$params ) {
2137             my $param = $params->{$key};
2138             my $value = defined($param) ? $param : '';
2139             $t->row( $key, ref $value eq 'ARRAY' ? ( join ', ', @$value ) : $value );
2140         }
2141         $c->log->debug( ucfirst($type) . " Parameters are:\n" . $t->draw );
2142     }
2143 }
2144
2145 =head2 $c->log_request_uploads
2146
2147 Logs file uploads included in the request to the debug logs.
2148 The parameter name, filename, file type, and file size are all included in
2149 the debug logs.
2150
2151 =cut
2152
2153 sub log_request_uploads {
2154     my $c = shift;
2155     my $request = shift;
2156     return unless $c->debug;
2157     my $uploads = $request->uploads;
2158     if ( keys %$uploads ) {
2159         my $t = Text::SimpleTable->new(
2160             [ 12, 'Parameter' ],
2161             [ 26, 'Filename' ],
2162             [ 18, 'Type' ],
2163             [ 9,  'Size' ]
2164         );
2165         for my $key ( sort keys %$uploads ) {
2166             my $upload = $uploads->{$key};
2167             for my $u ( ref $upload eq 'ARRAY' ? @{$upload} : ($upload) ) {
2168                 $t->row( $key, $u->filename, $u->type, $u->size );
2169             }
2170         }
2171         $c->log->debug( "File Uploads are:\n" . $t->draw );
2172     }
2173 }
2174
2175 =head2 $c->log_request_headers($headers);
2176
2177 Hook method which can be wrapped by plugins to log the request headers.
2178 No-op in the default implementation.
2179
2180 =cut
2181
2182 sub log_request_headers {}
2183
2184 =head2 $c->log_headers($type => $headers)
2185
2186 Logs L<HTTP::Headers> (either request or response) to the debug logs.
2187
2188 =cut
2189
2190 sub log_headers {
2191     my $c       = shift;
2192     my $type    = shift;
2193     my $headers = shift;    # an HTTP::Headers instance
2194
2195     return unless $c->debug;
2196
2197     my $column_width = Catalyst::Utils::term_width() - 28;
2198     my $t = Text::SimpleTable->new( [ 15, 'Header Name' ], [ $column_width, 'Value' ] );
2199     $headers->scan(
2200         sub {
2201             my ( $name, $value ) = @_;
2202             $t->row( $name, $value );
2203         }
2204     );
2205     $c->log->debug( ucfirst($type) . " Headers:\n" . $t->draw );
2206 }
2207
2208
2209 =head2 $c->prepare_read
2210
2211 Prepares the input for reading.
2212
2213 =cut
2214
2215 sub prepare_read { my $c = shift; $c->engine->prepare_read( $c, @_ ) }
2216
2217 =head2 $c->prepare_request
2218
2219 Prepares the engine request.
2220
2221 =cut
2222
2223 sub prepare_request { my $c = shift; $c->engine->prepare_request( $c, @_ ) }
2224
2225 =head2 $c->prepare_uploads
2226
2227 Prepares uploads.
2228
2229 =cut
2230
2231 sub prepare_uploads {
2232     my $c = shift;
2233
2234     $c->engine->prepare_uploads( $c, @_ );
2235 }
2236
2237 =head2 $c->prepare_write
2238
2239 Prepares the output for writing.
2240
2241 =cut
2242
2243 sub prepare_write { my $c = shift; $c->engine->prepare_write( $c, @_ ) }
2244
2245 =head2 $c->request_class
2246
2247 Returns or sets the request class. Defaults to L<Catalyst::Request>.
2248
2249 =head2 $c->response_class
2250
2251 Returns or sets the response class. Defaults to L<Catalyst::Response>.
2252
2253 =head2 $c->read( [$maxlength] )
2254
2255 Reads a chunk of data from the request body. This method is designed to
2256 be used in a while loop, reading C<$maxlength> bytes on every call.
2257 C<$maxlength> defaults to the size of the request if not specified.
2258
2259 You have to set C<< MyApp->config(parse_on_demand => 1) >> to use this
2260 directly.
2261
2262 Warning: If you use read(), Catalyst will not process the body,
2263 so you will not be able to access POST parameters or file uploads via
2264 $c->request.  You must handle all body parsing yourself.
2265
2266 =cut
2267
2268 sub read { my $c = shift; return $c->request->read( @_ ) }
2269
2270 =head2 $c->run
2271
2272 Starts the engine.
2273
2274 =cut
2275
2276 sub run {
2277   my $app = shift;
2278   $app->_make_immutable_if_needed;
2279   $app->engine_loader->needs_psgi_engine_compat_hack ?
2280     $app->engine->run($app, @_) :
2281       $app->engine->run( $app, $app->_finalized_psgi_app, @_ );
2282 }
2283
2284 sub _make_immutable_if_needed {
2285     my $class = shift;
2286     my $meta = Class::MOP::get_metaclass_by_name($class);
2287     my $isa_ca = $class->isa('Class::Accessor::Fast') || $class->isa('Class::Accessor');
2288     if (
2289         $meta->is_immutable
2290         && ! { $meta->immutable_options }->{replace_constructor}
2291         && $isa_ca
2292     ) {
2293         warn("You made your application class ($class) immutable, "
2294             . "but did not inline the\nconstructor. "
2295             . "This will break catalyst, as your app \@ISA "
2296             . "Class::Accessor(::Fast)?\nPlease pass "
2297             . "(replace_constructor => 1)\nwhen making your class immutable.\n");
2298     }
2299     unless ($meta->is_immutable) {
2300         # XXX - FIXME warning here as you should make your app immutable yourself.
2301         $meta->make_immutable(
2302             replace_constructor => 1,
2303         );
2304     }
2305 }
2306
2307 =head2 $c->set_action( $action, $code, $namespace, $attrs )
2308
2309 Sets an action in a given namespace.
2310
2311 =cut
2312
2313 sub set_action { my $c = shift; $c->dispatcher->set_action( $c, @_ ) }
2314
2315 =head2 $c->setup_actions($component)
2316
2317 Sets up actions for a component.
2318
2319 =cut
2320
2321 sub setup_actions { my $c = shift; $c->dispatcher->setup_actions( $c, @_ ) }
2322
2323 =head2 $c->setup_config
2324
2325 =cut
2326
2327 sub setup_config {
2328     my $class = shift;
2329
2330     my %args = %{ $class->config || {} };
2331
2332     my $container_class;
2333
2334     if ( exists $args{container_class} ) {
2335         $container_class = delete $args{container_class};
2336         Class::MOP::load_class($container_class);
2337     }
2338     else {
2339         $container_class = Class::MOP::load_first_existing_class("${class}::Container", 'Catalyst::IOC::Container');
2340     }
2341
2342     my $container = $container_class->new( %args, name => $class );
2343     $class->container($container);
2344
2345     my $config = $container->resolve( service => 'config' );
2346     $class->config($config);
2347     $class->finalize_config; # back-compat
2348 }
2349
2350 =head2 $c->finalize_config
2351
2352 =cut
2353
2354 sub finalize_config { }
2355
2356 =head2 $c->setup_components
2357
2358 This method is called internally to set up the application's components.
2359
2360 It finds modules by calling the L<locate_components> method, expands them to
2361 package names with the $container->expand_component_module method, and then
2362 installs each component into the application.
2363
2364 The C<setup_components> config option is passed to both of the above methods.
2365
2366 =cut
2367
2368 sub setup_components { shift->container->setup_components }
2369
2370 =head2 locate_components
2371
2372 =cut
2373
2374 sub locate_components {
2375     my $class = shift;
2376
2377     $class->log->warn('The locate_components method has been deprecated.');
2378     $class->log->warn('Please read Catalyst::IOC::Container documentation to');
2379     $class->log->warn('update your application.');
2380
2381     # XXX think about ditching this sort entirely
2382     return sort { length $a <=> length $b }
2383         @{ $class->container->resolve( service => 'locate_components' ) };
2384 }
2385
2386 =head2 $c->setup_dispatcher
2387
2388 Sets up dispatcher.
2389
2390 =cut
2391
2392 sub setup_dispatcher {
2393     my ( $class, $dispatcher ) = @_;
2394
2395     if ($dispatcher) {
2396         $dispatcher = 'Catalyst::Dispatcher::' . $dispatcher;
2397     }
2398
2399     if ( my $env = Catalyst::Utils::env_value( $class, 'DISPATCHER' ) ) {
2400         $dispatcher = 'Catalyst::Dispatcher::' . $env;
2401     }
2402
2403     unless ($dispatcher) {
2404         $dispatcher = $class->dispatcher_class;
2405     }
2406
2407     Class::MOP::load_class($dispatcher);
2408
2409     # dispatcher instance
2410     $class->dispatcher( $dispatcher->new );
2411 }
2412
2413 =head2 $c->setup_engine
2414
2415 Sets up engine.
2416
2417 =cut
2418
2419 sub engine_class {
2420     my ($class, $requested_engine) = @_;
2421
2422     if (!$class->engine_loader || $requested_engine) {
2423         $class->engine_loader(
2424             Catalyst::EngineLoader->new({
2425                 application_name => $class,
2426                 (defined $requested_engine
2427                      ? (catalyst_engine_class => $requested_engine) : ()),
2428             }),
2429         );
2430     }
2431
2432     $class->engine_loader->catalyst_engine_class;
2433 }
2434
2435 sub setup_engine {
2436     my ($class, $requested_engine) = @_;
2437
2438     my $engine = do {
2439         my $loader = $class->engine_loader;
2440
2441         if (!$loader || $requested_engine) {
2442             $loader = Catalyst::EngineLoader->new({
2443                 application_name => $class,
2444                 (defined $requested_engine
2445                      ? (requested_engine => $requested_engine) : ()),
2446             }),
2447
2448             $class->engine_loader($loader);
2449         }
2450
2451         $loader->catalyst_engine_class;
2452     };
2453
2454     # Don't really setup_engine -- see _setup_psgi_app for explanation.
2455     return if $class->loading_psgi_file;
2456
2457     Class::MOP::load_class($engine);
2458
2459     if ($ENV{MOD_PERL}) {
2460         my $apache = $class->engine_loader->auto;
2461
2462         my $meta = find_meta($class);
2463         my $was_immutable = $meta->is_immutable;
2464         my %immutable_options = $meta->immutable_options;
2465         $meta->make_mutable if $was_immutable;
2466
2467         $meta->add_method(handler => sub {
2468             my $r = shift;
2469             my $psgi_app = $class->_finalized_psgi_app;
2470             $apache->call_app($r, $psgi_app);
2471         });
2472
2473         $meta->make_immutable(%immutable_options) if $was_immutable;
2474     }
2475
2476     $class->engine( $engine->new );
2477
2478     return;
2479 }
2480
2481 sub _finalized_psgi_app {
2482     my ($app) = @_;
2483
2484     unless ($app->_psgi_app) {
2485         my $psgi_app = $app->_setup_psgi_app;
2486         $app->_psgi_app($psgi_app);
2487     }
2488
2489     return $app->_psgi_app;
2490 }
2491
2492 sub _setup_psgi_app {
2493     my ($app) = @_;
2494
2495     for my $home (Path::Class::Dir->new($app->config->{home})) {
2496         my $psgi_file = $home->file(
2497             Catalyst::Utils::appprefix($app) . '.psgi',
2498         );
2499
2500         next unless -e $psgi_file;
2501
2502         # If $psgi_file calls ->setup_engine, it's doing so to load
2503         # Catalyst::Engine::PSGI. But if it does that, we're only going to
2504         # throw away the loaded PSGI-app and load the 5.9 Catalyst::Engine
2505         # anyway. So set a flag (ick) that tells setup_engine not to populate
2506         # $c->engine or do any other things we might regret.
2507
2508         $app->loading_psgi_file(1);
2509         my $psgi_app = Plack::Util::load_psgi($psgi_file);
2510         $app->loading_psgi_file(0);
2511
2512         return $psgi_app
2513             unless $app->engine_loader->needs_psgi_engine_compat_hack;
2514
2515         warn <<"EOW";
2516 Found a legacy Catalyst::Engine::PSGI .psgi file at ${psgi_file}.
2517
2518 Its content has been ignored. Please consult the Catalyst::Upgrading
2519 documentation on how to upgrade from Catalyst::Engine::PSGI.
2520 EOW
2521     }
2522
2523     return $app->apply_default_middlewares($app->psgi_app);
2524 }
2525
2526 =head2 $c->apply_default_middlewares
2527
2528 Adds the following L<Plack> middlewares to your application, since they are
2529 useful and commonly needed:
2530
2531 L<Plack::Middleware::ReverseProxy>, (conditionally added based on the status
2532 of your $ENV{REMOTE_ADDR}, and can be forced on with C<using_frontend_proxy>
2533 or forced off with C<ignore_frontend_proxy>), L<Plack::Middleware::LighttpdScriptNameFix>
2534 (if you are using Lighttpd), L<Plack::Middleware::IIS6ScriptNameFix> (always
2535 applied since this middleware is smart enough to conditionally apply itself).
2536
2537 Additionally if we detect we are using Nginx, we add a bit of custom middleware
2538 to solve some problems with the way that server handles $ENV{PATH_INFO} and
2539 $ENV{SCRIPT_NAME}
2540
2541 =cut
2542
2543
2544 sub apply_default_middlewares {
2545     my ($app, $psgi_app) = @_;
2546
2547     $psgi_app = Plack::Middleware::Conditional->wrap(
2548         $psgi_app,
2549         builder   => sub { Plack::Middleware::ReverseProxy->wrap($_[0]) },
2550         condition => sub {
2551             my ($env) = @_;
2552             return if $app->config->{ignore_frontend_proxy};
2553             return $env->{REMOTE_ADDR} eq '127.0.0.1'
2554                 || $app->config->{using_frontend_proxy};
2555         },
2556     );
2557
2558     # If we're running under Lighttpd, swap PATH_INFO and SCRIPT_NAME
2559     # http://lists.scsys.co.uk/pipermail/catalyst/2006-June/008361.html
2560     $psgi_app = Plack::Middleware::Conditional->wrap(
2561         $psgi_app,
2562         builder   => sub { Plack::Middleware::LighttpdScriptNameFix->wrap($_[0]) },
2563         condition => sub {
2564             my ($env) = @_;
2565             return unless $env->{SERVER_SOFTWARE} && $env->{SERVER_SOFTWARE} =~ m!lighttpd[-/]1\.(\d+\.\d+)!;
2566             return unless $1 < 4.23;
2567             1;
2568         },
2569     );
2570
2571     # we're applying this unconditionally as the middleware itself already makes
2572     # sure it doesn't fuck things up if it's not running under one of the right
2573     # IIS versions
2574     $psgi_app = Plack::Middleware::IIS6ScriptNameFix->wrap($psgi_app);
2575
2576     return $psgi_app;
2577 }
2578
2579 =head2 $c->psgi_app
2580
2581 Returns a PSGI application code reference for the catalyst application
2582 C<$c>. This is the bare application without any middlewares
2583 applied. C<${myapp}.psgi> is not taken into account.
2584
2585 This is what you want to be using to retrieve the PSGI application code
2586 reference of your Catalyst application for use in F<.psgi> files.
2587
2588 =cut
2589
2590 sub psgi_app {
2591     my ($app) = @_;
2592     return $app->engine->build_psgi_app($app);
2593 }
2594
2595 =head2 $c->setup_home
2596
2597 Sets up the home directory.
2598
2599 =cut
2600
2601 sub setup_home {
2602     my ( $class, $home ) = @_;
2603
2604     if ( my $env = Catalyst::Utils::env_value( $class, 'HOME' ) ) {
2605         $home = $env;
2606     }
2607
2608     $home ||= Catalyst::Utils::home($class);
2609
2610     if ($home) {
2611         #I remember recently being scolded for assigning config values like this
2612         $class->config->{home} ||= $home;
2613         $class->config->{root} ||= Path::Class::Dir->new($home)->subdir('root');
2614     }
2615 }
2616
2617 =head2 $c->setup_log
2618
2619 Sets up log by instantiating a L<Catalyst::Log|Catalyst::Log> object and
2620 passing it to C<log()>. Pass in a comma-delimited list of levels to set the
2621 log to.
2622
2623 This method also installs a C<debug> method that returns a true value into the
2624 catalyst subclass if the "debug" level is passed in the comma-delimited list,
2625 or if the C<$CATALYST_DEBUG> environment variable is set to a true value.
2626
2627 Note that if the log has already been setup, by either a previous call to
2628 C<setup_log> or by a call such as C<< __PACKAGE__->log( MyLogger->new ) >>,
2629 that this method won't actually set up the log object.
2630
2631 =cut
2632
2633 sub setup_log {
2634     my ( $class, $levels ) = @_;
2635
2636     $levels ||= '';
2637     $levels =~ s/^\s+//;
2638     $levels =~ s/\s+$//;
2639     my %levels = map { $_ => 1 } split /\s*,\s*/, $levels;
2640
2641     my $env_debug = Catalyst::Utils::env_value( $class, 'DEBUG' );
2642     if ( defined $env_debug ) {
2643         $levels{debug} = 1 if $env_debug; # Ugly!
2644         delete($levels{debug}) unless $env_debug;
2645     }
2646
2647     unless ( $class->log ) {
2648         $class->log( Catalyst::Log->new(keys %levels) );
2649     }
2650
2651     if ( $levels{debug} ) {
2652         Class::MOP::get_metaclass_by_name($class)->add_method('debug' => sub { 1 });
2653         $class->log->debug('Debug messages enabled');
2654     }
2655 }
2656
2657 =head2 $c->setup_plugins
2658
2659 Sets up plugins.
2660
2661 =cut
2662
2663 =head2 $c->setup_stats
2664
2665 Sets up timing statistics class.
2666
2667 =cut
2668
2669 sub setup_stats {
2670     my ( $class, $stats ) = @_;
2671
2672     Catalyst::Utils::ensure_class_loaded($class->stats_class);
2673
2674     my $env = Catalyst::Utils::env_value( $class, 'STATS' );
2675     if ( defined($env) ? $env : ($stats || $class->debug ) ) {
2676         Class::MOP::get_metaclass_by_name($class)->add_method('use_stats' => sub { 1 });
2677         $class->log->debug('Statistics enabled');
2678     }
2679 }
2680
2681
2682 =head2 $c->registered_plugins
2683
2684 Returns a sorted list of the plugins which have either been stated in the
2685 import list.
2686
2687 If passed a given plugin name, it will report a boolean value indicating
2688 whether or not that plugin is loaded.  A fully qualified name is required if
2689 the plugin name does not begin with C<Catalyst::Plugin::>.
2690
2691  if ($c->registered_plugins('Some::Plugin')) {
2692      ...
2693  }
2694
2695 =cut
2696
2697 {
2698
2699     sub registered_plugins {
2700         my $proto = shift;
2701         return sort keys %{ $proto->_plugins } unless @_;
2702         my $plugin = shift;
2703         return 1 if exists $proto->_plugins->{$plugin};
2704         return exists $proto->_plugins->{"Catalyst::Plugin::$plugin"};
2705     }
2706
2707     sub _register_plugin {
2708         my ( $proto, $plugin, $instant ) = @_;
2709         my $class = ref $proto || $proto;
2710
2711         Class::MOP::load_class( $plugin );
2712         $class->log->warn( "$plugin inherits from 'Catalyst::Component' - this is deprecated and will not work in 5.81" )
2713             if $plugin->isa( 'Catalyst::Component' );
2714         my $plugin_meta = Moose::Meta::Class->create($plugin);
2715         if (!$plugin_meta->has_method('new')
2716             && ( $plugin->isa('Class::Accessor::Fast') || $plugin->isa('Class::Accessor') ) ) {
2717             $plugin_meta->add_method('new', Moose::Object->meta->get_method('new'))
2718         }
2719         if (!$instant && !$proto->_plugins->{$plugin}) {
2720             my $meta = Class::MOP::get_metaclass_by_name($class);
2721             $meta->superclasses($plugin, $meta->superclasses);
2722         }
2723         $proto->_plugins->{$plugin} = 1;
2724         return $class;
2725     }
2726
2727     sub setup_plugins {
2728         my ( $class, $plugins ) = @_;
2729
2730         $class->_plugins( {} ) unless $class->_plugins;
2731         $plugins = Data::OptList::mkopt($plugins || []);
2732
2733         my @plugins = map {
2734             [ Catalyst::Utils::resolve_namespace(
2735                   $class . '::Plugin',
2736                   'Catalyst::Plugin', $_->[0]
2737               ),
2738               $_->[1],
2739             ]
2740          } @{ $plugins };
2741
2742         for my $plugin ( reverse @plugins ) {
2743             Class::MOP::load_class($plugin->[0], $plugin->[1]);
2744             my $meta = find_meta($plugin->[0]);
2745             next if $meta && $meta->isa('Moose::Meta::Role');
2746
2747             $class->_register_plugin($plugin->[0]);
2748         }
2749
2750         my @roles =
2751             map  { $_->[0]->name, $_->[1] }
2752             grep { blessed($_->[0]) && $_->[0]->isa('Moose::Meta::Role') }
2753             map  { [find_meta($_->[0]), $_->[1]] }
2754             @plugins;
2755
2756         Moose::Util::apply_all_roles(
2757             $class => @roles
2758         ) if @roles;
2759     }
2760 }
2761
2762 =head2 $c->stack
2763
2764 Returns an arrayref of the internal execution stack (actions that are
2765 currently executing).
2766
2767 =head2 $c->stats
2768
2769 Returns the current timing statistics object. By default Catalyst uses
2770 L<Catalyst::Stats|Catalyst::Stats>, but can be set otherwise with
2771 L<< stats_class|/"$c->stats_class" >>.
2772
2773 Even if L<< -Stats|/"-Stats" >> is not enabled, the stats object is still
2774 available. By enabling it with C< $c->stats->enabled(1) >, it can be used to
2775 profile explicitly, although MyApp.pm still won't profile nor output anything
2776 by itself.
2777
2778 =head2 $c->stats_class
2779
2780 Returns or sets the stats (timing statistics) class. L<Catalyst::Stats|Catalyst::Stats> is used by default.
2781
2782 =head2 $c->use_stats
2783
2784 Returns 1 when L<< stats collection|/"-Stats" >> is enabled.
2785
2786 Note that this is a static method, not an accessor and should be overridden
2787 by declaring C<sub use_stats { 1 }> in your MyApp.pm, not by calling C<< $c->use_stats(1) >>.
2788
2789 =cut
2790
2791 sub use_stats { 0 }
2792
2793
2794 =head2 $c->write( $data )
2795
2796 Writes $data to the output stream. When using this method directly, you
2797 will need to manually set the C<Content-Length> header to the length of
2798 your output data, if known.
2799
2800 =cut
2801
2802 sub write {
2803     my $c = shift;
2804
2805     # Finalize headers if someone manually writes output (for compat)
2806     $c->finalize_headers;
2807
2808     return $c->response->write( @_ );
2809 }
2810
2811 =head2 version
2812
2813 Returns the Catalyst version number. Mostly useful for "powered by"
2814 messages in template systems.
2815
2816 =cut
2817
2818 sub version { return $Catalyst::VERSION }
2819
2820 =head1 CONFIGURATION
2821
2822 There are a number of 'base' config variables which can be set:
2823
2824 =over
2825
2826 =item *
2827
2828 C<default_model> - The default model picked if you say C<< $c->model >>. See L<< /$c->model($name) >>.
2829
2830 =item *
2831
2832 C<default_view> - The default view to be rendered or returned when C<< $c->view >> is called. See L<< /$c->view($name) >>.
2833
2834 =item *
2835
2836 C<home> - The application home directory. In an uninstalled application,
2837 this is the top level application directory. In an installed application,
2838 this will be the directory containing C<< MyApp.pm >>.
2839
2840 =item *
2841
2842 C<ignore_frontend_proxy> - See L</PROXY SUPPORT>
2843
2844 =item *
2845
2846 C<name> - The name of the application in debug messages and the debug and
2847 welcome screens
2848
2849 =item *
2850
2851 C<parse_on_demand> - The request body (for example file uploads) will not be parsed
2852 until it is accessed. This allows you to (for example) check authentication (and reject
2853 the upload) before actually receiving all the data. See L</ON-DEMAND PARSER>
2854
2855 =item *
2856
2857 C<root> - The root directory for templates. Usually this is just a
2858 subdirectory of the home directory, but you can set it to change the
2859 templates to a different directory.
2860
2861 =item *
2862
2863 C<show_internal_actions> - If true, causes internal actions such as C<< _DISPATCH >>
2864 to be shown in hit debug tables in the test server.
2865
2866 =item *
2867
2868 C<use_request_uri_for_path> - Controls if the C<REQUEST_URI> or C<PATH_INFO> environment
2869 variable should be used for determining the request path. 
2870
2871 Most web server environments pass the requested path to the application using environment variables,
2872 from which Catalyst has to reconstruct the request base (i.e. the top level path to / in the application,
2873 exposed as C<< $c->request->base >>) and the request path below that base.
2874
2875 There are two methods of doing this, both of which have advantages and disadvantages. Which method is used
2876 is determined by the C<< $c->config(use_request_uri_for_path) >> setting (which can either be true or false).
2877
2878 =over
2879
2880 =item use_request_uri_for_path => 0
2881
2882 This is the default (and the) traditional method that Catalyst has used for determining the path information.
2883 The path is generated from a combination of the C<PATH_INFO> and C<SCRIPT_NAME> environment variables.
2884 The allows the application to behave correctly when C<mod_rewrite> is being used to redirect requests
2885 into the application, as these variables are adjusted by mod_rewrite to take account for the redirect.
2886
2887 However this method has the major disadvantage that it is impossible to correctly decode some elements
2888 of the path, as RFC 3875 says: "C<< Unlike a URI path, the PATH_INFO is not URL-encoded, and cannot
2889 contain path-segment parameters. >>" This means PATH_INFO is B<always> decoded, and therefore Catalyst
2890 can't distinguish / vs %2F in paths (in addition to other encoded values).
2891
2892 =item use_request_uri_for_path => 1
2893
2894 This method uses the C<REQUEST_URI> and C<SCRIPT_NAME> environment variables. As C<REQUEST_URI> is never
2895 decoded, this means that applications using this mode can correctly handle URIs including the %2F character
2896 (i.e. with C<AllowEncodedSlashes> set to C<On> in Apache).
2897
2898 Given that this method of path resolution is provably more correct, it is recommended that you use
2899 this unless you have a specific need to deploy your application in a non-standard environment, and you are
2900 aware of the implications of not being able to handle encoded URI paths correctly.
2901
2902 However it also means that in a number of cases when the app isn't installed directly at a path, but instead
2903 is having paths rewritten into it (e.g. as a .cgi/fcgi in a public_html directory, with mod_rewrite in a
2904 .htaccess file, or when SSI is used to rewrite pages into the app, or when sub-paths of the app are exposed
2905 at other URIs than that which the app is 'normally' based at with C<mod_rewrite>), the resolution of
2906 C<< $c->request->base >> will be incorrect.
2907
2908 =back
2909
2910 =item *
2911
2912 C<using_frontend_proxy> - See L</PROXY SUPPORT>.
2913
2914 =back
2915
2916 =head1 INTERNAL ACTIONS
2917
2918 Catalyst uses internal actions like C<_DISPATCH>, C<_BEGIN>, C<_AUTO>,
2919 C<_ACTION>, and C<_END>. These are by default not shown in the private
2920 action table, but you can make them visible with a config parameter.
2921
2922     MyApp->config(show_internal_actions => 1);
2923
2924 =head1 ON-DEMAND PARSER
2925
2926 The request body is usually parsed at the beginning of a request,
2927 but if you want to handle input yourself, you can enable on-demand
2928 parsing with a config parameter.
2929
2930     MyApp->config(parse_on_demand => 1);
2931
2932 =head1 PROXY SUPPORT
2933
2934 Many production servers operate using the common double-server approach,
2935 with a lightweight frontend web server passing requests to a larger
2936 backend server. An application running on the backend server must deal
2937 with two problems: the remote user always appears to be C<127.0.0.1> and
2938 the server's hostname will appear to be C<localhost> regardless of the
2939 virtual host that the user connected through.
2940
2941 Catalyst will automatically detect this situation when you are running
2942 the frontend and backend servers on the same machine. The following
2943 changes are made to the request.
2944
2945     $c->req->address is set to the user's real IP address, as read from
2946     the HTTP X-Forwarded-For header.
2947
2948     The host value for $c->req->base and $c->req->uri is set to the real
2949     host, as read from the HTTP X-Forwarded-Host header.
2950
2951 Additionally, you may be running your backend application on an insecure
2952 connection (port 80) while your frontend proxy is running under SSL.  If there
2953 is a discrepancy in the ports, use the HTTP header C<X-Forwarded-Port> to
2954 tell Catalyst what port the frontend listens on.  This will allow all URIs to
2955 be created properly.
2956
2957 In the case of passing in:
2958
2959     X-Forwarded-Port: 443
2960
2961 All calls to C<uri_for> will result in an https link, as is expected.
2962
2963 Obviously, your web server must support these headers for this to work.
2964
2965 In a more complex server farm environment where you may have your
2966 frontend proxy server(s) on different machines, you will need to set a
2967 configuration option to tell Catalyst to read the proxied data from the
2968 headers.
2969
2970     MyApp->config(using_frontend_proxy => 1);
2971
2972 If you do not wish to use the proxy support at all, you may set:
2973
2974     MyApp->config(ignore_frontend_proxy => 0);
2975
2976 =head2 Note about psgi files
2977
2978 Note that if you supply your own .psgi file, calling
2979 C<< MyApp->psgi_app(@_); >>, then B<this will not happen automatically>.
2980
2981 You either need to apply L<Plack::Middleware::ReverseProxy> yourself
2982 in your psgi, for example:
2983
2984     builder {
2985         enable "Plack::Middleware::ReverseProxy";
2986         MyApp->psgi_app
2987     };
2988
2989 This will unconditionally add the ReverseProxy support, or you need to call
2990 C<< $app = MyApp->apply_default_middlewares($app) >> (to conditionally
2991 apply the support depending upon your config).
2992
2993 See L<Catalyst::PSGI> for more information.
2994
2995 =head1 THREAD SAFETY
2996
2997 Catalyst has been tested under Apache 2's threading C<mpm_worker>,
2998 C<mpm_winnt>, and the standalone forking HTTP server on Windows. We
2999 believe the Catalyst core to be thread-safe.
3000
3001 If you plan to operate in a threaded environment, remember that all other
3002 modules you are using must also be thread-safe. Some modules, most notably
3003 L<DBD::SQLite>, are not thread-safe.
3004
3005 =head1 SUPPORT
3006
3007 IRC:
3008
3009     Join #catalyst on irc.perl.org.
3010
3011 Mailing Lists:
3012
3013     http://lists.scsys.co.uk/cgi-bin/mailman/listinfo/catalyst
3014     http://lists.scsys.co.uk/cgi-bin/mailman/listinfo/catalyst-dev
3015
3016 Web:
3017
3018     http://catalyst.perl.org
3019
3020 Wiki:
3021
3022     http://dev.catalyst.perl.org
3023
3024 =head1 SEE ALSO
3025
3026 =head2 L<Task::Catalyst> - All you need to start with Catalyst
3027
3028 =head2 L<Catalyst::Manual> - The Catalyst Manual
3029
3030 =head2 L<Catalyst::Component>, L<Catalyst::Controller> - Base classes for components
3031
3032 =head2 L<Catalyst::Engine> - Core engine
3033
3034 =head2 L<Catalyst::Log> - Log class.
3035
3036 =head2 L<Catalyst::Request> - Request object
3037
3038 =head2 L<Catalyst::Response> - Response object
3039
3040 =head2 L<Catalyst::Test> - The test suite.
3041
3042 =head1 PROJECT FOUNDER
3043
3044 sri: Sebastian Riedel <sri@cpan.org>
3045
3046 =head1 CONTRIBUTORS
3047
3048 abw: Andy Wardley
3049
3050 acme: Leon Brocard <leon@astray.com>
3051
3052 abraxxa: Alexander Hartmaier <abraxxa@cpan.org>
3053
3054 Andrew Bramble
3055
3056 Andrew Ford E<lt>A.Ford@ford-mason.co.ukE<gt>
3057
3058 Andrew Ruthven
3059
3060 André Walker
3061
3062 andyg: Andy Grundman <andy@hybridized.org>
3063
3064 audreyt: Audrey Tang
3065
3066 bricas: Brian Cassidy <bricas@cpan.org>
3067
3068 Caelum: Rafael Kitover <rkitover@io.com>
3069
3070 chansen: Christian Hansen
3071
3072 chicks: Christopher Hicks
3073
3074 Chisel Wright C<pause@herlpacker.co.uk>
3075
3076 Danijel Milicevic C<me@danijel.de>
3077
3078 David Kamholz E<lt>dkamholz@cpan.orgE<gt>
3079
3080 David Naughton, C<naughton@umn.edu>
3081
3082 David E. Wheeler
3083
3084 dhoss: Devin Austin <dhoss@cpan.org>
3085
3086 dkubb: Dan Kubb <dan.kubb-cpan@onautopilot.com>
3087
3088 Drew Taylor
3089
3090 dwc: Daniel Westermann-Clark <danieltwc@cpan.org>
3091
3092 esskar: Sascha Kiefer
3093
3094 fireartist: Carl Franks <cfranks@cpan.org>
3095
3096 frew: Arthur Axel "fREW" Schmidt <frioux@gmail.com>
3097
3098 gabb: Danijel Milicevic
3099
3100 Gary Ashton Jones
3101
3102 Gavin Henry C<ghenry@perl.me.uk>
3103
3104 Geoff Richards
3105
3106 groditi: Guillermo Roditi <groditi@gmail.com>
3107
3108 hobbs: Andrew Rodland <andrew@cleverdomain.org>
3109
3110 ilmari: Dagfinn Ilmari MannsÃ¥ker <ilmari@ilmari.org>
3111
3112 jcamacho: Juan Camacho
3113
3114 jester: Jesse Sheidlower C<jester@panix.com>
3115
3116 jhannah: Jay Hannah <jay@jays.net>
3117
3118 Jody Belka
3119
3120 Johan Lindstrom
3121
3122 jon: Jon Schutz <jjschutz@cpan.org>
3123
3124 Jonathan Rockway C<< <jrockway@cpan.org> >>
3125
3126 Kieren Diment C<kd@totaldatasolution.com>
3127
3128 konobi: Scott McWhirter <konobi@cpan.org>
3129
3130 marcus: Marcus Ramberg <mramberg@cpan.org>
3131
3132 miyagawa: Tatsuhiko Miyagawa <miyagawa@bulknews.net>
3133
3134 mst: Matt S. Trout <mst@shadowcatsystems.co.uk>
3135
3136 mugwump: Sam Vilain
3137
3138 naughton: David Naughton
3139
3140 ningu: David Kamholz <dkamholz@cpan.org>
3141
3142 nothingmuch: Yuval Kogman <nothingmuch@woobling.org>
3143
3144 numa: Dan Sully <daniel@cpan.org>
3145
3146 obra: Jesse Vincent
3147
3148 Octavian Rasnita
3149
3150 omega: Andreas Marienborg
3151
3152 Oleg Kostyuk <cub.uanic@gmail.com>
3153
3154 phaylon: Robert Sedlacek <phaylon@dunkelheit.at>
3155
3156 rafl: Florian Ragwitz <rafl@debian.org>
3157
3158 random: Roland Lammel <lammel@cpan.org>
3159
3160 Robert Sedlacek C<< <rs@474.at> >>
3161
3162 SpiceMan: Marcel Montes
3163
3164 sky: Arthur Bergman
3165
3166 szbalint: Balint Szilakszi <szbalint@cpan.org>
3167
3168 t0m: Tomas Doran <bobtfish@bobtfish.net>
3169
3170 Ulf Edvinsson
3171
3172 Viljo Marrandi C<vilts@yahoo.com>
3173
3174 Will Hawes C<info@whawes.co.uk>
3175
3176 willert: Sebastian Willert <willert@cpan.org>
3177
3178 wreis: Wallace Reis <wallace@reis.org.br>
3179
3180 Yuval Kogman, C<nothingmuch@woobling.org>
3181
3182 rainboxx: Matthias Dietrich, C<perl@rainboxx.de>
3183
3184 dd070: Dhaval Dhanani <dhaval070@gmail.com>
3185
3186 =head1 COPYRIGHT
3187
3188 Copyright (c) 2005, the above named PROJECT FOUNDER and CONTRIBUTORS.
3189
3190 =head1 LICENSE
3191
3192 This library is free software. You can redistribute it and/or modify it under
3193 the same terms as Perl itself.
3194
3195 =cut
3196
3197 no Moose;
3198
3199 __PACKAGE__->meta->make_immutable;
3200
3201 1;