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;
12 use Catalyst::Request;
13 use Catalyst::Request::Upload;
14 use Catalyst::Response;
16 use Catalyst::Controller;
19 use Text::SimpleTable ();
20 use Path::Class::Dir ();
21 use Path::Class::File ();
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/;
30 use String::RewritePrefix;
31 use Catalyst::EngineLoader;
33 use Carp qw/croak carp shortmess/;
35 use Plack::Middleware::Conditional;
36 use Plack::Middleware::ReverseProxy;
37 use Plack::Middleware::IIS6ScriptNameFix;
38 use Plack::Middleware::LighttpdScriptNameFix;
40 BEGIN { require 5.008003; }
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 { {} });
52 my %p = ( _log => $self->log );
53 $p{_uploadtmp} = $self->_uploadtmp if $self->_has_uploadtmp;
54 $self->request_class->new(\%p);
62 $self->response_class->new({ _log => $self->log });
66 has namespace => (is => 'rw');
68 sub depth { scalar @{ shift->stack || [] }; }
69 sub comp { shift->component(@_) }
72 my $self = shift; return $self->request(@_);
75 my $self = shift; return $self->response(@_);
78 # For backwards compatibility
79 sub finalize_output { shift->finalize_body(@_) };
84 our $RECURSION = 1000;
85 our $DETACH = Catalyst::Exception::Detach->new;
86 our $GO = Catalyst::Exception::Go->new;
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/;
95 __PACKAGE__->dispatcher_class('Catalyst::Dispatcher');
96 __PACKAGE__->request_class('Catalyst::Request');
97 __PACKAGE__->response_class('Catalyst::Response');
98 __PACKAGE__->stats_class('Catalyst::Stats');
100 # Remember to update this in Catalyst::Runtime as well!
102 our $VERSION = '5.90015';
105 my ( $class, @arguments ) = @_;
107 # We have to limit $class to Catalyst to avoid pushing Catalyst upon every
109 return unless $class eq 'Catalyst';
111 my $caller = caller();
112 return if $caller eq 'main';
114 my $meta = Moose::Meta::Class->initialize($caller);
116 unless ( $caller->isa('Catalyst') ) { # XXX - Remove!
117 my @superclasses = ($meta->superclasses, $class, 'Catalyst::Component'); # XXX - Remove!
118 $meta->superclasses(@superclasses); # XXX - Remove!
121 # Avoid possible C3 issues if 'Moose::Object' is already on RHS of MyApp
122 $meta->superclasses(grep { $_ ne 'Moose::Object' } $meta->superclasses);
124 unless( $meta->has_method('meta') ){
125 if ($Moose::VERSION >= 1.15) {
126 $meta->_add_meta_method('meta');
129 $meta->add_method(meta => sub { Moose::Meta::Class->initialize("${caller}") } );
133 $caller->arguments( [@arguments] );
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."
146 sub _application { $_[0] }
152 Catalyst - The Elegant MVC Web Application Framework
156 See the L<Catalyst::Manual> distribution for comprehensive
157 documentation and tutorials.
159 # Install Catalyst::Devel for helpers and other development tools
160 # use the helper to create a new application
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
168 # built in testserver -- use -r to restart automatically on changes
169 # --help to see all available options
170 script/myapp_server.pl
172 # command line testing interface
173 script/myapp_test.pl /yada
176 use Catalyst qw/-Debug/; # include plugins here as well
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
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
191 # The foo.tt TT template can use the stash data from the database
192 [% WHILE (item = data.next) %]
196 # called for /bar/of/soap, /bar/of/soap/10, etc.
197 sub bar : Chained('/') PathPart('/bar/of/soap') Args() { ... }
199 # called after all actions are finished
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
207 See L<Catalyst::Manual::Intro> for additional information.
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>.
216 See L<Catalyst::Manual> for more documentation.
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
223 use Catalyst qw/My::Module/;
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:
230 +Fully::Qualified::Plugin::Name
233 Special flags like C<-Debug> can also be specified as
234 arguments when Catalyst is loaded:
236 use Catalyst qw/-Debug My::Module/;
238 The position of plugins and flags in the chain is important, because
239 they are loaded in the order in which they appear.
241 The following flags are supported:
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
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 >>.
255 Forces Catalyst to use a specific home directory, e.g.:
257 use Catalyst qw[-Home=/usr/mst];
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.
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)
275 use Catalyst '-Log=warn,fatal,error';
277 Specifies a comma-delimited list of log levels.
281 Enables statistics collection and reporting.
283 use Catalyst qw/-Stats=1/;
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.
289 Stats are also enabled if L<< debugging |/"-Debug" >> is enabled.
293 =head2 INFORMATION ABOUT THE CURRENT REQUEST
297 Returns a L<Catalyst::Action> object for the current action, which
298 stringifies to the action name. See L<Catalyst::Action>.
302 Returns the namespace of the current action, i.e., the URI prefix
303 corresponding to the controller of the current action. For example:
305 # in Controller::Foo::Bar
306 $c->namespace; # returns 'foo/bar';
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>.
316 =head2 REQUEST FLOW HANDLING
318 =head2 $c->forward( $action [, \@arguments ] )
320 =head2 $c->forward( $class, $method, [, \@arguments ] )
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.
328 Any data C<return>ed from the action forwarded to, will be returned by the
331 my $foodata = $c->forward('/foo');
332 $c->forward('index');
333 $c->forward(qw/Model::DBIC::Foo do_stuff/);
334 $c->forward('View::TT');
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
344 die join "\n", @{ $c->error } if @{ $c->error };
346 Or make sure to always return true values from your actions and write
349 $c->forward('foo') || return;
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:
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,
362 $c->stash->{array} = \@array;
364 and access it from the stash.
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.
370 sub forward { my $c = shift; no warnings 'recursion'; $c->dispatcher->forward( $c, @_ ) }
372 =head2 $c->detach( $action [, \@arguments ] )
374 =head2 $c->detach( $class, $method, [, \@arguments ] )
378 The same as L<< forward|/"$c->forward( $action [, \@arguments ] )" >>, but
379 doesn't return to the previous action when processing is finished.
381 When called with no arguments it escapes the processing chain entirely.
385 sub detach { my $c = shift; $c->dispatcher->detach( $c, @_ ) }
387 =head2 $c->visit( $action [, \@arguments ] )
389 =head2 $c->visit( $action [, \@captures, \@arguments ] )
391 =head2 $c->visit( $class, $method, [, \@arguments ] )
393 =head2 $c->visit( $class, $method, [, \@captures, \@arguments ] )
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.
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.
409 C<< $c->stash >> is kept unchanged.
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.
419 sub visit { my $c = shift; $c->dispatcher->visit( $c, @_ ) }
421 =head2 $c->go( $action [, \@arguments ] )
423 =head2 $c->go( $action [, \@captures, \@arguments ] )
425 =head2 $c->go( $class, $method, [, \@arguments ] )
427 =head2 $c->go( $class, $method, [, \@captures, \@arguments ] )
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.
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
445 sub go { my $c = shift; $c->dispatcher->go( $c, @_ ) }
451 Returns the current L<Catalyst::Response> object, see there for details.
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
463 $c->stash->{foo} = $bar;
464 $c->stash( { moose => 'majestic', qux => 0 } );
465 $c->stash( bar => 1, gorch => 2 ); # equivalent to passing a hashref
467 # stash is automatically passed to the view for use in a template
468 $c->forward( 'MyApp::View::TT' );
472 around stash => sub {
475 my $stash = $orig->($c);
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};
490 =head2 $c->error($error, ...)
492 =head2 $c->error($arrayref)
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.
498 my @error = @{ $c->error };
502 $c->error('Something bad happened');
509 my $error = ref $_[0] eq 'ARRAY' ? $_[0] : [@_];
510 croak @$error unless ref $c;
511 push @{ $c->{error} }, @$error;
513 elsif ( defined $_[0] ) { $c->{error} = undef }
514 return $c->{error} || [];
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.
524 =head2 $c->clear_errors
526 Clear errors. You probably don't want to clear the errors unless you are
527 implementing a custom error screen.
529 This is equivalent to running
540 =head2 COMPONENT ACCESSORS
542 =head2 $c->controller($name)
544 Gets a L<Catalyst::Controller> instance by name.
546 $c->controller('Foo')->do_stuff;
548 If the name is omitted, will return the controller for the dispatched
551 If you want to search for controllers, pass in a regexp as the argument.
553 # find all controllers that start with Foo
554 my @foo_controllers = $c->controller(qr{^Foo});
559 sub controller { shift->_lookup_mvc('controller', @_) }
561 =head2 $c->model($name)
563 Gets a L<Catalyst::Model> instance by name.
565 $c->model('Foo')->do_stuff;
567 Any extra arguments are directly passed to ACCEPT_CONTEXT.
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.
575 If you want to search for models, pass in a regexp as the argument.
577 # find all models that start with Foo
578 my @foo_models = $c->model(qr{^Foo});
582 sub model { shift->_lookup_mvc('model', @_) }
584 =head2 $c->view($name)
586 Gets a L<Catalyst::View> instance by name.
588 $c->view('Foo')->do_stuff;
590 Any extra arguments are directly passed to ACCEPT_CONTEXT.
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.
598 If you want to search for views, pass in a regexp as the argument.
600 # find all views that start with Foo
601 my @foo_views = $c->view(qr{^Foo});
605 sub view { shift->_lookup_mvc('view', @_) }
608 my ( $c, $type, $name, @args ) = @_;
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';
615 $name = $type eq 'controller'
616 ? Catalyst::Utils::class2classshortsuffix($c->action->class)
617 : $c->stash->{"current_${type}"}
621 return $c->container->get_component_from_sub_container($type, $name, $c, @args);
624 =head2 $c->controllers
626 Returns the available names which can be passed to $c->controller
632 return $c->container->get_sub_container('controller')->get_service_list;
637 Returns the available names which can be passed to $c->model
643 return $c->container->get_sub_container('model')->get_service_list;
649 Returns the available names which can be passed to $c->view
655 return $c->container->get_sub_container('view')->get_service_list;
658 =head2 $c->comp($name)
660 =head2 $c->component($name)
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.
667 If C<$name> is a regexp, a list of components matched against the full
668 component name will be returned.
673 my ( $c, $component, @args ) = @_;
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;
682 my @result = $c->container->find_component( $component, $c, @args );
684 # list context for regexp searches
685 return @result if ref $component;
687 # only one component (if it's found) for string searches
688 return shift @result if @result;
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.');
696 $c->log->warn("Looking for '$component', but nothing was found.");
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.');
704 return $c->component_list;
707 =head2 $c->component_list
709 Returns the sorted list of the component names of the application.
713 sub component_list { sort keys %{ shift->components } }
715 =head2 CLASS DATA AND HELPER CLASSES
719 Returns or takes a hashref containing the application's configuration.
721 __PACKAGE__->config( { db => 'dsn:SQLite:foo.db' } );
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>.
727 =head3 Cascading configuration
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.
736 The configuration for a component is then passed to the C<new> method when a
737 component is constructed.
741 MyApp->config({ 'Model::Foo' => { bar => 'baz', overrides => 'me' } });
742 MyApp::Model::Foo->config({ quux => 'frob', overrides => 'this' });
744 will mean that C<MyApp::Model::Foo> receives the following data when
747 MyApp::Model::Foo->new({
753 It's common practice to use a Moose attribute
754 on the receiving component to access the config value.
756 package MyApp::Model::Foo;
760 # this attr will receive 'baz' at construction time
766 You can then get the value 'baz' by calling $c->model('Foo')->bar
767 (or $self->bar inside code in the model).
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.
776 around config => sub {
780 croak('Setting config after setup has been run is not allowed.')
781 if ( @_ and $c->setup_finished );
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 >>.
793 __PACKAGE__->log( MyLogger->new );
798 $c->log->info( 'Now logging with my own logger!' );
800 Your log class should implement the methods described in
806 Returns 1 if debug mode is enabled, 0 otherwise.
808 You can enable debug mode in several ways:
812 =item By calling myapp_server.pl with the -d flag
814 =item With the environment variables MYAPP_DEBUG, or CATALYST_DEBUG
816 =item The -Debug option in your MyApp.pm
818 =item By declaring C<sub debug { 1 }> in your MyApp.pm.
822 The first three also set the log level to 'debug'.
824 Calling C<< $c->debug(1) >> has no effect.
830 =head2 $c->dispatcher
832 Returns the dispatcher instance. See L<Catalyst::Dispatcher>.
836 Returns the engine instance. See L<Catalyst::Engine>.
839 =head2 UTILITY METHODS
841 =head2 $c->path_to(@path)
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.
850 $c->path_to( 'db', 'sqlite.db' );
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 ) }
862 my ( $class, $name, $plugin, @args ) = @_;
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/);
868 $class->_register_plugin( $plugin, 1 );
870 eval { $plugin->import };
871 $class->mk_classdata($name);
873 eval { $obj = $plugin->new(@args) };
876 Catalyst::Exception->throw( message =>
877 qq/Couldn't instantiate instant plugin "$plugin", "$@"/ );
881 $class->log->debug(qq/Initialized instant plugin "$plugin" as "$name"/)
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
893 MyApp->setup( qw/-Debug/ );
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.
901 my ( $class, @arguments ) = @_;
902 croak('Running setup more than once')
903 if ( $class->setup_finished );
905 unless ( $class->isa('Catalyst') ) {
907 Catalyst::Exception->throw(
908 message => qq/'$class' does not inherit from Catalyst/ );
911 if ( $class->arguments ) {
912 @arguments = ( @arguments, @{ $class->arguments } );
918 foreach (@arguments) {
922 ( $flags->{log} ) ? 'debug,' . $flags->{log} : 'debug';
924 elsif (/^-(\w+)=?(.*)$/) {
925 $flags->{ lc $1 } = $2;
928 push @{ $flags->{plugins} }, $_;
932 $class->setup_config();
933 $class->setup_home( delete $flags->{home} );
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");
941 $class->setup_engine();
942 $class->setup_stats( delete $flags->{stats} );
944 for my $flag ( sort keys %{$flags} ) {
946 if ( my $code = $class->can( 'setup_' . $flag ) ) {
947 &$code( $class, delete $flags->{$flag} );
950 $class->log->warn(qq/Unknown flag "$flag"/);
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!
959 Please update by running (this will overwrite existing files):
960 catalyst.pl -force -scripts $class
962 or (this will not overwrite existing files):
963 catalyst.pl -scripts $class
968 if ( $class->debug ) {
969 my @plugins = map { "$_ " . ( $_->VERSION || '' ) } $class->registered_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" );
978 my $dispatcher = $class->dispatcher;
979 my $engine = $class->engine;
980 my $home = $class->config->{home};
982 $class->log->debug(sprintf(q/Loaded dispatcher "%s"/, blessed($dispatcher)));
983 $class->log->debug(sprintf(q/Loaded engine "%s"/, blessed($engine)));
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/);
992 # Call plugins setup, this is stupid and evil.
993 # Also screws C3 badly on 5.10, hack to avoid.
995 no warnings qw/redefine/;
996 local *setup = sub { };
997 $class->setup unless $Catalyst::__AM_RESTARTING;
1000 $class->setup_components;
1004 my $comps = $class->container->get_all_components($class)
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;
1010 $class->log->debug( "Loaded components:\n" . $t->draw . "\n" );
1013 $class->setup_actions;
1015 if ( $class->debug ) {
1016 my $name = $class->config->{name} || 'Application';
1017 $class->log->info("$name powered by Catalyst $Catalyst::VERSION");
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.");
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.
1032 =head2 $app->setup_finalize
1034 A hook to attach modifiers to. This method does not do anything except set the
1035 C<setup_finished> accessor.
1037 Applying method modifiers to the C<setup> method doesn't work, because of quirky things done for plugin setup.
1041 after setup_finalize => sub {
1049 sub setup_finalize {
1051 $class->setup_finished(1);
1054 =head2 $c->uri_for( $path?, @args?, \%query_values? )
1056 =head2 $c->uri_for( $action, \@captures?, @args?, \%query_values? )
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>.
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 ) >>.
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.
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
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.
1087 # Equivalent to $c->req->uri
1088 $c->uri_for($c->action, $c->req->captures,
1089 @{ $c->req->args }, $c->req->params);
1091 # For the Foo action in the Bar controller
1092 $c->uri_for($c->controller('Bar')->action_for('Foo'));
1094 # Path to a static resource
1095 $c->uri_for('/static/images/logo.png');
1100 my ( $c, $path, @args ) = @_;
1102 if (blessed($path) && $path->isa('Catalyst::Controller')) {
1103 $path = $path->path_prefix;
1108 undef($path) if (defined $path && $path eq '');
1111 ( scalar @args && ref $args[$#args] eq 'HASH' ? pop @args : {} );
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;
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'
1126 foreach my $capture (@$captures) {
1127 utf8::encode($capture) if utf8::is_utf8($capture);
1128 $capture =~ s/([^$URI::uric])/$URI::Escape::escapes{$1}/go;
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 );
1136 my $num_captures = $expanded_action->number_of_captures;
1137 unshift @args, splice @$captures, $num_captures;
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/)
1146 $path = '/' if $path eq '';
1149 unshift(@args, $path);
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{^\.\./}{};
1156 unshift(@args, $namespace || '');
1159 # join args with '/', or a blank string
1160 my $args = join('/', grep { defined($_) } @args);
1161 $args =~ s/\?/%3F/g; # STUPID STUPID SPECIAL CASE
1163 my $base = $c->req->base;
1164 my $class = ref($base);
1165 $base =~ s{(?<!/)$}{/};
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;
1176 $val = '' unless defined $val;
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;
1183 "${key}=$param"; } ( ref $val eq 'ARRAY' ? @$val : $val ));
1187 my $res = bless(\"${base}${args}${query}", $class);
1191 =head2 $c->uri_for_action( $path, \@captures_and_args?, @args?, \%query_values? )
1193 =head2 $c->uri_for_action( $action, \@captures_and_args?, @args?, \%query_values? )
1199 A private path to the Catalyst action you want to create a URI for.
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<<
1205 You can also pass in a Catalyst::Action object, in which case it is passed to
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.
1210 For example, if the action looks like:
1212 package MyApp::Controller::Users;
1214 sub lst : Path('the-list') {}
1218 $c->uri_for_action('/users/lst')
1220 and it will create the URI /users/the-list.
1222 =item \@captures_and_args?
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.
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
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)..
1237 =item \%query_values?
1239 Optional array reference of query parameters to append. E.g.
1245 /rest/of/your/uri?foo=bar
1251 sub uri_for_action {
1252 my ( $c, $path, @args ) = @_;
1253 my $action = blessed($path)
1255 : $c->dispatcher->get_action_by_path($path);
1256 unless (defined $action) {
1257 croak "Can't find action for path '$path'";
1259 return $c->uri_for( $action, @args );
1262 =head2 $c->welcome_message
1264 Returns the Catalyst welcome HTML page.
1268 sub welcome_message {
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');
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">
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">
1285 background-color: #eee;
1292 margin-bottom: 10px;
1294 background-color: #ccc;
1295 border: 1px solid #aaa;
1300 font-family: verdana, tahoma, sans-serif;
1303 font-family: verdana, tahoma, sans-serif;
1306 text-decoration: none;
1308 border-bottom: 1px dotted #bbb;
1310 :link:hover, :visited:hover {
1323 background-color: #fff;
1324 border: 1px solid #aaa;
1328 font-weight: normal;
1350 <h1><span id="appname">$name</span> on <a href="http://catalyst.perl.org">Catalyst</a>
1355 <img src="$logo" alt="Catalyst Logo" />
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>
1368 <p>Afterwards you can go on to check out a more complete look at our features.</p>
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 -->
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.
1386 <p>Catalyst has a very active community. Here are the main places to
1387 get in touch with us.</p>
1390 <a href="http://dev.catalyst.perl.org">Wiki</a>
1393 <a href="http://lists.scsys.co.uk/cgi-bin/mailman/listinfo/catalyst">Mailing-List</a>
1396 <a href="irc://irc.perl.org/catalyst">IRC channel #catalyst on irc.perl.org</a>
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>
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.
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
1420 =head1 INTERNAL METHODS
1422 These methods are not meant to be used by end users.
1424 =head2 $c->components
1426 Returns a hash of components.
1431 my ( $class, $comps ) = @_;
1433 # people create components calling this sub directly, before setup
1434 $class->setup_config unless $class->container;
1436 my $container = $class->container;
1439 $container->add_component( $_ ) for keys %$comps;
1442 return $container->get_all_components($class);
1445 =head2 $c->context_class
1447 Returns or sets the context class.
1451 Returns a hashref containing coderefs and execution counts (needed for
1452 deep recursion detection).
1456 Returns the number of actions on the current internal execution stack.
1460 Dispatches a request to actions.
1464 sub dispatch { my $c = shift; $c->dispatcher->dispatch( $c, @_ ) }
1466 =head2 $c->dispatcher_class
1468 Returns or sets the dispatcher class.
1470 =head2 $c->dump_these
1472 Returns a list of 2-element array references (name, structure) pairs
1473 that will be dumped on the error page in debug mode.
1479 [ Request => $c->req ],
1480 [ Response => $c->res ],
1481 [ Stash => $c->stash ],
1482 [ Config => $c->config ];
1485 =head2 $c->engine_class
1487 Returns or sets the engine class.
1489 =head2 $c->execute( $class, $coderef )
1491 Execute a coderef in given class and catch exceptions. Errors are available
1497 my ( $c, $class, $code ) = @_;
1498 $class = $c->component($class) || $class;
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);
1511 my $stats_info = $c->_stats_start_execute( $code ) if $c->use_stats;
1513 push( @{ $c->stack }, $code );
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 ) };
1520 $c->_stats_finish_execute( $stats_info ) if $c->use_stats and $stats_info;
1522 my $last = pop( @{ $c->stack } );
1524 if ( my $error = $@ ) {
1525 if ( blessed($error) and $error->isa('Catalyst::Exception::Detach') ) {
1526 $error->rethrow if $c->depth > 1;
1528 elsif ( blessed($error) and $error->isa('Catalyst::Exception::Go') ) {
1529 $error->rethrow if $c->depth > 0;
1532 unless ( ref $error ) {
1533 no warnings 'uninitialized';
1535 my $class = $last->class;
1536 my $name = $last->name;
1537 $error = qq/Caught exception in $class->$name "$error"/;
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} ) );
1552 my $action_name = $code->reverse();
1553 $c->counter->{$action_name}++;
1555 my $action = $action_name;
1556 $action = "/$action" unless $action =~ /->/;
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
1562 for my $index ( 2 .. 11 ) {
1564 if ( ( caller($index) )[0] eq 'Catalyst'
1565 && ( caller($index) )[3] eq '(eval)' );
1567 if ( ( caller($index) )[3] =~ /forward$/ ) {
1568 $callsub = ( caller($index) )[3];
1569 $action = "-> $action";
1574 my $uid = $action_name . $c->counter->{$action_name};
1576 # is this a root-level call or a forwarded call?
1577 if ( $callsub =~ /forward$/ ) {
1578 my $parent = $c->stack->[-1];
1580 # forward, locate the caller
1581 if ( defined $parent && exists $c->counter->{"$parent"} ) {
1584 parent => "$parent" . $c->counter->{"$parent"},
1590 # forward with no caller may come from a plugin
1609 sub _stats_finish_execute {
1610 my ( $c, $info ) = @_;
1611 $c->stats->profile( end => $info );
1616 Finalizes the request.
1623 for my $error ( @{ $c->error } ) {
1624 $c->log->error($error);
1627 # Allow engine to handle finalize flow (for POE)
1628 my $engine = $c->engine;
1629 if ( my $code = $engine->can('finalize') ) {
1634 $c->finalize_uploads;
1637 if ( $#{ $c->error } >= 0 ) {
1641 $c->finalize_headers unless $c->response->finalized_headers;
1644 if ( $c->request->method eq 'HEAD' ) {
1645 $c->response->body('');
1653 if ($c->use_stats) {
1654 my $elapsed = sprintf '%f', $c->stats->elapsed;
1655 my $av = $elapsed == 0 ? '??' : sprintf '%.3f', 1 / $elapsed;
1657 "Request took ${elapsed}s ($av/s)\n" . $c->stats->report . "\n" );
1660 return $c->response->status;
1663 =head2 $c->finalize_body
1669 sub finalize_body { my $c = shift; $c->engine->finalize_body( $c, @_ ) }
1671 =head2 $c->finalize_cookies
1677 sub finalize_cookies { my $c = shift; $c->engine->finalize_cookies( $c, @_ ) }
1679 =head2 $c->finalize_error
1685 sub finalize_error { my $c = shift; $c->engine->finalize_error( $c, @_ ) }
1687 =head2 $c->finalize_headers
1693 sub finalize_headers {
1696 my $response = $c->response; #accessor calls can add up?
1698 # Check if we already finalized headers
1699 return if $response->finalized_headers;
1702 if ( my $location = $response->redirect ) {
1703 $c->log->debug(qq/Redirecting to "$location"/) if $c->debug;
1704 $response->header( Location => $location );
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">
1712 <title>Moved</title>
1715 <p>This item has moved <a href="$location">here</a>.</p>
1719 $response->content_type('text/html; charset=utf-8');
1724 if ( defined $response->body && length $response->body && !$response->content_length ) {
1726 # get the length from a filehandle
1727 if ( blessed( $response->body ) && $response->body->can('read') || ref( $response->body ) eq 'GLOB' )
1729 my $size = -s $response->body;
1731 $response->content_length( $size );
1734 $c->log->warn('Serving filehandle without a content-length');
1738 # everything should be bytes at this point, but just in case
1739 $response->content_length( length( $response->body ) );
1744 if ( $response->status =~ /^(1\d\d|[23]04)$/ ) {
1745 $response->headers->remove_header("Content-Length");
1746 $response->body('');
1749 $c->finalize_cookies;
1751 $c->response->finalize_headers();
1754 $response->finalized_headers(1);
1757 =head2 $c->finalize_output
1759 An alias for finalize_body.
1761 =head2 $c->finalize_read
1763 Finalizes the input after reading is complete.
1767 sub finalize_read { my $c = shift; $c->engine->finalize_read( $c, @_ ) }
1769 =head2 $c->finalize_uploads
1771 Finalizes uploads. Cleans up any temporary files.
1775 sub finalize_uploads { my $c = shift; $c->engine->finalize_uploads( $c, @_ ) }
1777 =head2 $c->get_action( $action, $namespace )
1779 Gets an action in a given namespace.
1783 sub get_action { my $c = shift; $c->dispatcher->get_action(@_) }
1785 =head2 $c->get_actions( $action, $namespace )
1787 Gets all actions of a given name in a namespace and all parent
1792 sub get_actions { my $c = shift; $c->dispatcher->get_actions( $c, @_ ) }
1794 =head2 $app->handle_request( @arguments )
1796 Called to handle each HTTP request.
1800 sub handle_request {
1801 my ( $class, @arguments ) = @_;
1803 # Always expect worst case!
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] ***");
1813 my $c = $class->prepare(@arguments);
1815 $status = $c->finalize;
1818 chomp(my $error = $_);
1819 $class->log->error(qq/Caught exception in engine "$error"/);
1824 if(my $coderef = $class->log->can('_flush')){
1825 $class->log->$coderef();
1830 =head2 $class->prepare( @arguments )
1832 Creates a Catalyst context from an engine-specific request (Apache, CGI,
1839 predicate => '_has_uploadtmp',
1843 my ( $class, @arguments ) = @_;
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;
1850 my $uploadtmp = $class->config->{uploadtmp};
1851 my $c = $class->context_class->new({ $uploadtmp ? (_uploadtmp => $uploadtmp) : ()});
1853 $c->response->_context($c);
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 );
1862 # Allow engine to direct the prepare flow (for POE)
1863 if ( my $prepare = $c->engine->can('prepare') ) {
1864 $c->engine->$prepare( $c, @arguments );
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
1874 # Prepare the body for reading, either by prepare_body
1875 # or the user, if they are using $c->read
1878 # Parse the body unless the user wants it on-demand
1879 unless ( ref($c)->config->{parse_on_demand} ) {
1885 # VERY ugly and probably shouldn't rely on ->finalize actually working
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
1907 =head2 $c->prepare_action
1909 Prepares action. See L<Catalyst::Dispatcher>.
1913 sub prepare_action { my $c = shift; $c->dispatcher->prepare_action( $c, @_ ) }
1915 =head2 $c->prepare_body
1917 Prepares message body.
1924 return if $c->request->_has_body;
1926 # Initialize on-demand data
1927 $c->engine->prepare_body( $c, @_ );
1928 $c->prepare_parameters;
1929 $c->prepare_uploads;
1932 =head2 $c->prepare_body_chunk( $chunk )
1934 Prepares a chunk of data before sending it to L<HTTP::Body>.
1936 See L<Catalyst::Engine>.
1940 sub prepare_body_chunk {
1942 $c->engine->prepare_body_chunk( $c, @_ );
1945 =head2 $c->prepare_body_parameters
1947 Prepares body parameters.
1951 sub prepare_body_parameters {
1953 $c->engine->prepare_body_parameters( $c, @_ );
1956 =head2 $c->prepare_connection
1958 Prepares connection.
1962 sub prepare_connection {
1964 # XXX - This is called on the engine (not the request) to maintain
1965 # Engine::PSGI back compat.
1966 $c->engine->prepare_connection($c);
1969 =head2 $c->prepare_cookies
1971 Prepares cookies by ensuring that the attribute on the request
1972 object has been built.
1976 sub prepare_cookies { my $c = shift; $c->request->cookies }
1978 =head2 $c->prepare_headers
1980 Prepares request headers by ensuring that the attribute on the request
1981 object has been built.
1985 sub prepare_headers { my $c = shift; $c->request->headers }
1987 =head2 $c->prepare_parameters
1989 Prepares parameters.
1993 sub prepare_parameters {
1995 $c->prepare_body_parameters;
1996 $c->engine->prepare_parameters( $c, @_ );
1999 =head2 $c->prepare_path
2001 Prepares path and base.
2005 sub prepare_path { my $c = shift; $c->engine->prepare_path( $c, @_ ) }
2007 =head2 $c->prepare_query_parameters
2009 Prepares query parameters.
2013 sub prepare_query_parameters {
2016 $c->engine->prepare_query_parameters( $c, @_ );
2019 =head2 $c->log_request
2021 Writes information about the request to the debug logs. This includes:
2025 =item * Request method, path, and remote IP address
2027 =item * Query keywords (see L<Catalyst::Request/query_keywords>)
2029 =item * Request parameters
2031 =item * File uploads
2040 return unless $c->debug;
2042 my($dump) = grep {$_->[0] eq 'Request' } $c->dump_these;
2043 my $request = $dump->[1];
2045 my ( $method, $path, $address ) = ( $request->method, $request->path, $request->address );
2047 $path = '/' unless length $path;
2049 $c->log->debug(qq/"$method" request for "$path" from "$address"/);
2051 $c->log_request_headers($request->headers);
2053 if ( my $keywords = $request->query_keywords ) {
2054 $c->log->debug("Query keywords are: $keywords");
2057 $c->log_request_parameters( query => $request->query_parameters, $request->_has_body ? (body => $request->body_parameters) : () );
2059 $c->log_request_uploads($request);
2062 =head2 $c->log_response
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 >>.
2072 return unless $c->debug;
2074 my($dump) = grep {$_->[0] eq 'Response' } $c->dump_these;
2075 my $response = $dump->[1];
2077 $c->log_response_status_line($response);
2078 $c->log_response_headers($response->headers);
2081 =head2 $c->log_response_status_line($response)
2083 Writes one line of information about the response to the debug logs. This includes:
2087 =item * Response status code
2089 =item * Content-Type header (if present)
2091 =item * Content-Length header (if present)
2097 sub log_response_status_line {
2098 my ($c, $response) = @_;
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'
2110 =head2 $c->log_response_headers($headers);
2112 Hook method which can be wrapped by plugins to log the response headers.
2113 No-op in the default implementation.
2117 sub log_response_headers {}
2119 =head2 $c->log_request_parameters( query => {}, body => {} )
2121 Logs request parameters to debug logs
2125 sub log_request_parameters {
2127 my %all_params = @_;
2129 return unless $c->debug;
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 );
2141 $c->log->debug( ucfirst($type) . " Parameters are:\n" . $t->draw );
2145 =head2 $c->log_request_uploads
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
2153 sub log_request_uploads {
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' ],
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 );
2171 $c->log->debug( "File Uploads are:\n" . $t->draw );
2175 =head2 $c->log_request_headers($headers);
2177 Hook method which can be wrapped by plugins to log the request headers.
2178 No-op in the default implementation.
2182 sub log_request_headers {}
2184 =head2 $c->log_headers($type => $headers)
2186 Logs L<HTTP::Headers> (either request or response) to the debug logs.
2193 my $headers = shift; # an HTTP::Headers instance
2195 return unless $c->debug;
2197 my $column_width = Catalyst::Utils::term_width() - 28;
2198 my $t = Text::SimpleTable->new( [ 15, 'Header Name' ], [ $column_width, 'Value' ] );
2201 my ( $name, $value ) = @_;
2202 $t->row( $name, $value );
2205 $c->log->debug( ucfirst($type) . " Headers:\n" . $t->draw );
2209 =head2 $c->prepare_read
2211 Prepares the input for reading.
2215 sub prepare_read { my $c = shift; $c->engine->prepare_read( $c, @_ ) }
2217 =head2 $c->prepare_request
2219 Prepares the engine request.
2223 sub prepare_request { my $c = shift; $c->engine->prepare_request( $c, @_ ) }
2225 =head2 $c->prepare_uploads
2231 sub prepare_uploads {
2234 $c->engine->prepare_uploads( $c, @_ );
2237 =head2 $c->prepare_write
2239 Prepares the output for writing.
2243 sub prepare_write { my $c = shift; $c->engine->prepare_write( $c, @_ ) }
2245 =head2 $c->request_class
2247 Returns or sets the request class. Defaults to L<Catalyst::Request>.
2249 =head2 $c->response_class
2251 Returns or sets the response class. Defaults to L<Catalyst::Response>.
2253 =head2 $c->read( [$maxlength] )
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.
2259 You have to set C<< MyApp->config(parse_on_demand => 1) >> to use this
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.
2268 sub read { my $c = shift; return $c->request->read( @_ ) }
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, @_ );
2284 sub _make_immutable_if_needed {
2286 my $meta = Class::MOP::get_metaclass_by_name($class);
2287 my $isa_ca = $class->isa('Class::Accessor::Fast') || $class->isa('Class::Accessor');
2290 && ! { $meta->immutable_options }->{replace_constructor}
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");
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,
2307 =head2 $c->set_action( $action, $code, $namespace, $attrs )
2309 Sets an action in a given namespace.
2313 sub set_action { my $c = shift; $c->dispatcher->set_action( $c, @_ ) }
2315 =head2 $c->setup_actions($component)
2317 Sets up actions for a component.
2321 sub setup_actions { my $c = shift; $c->dispatcher->setup_actions( $c, @_ ) }
2323 =head2 $c->setup_config
2330 my %args = %{ $class->config || {} };
2332 my $container_class;
2334 if ( exists $args{container_class} ) {
2335 $container_class = delete $args{container_class};
2336 Class::MOP::load_class($container_class);
2339 $container_class = Class::MOP::load_first_existing_class("${class}::Container", 'Catalyst::IOC::Container');
2342 my $container = $container_class->new( %args, name => $class );
2343 $class->container($container);
2345 my $config = $container->resolve( service => 'config' );
2346 $class->config($config);
2347 $class->finalize_config; # back-compat
2350 =head2 $c->finalize_config
2354 sub finalize_config { }
2356 =head2 $c->setup_components
2358 This method is called internally to set up the application's components.
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.
2364 The C<setup_components> config option is passed to both of the above methods.
2368 sub setup_components { shift->container->setup_components }
2370 =head2 locate_components
2374 sub locate_components {
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.');
2381 # XXX think about ditching this sort entirely
2382 return sort { length $a <=> length $b }
2383 @{ $class->container->resolve( service => 'locate_components' ) };
2386 =head2 $c->setup_dispatcher
2392 sub setup_dispatcher {
2393 my ( $class, $dispatcher ) = @_;
2396 $dispatcher = 'Catalyst::Dispatcher::' . $dispatcher;
2399 if ( my $env = Catalyst::Utils::env_value( $class, 'DISPATCHER' ) ) {
2400 $dispatcher = 'Catalyst::Dispatcher::' . $env;
2403 unless ($dispatcher) {
2404 $dispatcher = $class->dispatcher_class;
2407 Class::MOP::load_class($dispatcher);
2409 # dispatcher instance
2410 $class->dispatcher( $dispatcher->new );
2413 =head2 $c->setup_engine
2420 my ($class, $requested_engine) = @_;
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) : ()),
2432 $class->engine_loader->catalyst_engine_class;
2436 my ($class, $requested_engine) = @_;
2439 my $loader = $class->engine_loader;
2441 if (!$loader || $requested_engine) {
2442 $loader = Catalyst::EngineLoader->new({
2443 application_name => $class,
2444 (defined $requested_engine
2445 ? (requested_engine => $requested_engine) : ()),
2448 $class->engine_loader($loader);
2451 $loader->catalyst_engine_class;
2454 # Don't really setup_engine -- see _setup_psgi_app for explanation.
2455 return if $class->loading_psgi_file;
2457 Class::MOP::load_class($engine);
2459 if ($ENV{MOD_PERL}) {
2460 my $apache = $class->engine_loader->auto;
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;
2467 $meta->add_method(handler => sub {
2469 my $psgi_app = $class->_finalized_psgi_app;
2470 $apache->call_app($r, $psgi_app);
2473 $meta->make_immutable(%immutable_options) if $was_immutable;
2476 $class->engine( $engine->new );
2481 sub _finalized_psgi_app {
2484 unless ($app->_psgi_app) {
2485 my $psgi_app = $app->_setup_psgi_app;
2486 $app->_psgi_app($psgi_app);
2489 return $app->_psgi_app;
2492 sub _setup_psgi_app {
2495 for my $home (Path::Class::Dir->new($app->config->{home})) {
2496 my $psgi_file = $home->file(
2497 Catalyst::Utils::appprefix($app) . '.psgi',
2500 next unless -e $psgi_file;
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.
2508 $app->loading_psgi_file(1);
2509 my $psgi_app = Plack::Util::load_psgi($psgi_file);
2510 $app->loading_psgi_file(0);
2513 unless $app->engine_loader->needs_psgi_engine_compat_hack;
2516 Found a legacy Catalyst::Engine::PSGI .psgi file at ${psgi_file}.
2518 Its content has been ignored. Please consult the Catalyst::Upgrading
2519 documentation on how to upgrade from Catalyst::Engine::PSGI.
2523 return $app->apply_default_middlewares($app->psgi_app);
2526 =head2 $c->apply_default_middlewares
2528 Adds the following L<Plack> middlewares to your application, since they are
2529 useful and commonly needed:
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).
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
2544 sub apply_default_middlewares {
2545 my ($app, $psgi_app) = @_;
2547 $psgi_app = Plack::Middleware::Conditional->wrap(
2549 builder => sub { Plack::Middleware::ReverseProxy->wrap($_[0]) },
2552 return if $app->config->{ignore_frontend_proxy};
2553 return $env->{REMOTE_ADDR} eq '127.0.0.1'
2554 || $app->config->{using_frontend_proxy};
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(
2562 builder => sub { Plack::Middleware::LighttpdScriptNameFix->wrap($_[0]) },
2565 return unless $env->{SERVER_SOFTWARE} && $env->{SERVER_SOFTWARE} =~ m!lighttpd[-/]1\.(\d+\.\d+)!;
2566 return unless $1 < 4.23;
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
2574 $psgi_app = Plack::Middleware::IIS6ScriptNameFix->wrap($psgi_app);
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.
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.
2592 return $app->engine->build_psgi_app($app);
2595 =head2 $c->setup_home
2597 Sets up the home directory.
2602 my ( $class, $home ) = @_;
2604 if ( my $env = Catalyst::Utils::env_value( $class, 'HOME' ) ) {
2608 $home ||= Catalyst::Utils::home($class);
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');
2617 =head2 $c->setup_log
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
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.
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.
2634 my ( $class, $levels ) = @_;
2637 $levels =~ s/^\s+//;
2638 $levels =~ s/\s+$//;
2639 my %levels = map { $_ => 1 } split /\s*,\s*/, $levels;
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;
2647 unless ( $class->log ) {
2648 $class->log( Catalyst::Log->new(keys %levels) );
2651 if ( $levels{debug} ) {
2652 Class::MOP::get_metaclass_by_name($class)->add_method('debug' => sub { 1 });
2653 $class->log->debug('Debug messages enabled');
2657 =head2 $c->setup_plugins
2663 =head2 $c->setup_stats
2665 Sets up timing statistics class.
2670 my ( $class, $stats ) = @_;
2672 Catalyst::Utils::ensure_class_loaded($class->stats_class);
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');
2682 =head2 $c->registered_plugins
2684 Returns a sorted list of the plugins which have either been stated in the
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::>.
2691 if ($c->registered_plugins('Some::Plugin')) {
2699 sub registered_plugins {
2701 return sort keys %{ $proto->_plugins } unless @_;
2703 return 1 if exists $proto->_plugins->{$plugin};
2704 return exists $proto->_plugins->{"Catalyst::Plugin::$plugin"};
2707 sub _register_plugin {
2708 my ( $proto, $plugin, $instant ) = @_;
2709 my $class = ref $proto || $proto;
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'))
2719 if (!$instant && !$proto->_plugins->{$plugin}) {
2720 my $meta = Class::MOP::get_metaclass_by_name($class);
2721 $meta->superclasses($plugin, $meta->superclasses);
2723 $proto->_plugins->{$plugin} = 1;
2728 my ( $class, $plugins ) = @_;
2730 $class->_plugins( {} ) unless $class->_plugins;
2731 $plugins = Data::OptList::mkopt($plugins || []);
2734 [ Catalyst::Utils::resolve_namespace(
2735 $class . '::Plugin',
2736 'Catalyst::Plugin', $_->[0]
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');
2747 $class->_register_plugin($plugin->[0]);
2751 map { $_->[0]->name, $_->[1] }
2752 grep { blessed($_->[0]) && $_->[0]->isa('Moose::Meta::Role') }
2753 map { [find_meta($_->[0]), $_->[1]] }
2756 Moose::Util::apply_all_roles(
2764 Returns an arrayref of the internal execution stack (actions that are
2765 currently executing).
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" >>.
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
2778 =head2 $c->stats_class
2780 Returns or sets the stats (timing statistics) class. L<Catalyst::Stats|Catalyst::Stats> is used by default.
2782 =head2 $c->use_stats
2784 Returns 1 when L<< stats collection|/"-Stats" >> is enabled.
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) >>.
2794 =head2 $c->write( $data )
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.
2805 # Finalize headers if someone manually writes output (for compat)
2806 $c->finalize_headers;
2808 return $c->response->write( @_ );
2813 Returns the Catalyst version number. Mostly useful for "powered by"
2814 messages in template systems.
2818 sub version { return $Catalyst::VERSION }
2820 =head1 CONFIGURATION
2822 There are a number of 'base' config variables which can be set:
2828 C<default_model> - The default model picked if you say C<< $c->model >>. See L<< /$c->model($name) >>.
2832 C<default_view> - The default view to be rendered or returned when C<< $c->view >> is called. See L<< /$c->view($name) >>.
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 >>.
2842 C<ignore_frontend_proxy> - See L</PROXY SUPPORT>
2846 C<name> - The name of the application in debug messages and the debug and
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>
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.
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.
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.
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.
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).
2880 =item use_request_uri_for_path => 0
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.
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).
2892 =item use_request_uri_for_path => 1
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).
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.
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.
2912 C<using_frontend_proxy> - See L</PROXY SUPPORT>.
2916 =head1 INTERNAL ACTIONS
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.
2922 MyApp->config(show_internal_actions => 1);
2924 =head1 ON-DEMAND PARSER
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.
2930 MyApp->config(parse_on_demand => 1);
2932 =head1 PROXY SUPPORT
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.
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.
2945 $c->req->address is set to the user's real IP address, as read from
2946 the HTTP X-Forwarded-For header.
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.
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.
2957 In the case of passing in:
2959 X-Forwarded-Port: 443
2961 All calls to C<uri_for> will result in an https link, as is expected.
2963 Obviously, your web server must support these headers for this to work.
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
2970 MyApp->config(using_frontend_proxy => 1);
2972 If you do not wish to use the proxy support at all, you may set:
2974 MyApp->config(ignore_frontend_proxy => 0);
2976 =head2 Note about psgi files
2978 Note that if you supply your own .psgi file, calling
2979 C<< MyApp->psgi_app(@_); >>, then B<this will not happen automatically>.
2981 You either need to apply L<Plack::Middleware::ReverseProxy> yourself
2982 in your psgi, for example:
2985 enable "Plack::Middleware::ReverseProxy";
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).
2993 See L<Catalyst::PSGI> for more information.
2995 =head1 THREAD SAFETY
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.
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.
3009 Join #catalyst on irc.perl.org.
3013 http://lists.scsys.co.uk/cgi-bin/mailman/listinfo/catalyst
3014 http://lists.scsys.co.uk/cgi-bin/mailman/listinfo/catalyst-dev
3018 http://catalyst.perl.org
3022 http://dev.catalyst.perl.org
3026 =head2 L<Task::Catalyst> - All you need to start with Catalyst
3028 =head2 L<Catalyst::Manual> - The Catalyst Manual
3030 =head2 L<Catalyst::Component>, L<Catalyst::Controller> - Base classes for components
3032 =head2 L<Catalyst::Engine> - Core engine
3034 =head2 L<Catalyst::Log> - Log class.
3036 =head2 L<Catalyst::Request> - Request object
3038 =head2 L<Catalyst::Response> - Response object
3040 =head2 L<Catalyst::Test> - The test suite.
3042 =head1 PROJECT FOUNDER
3044 sri: Sebastian Riedel <sri@cpan.org>
3050 acme: Leon Brocard <leon@astray.com>
3052 abraxxa: Alexander Hartmaier <abraxxa@cpan.org>
3056 Andrew Ford E<lt>A.Ford@ford-mason.co.ukE<gt>
3062 andyg: Andy Grundman <andy@hybridized.org>
3064 audreyt: Audrey Tang
3066 bricas: Brian Cassidy <bricas@cpan.org>
3068 Caelum: Rafael Kitover <rkitover@io.com>
3070 chansen: Christian Hansen
3072 chicks: Christopher Hicks
3074 Chisel Wright C<pause@herlpacker.co.uk>
3076 Danijel Milicevic C<me@danijel.de>
3078 David Kamholz E<lt>dkamholz@cpan.orgE<gt>
3080 David Naughton, C<naughton@umn.edu>
3084 dhoss: Devin Austin <dhoss@cpan.org>
3086 dkubb: Dan Kubb <dan.kubb-cpan@onautopilot.com>
3090 dwc: Daniel Westermann-Clark <danieltwc@cpan.org>
3092 esskar: Sascha Kiefer
3094 fireartist: Carl Franks <cfranks@cpan.org>
3096 frew: Arthur Axel "fREW" Schmidt <frioux@gmail.com>
3098 gabb: Danijel Milicevic
3102 Gavin Henry C<ghenry@perl.me.uk>
3106 groditi: Guillermo Roditi <groditi@gmail.com>
3108 hobbs: Andrew Rodland <andrew@cleverdomain.org>
3110 ilmari: Dagfinn Ilmari Mannsåker <ilmari@ilmari.org>
3112 jcamacho: Juan Camacho
3114 jester: Jesse Sheidlower C<jester@panix.com>
3116 jhannah: Jay Hannah <jay@jays.net>
3122 jon: Jon Schutz <jjschutz@cpan.org>
3124 Jonathan Rockway C<< <jrockway@cpan.org> >>
3126 Kieren Diment C<kd@totaldatasolution.com>
3128 konobi: Scott McWhirter <konobi@cpan.org>
3130 marcus: Marcus Ramberg <mramberg@cpan.org>
3132 miyagawa: Tatsuhiko Miyagawa <miyagawa@bulknews.net>
3134 mst: Matt S. Trout <mst@shadowcatsystems.co.uk>
3138 naughton: David Naughton
3140 ningu: David Kamholz <dkamholz@cpan.org>
3142 nothingmuch: Yuval Kogman <nothingmuch@woobling.org>
3144 numa: Dan Sully <daniel@cpan.org>
3150 omega: Andreas Marienborg
3152 Oleg Kostyuk <cub.uanic@gmail.com>
3154 phaylon: Robert Sedlacek <phaylon@dunkelheit.at>
3156 rafl: Florian Ragwitz <rafl@debian.org>
3158 random: Roland Lammel <lammel@cpan.org>
3160 Robert Sedlacek C<< <rs@474.at> >>
3162 SpiceMan: Marcel Montes
3166 szbalint: Balint Szilakszi <szbalint@cpan.org>
3168 t0m: Tomas Doran <bobtfish@bobtfish.net>
3172 Viljo Marrandi C<vilts@yahoo.com>
3174 Will Hawes C<info@whawes.co.uk>
3176 willert: Sebastian Willert <willert@cpan.org>
3178 wreis: Wallace Reis <wallace@reis.org.br>
3180 Yuval Kogman, C<nothingmuch@woobling.org>
3182 rainboxx: Matthias Dietrich, C<perl@rainboxx.de>
3184 dd070: Dhaval Dhanani <dhaval070@gmail.com>
3188 Copyright (c) 2005, the above named PROJECT FOUNDER and CONTRIBUTORS.
3192 This library is free software. You can redistribute it and/or modify it under
3193 the same terms as Perl itself.
3199 __PACKAGE__->meta->make_immutable;