4 use base 'Catalyst::Base';
6 use UNIVERSAL::require;
7 use Catalyst::Exception;
10 use Catalyst::Request::Upload;
11 use Catalyst::Response;
14 use Text::SimpleTable;
16 use Time::HiRes qw/gettimeofday tv_interval/;
18 use Scalar::Util qw/weaken/;
22 require Catalyst::Helper;
23 require Catalyst::PAR;
24 require Catalyst::Build;
25 require Catalyst::Test;
27 require Catalyst::Engine::HTTP;
28 require Catalyst::Engine::CGI;
30 require Catalyst::Controller;
31 require Catalyst::Model;
32 require Catalyst::View;
34 __PACKAGE__->mk_accessors(
35 qw/counter request response state action stack namespace/
38 attributes->import( __PACKAGE__, \&namespace, 'lvalue' );
40 sub depth { scalar @{ shift->stack || [] }; }
47 # For backwards compatibility
48 *finalize_output = \&finalize_body;
53 our $RECURSION = 1000;
54 our $DETACH = "catalyst_detach\n";
56 require Module::Pluggable::Fast;
58 # Helper script generation
59 our $CATALYST_SCRIPT_GEN = 18;
61 __PACKAGE__->mk_classdata($_)
62 for qw/components arguments dispatcher engine log dispatcher_class
63 engine_class context_class request_class response_class/;
65 __PACKAGE__->dispatcher_class('Catalyst::Dispatcher');
66 __PACKAGE__->engine_class('Catalyst::Engine::CGI');
67 __PACKAGE__->request_class('Catalyst::Request');
68 __PACKAGE__->response_class('Catalyst::Response');
70 our $VERSION = '5.57';
73 my ( $class, @arguments ) = @_;
75 # We have to limit $class to Catalyst to avoid pushing Catalyst upon every
77 return unless $class eq 'Catalyst';
79 my $caller = caller(0);
81 unless ( $caller->isa('Catalyst') ) {
83 push @{"$caller\::ISA"}, $class;
86 $caller->arguments( [@arguments] );
92 Catalyst - The Elegant MVC Web Application Framework
96 # use the helper to start a new application
99 # add models, views, controllers
100 script/myapp_create.pl model Database DBIC dbi:SQLite:/path/to/db
101 script/myapp_create.pl view TT TT
102 script/myapp_create.pl controller Search
104 # built in testserver -- use -r to restart automatically on changes
105 script/myapp_server.pl
107 # command line testing interface
108 script/myapp_test.pl /yada
111 use Catalyst qw/-Debug/; # include plugins here as well
113 sub foo : Global { # called for /foo, /foo/1, /foo/1/2, etc.
114 my ( $self, $c, @args ) = @_; # args are qw/1 2/ for /foo/1/2
115 $c->stash->{template} = 'foo.tt'; # set the template
116 # lookup something from db -- stash vars are passed to TT
118 MyApp::Model::Database::Foo->search( { country => $args[0] } );
119 if ( $c->req->params->{bar} ) { # access GET or POST parameters
120 $c->forward( 'bar' ); # process another action
121 # do something else after forward returns
125 # The foo.tt TT template can use the stash data from the database
126 [% WHILE (item = data.next) %]
130 # called for /bar/of/soap, /bar/of/soap/10, etc.
131 sub bar : Path('/bar/of/soap') { ... }
133 # called for all actions, from the top-most controller downwards
135 my ( $self, $c ) = @_;
137 $c->res->redirect( '/login' ); # require login
138 return 0; # abort request and go immediately to end()
140 return 1; # success; carry on to next action
143 # called after all actions are finished
145 my ( $self, $c ) = @_;
146 if ( scalar @{ $c->error } ) { ... } # handle errors
147 return if $c->res->body; # already have a response
148 $c->forward( 'MyApp::View::TT' ); # render template
151 ### in MyApp/Controller/Foo.pm
152 # called for /foo/bar
153 sub bar : Local { ... }
155 # called for /blargle
156 sub blargle : Global { ... }
158 # an index action matches /foo, but not /foo/1, etc.
159 sub index : Private { ... }
161 ### in MyApp/Controller/Foo/Bar.pm
162 # called for /foo/bar/baz
163 sub baz : Local { ... }
165 # first MyApp auto is called, then Foo auto, then this
166 sub auto : Private { ... }
168 # powerful regular expression paths are also possible
169 sub details : Regex('^product/(\w+)/details$') {
170 my ( $self, $c ) = @_;
171 # extract the (\w+) from the URI
172 my $product = $c->req->snippets->[0];
175 See L<Catalyst::Manual::Intro> for additional information.
179 The key concept of Catalyst is DRY (Don't Repeat Yourself).
181 See L<Catalyst::Manual> for more documentation.
183 Catalyst plugins can be loaded by naming them as arguments to the "use
184 Catalyst" statement. Omit the C<Catalyst::Plugin::> prefix from the
185 plugin name, i.e., C<Catalyst::Plugin::My::Module> becomes
188 use Catalyst qw/My::Module/;
190 Special flags like C<-Debug> and C<-Engine> can also be specified as
191 arguments when Catalyst is loaded:
193 use Catalyst qw/-Debug My::Module/;
195 The position of plugins and flags in the chain is important, because
196 they are loaded in exactly the order in which they appear.
198 The following flags are supported:
204 Enables debug output.
208 Forces Catalyst to use a specific engine. Omit the
209 C<Catalyst::Engine::> prefix of the engine name, i.e.:
211 use Catalyst qw/-Engine=CGI/;
215 Forces Catalyst to use a specific home directory, e.g.:
217 use Catalyst qw[-Home=/usr/sri];
227 =head2 Information about the current request
233 Returns a L<Catalyst::Action> object for the current action, which
234 stringifies to the action name. See L<Catalyst::Action>.
238 Returns the namespace of the current action, i.e., the uri prefix
239 corresponding to the controller of the current action. For example:
241 # in Controller::Foo::Bar
242 $c->namespace; # returns 'foo/bar';
248 Returns the current L<Catalyst::Request> object. See
249 L<Catalyst::Request>.
253 =head2 Processing and response to the current request
257 =item $c->forward( $action [, \@arguments ] )
259 =item $c->forward( $class, $method, [, \@arguments ] )
261 Forwards processing to a private action. If you give a class name but no
262 method, C<process()> is called. You may also optionally pass arguments
263 in an arrayref. The action will receive the arguments in C<@_> and
264 C<$c-E<gt>req-E<gt>args>. Upon returning from the function,
265 C<$c-E<gt>req-E<gt>args> will be restored to the previous values.
268 $c->forward('index');
269 $c->forward(qw/MyApp::Model::CDBI::Foo do_stuff/);
270 $c->forward('MyApp::View::TT');
274 sub forward { my $c = shift; $c->dispatcher->forward( $c, @_ ) }
276 =item $c->detach( $action [, \@arguments ] )
278 =item $c->detach( $class, $method, [, \@arguments ] )
280 The same as C<forward>, but doesn't return.
284 sub detach { my $c = shift; $c->dispatcher->detach( $c, @_ ) }
288 =item $c->error($error, ...)
290 =item $c->error($arrayref)
292 Returns an arrayref containing error messages. If Catalyst encounters an
293 error while processing a request, it stores the error in $c->error. This
294 method should not be used to store non-fatal error messages.
296 my @error = @{ $c->error };
300 $c->error('Something bad happened');
302 Clear errors. You probably don't want to clear the errors unless you are
303 implementing a custom error screen.
312 my $error = ref $_[0] eq 'ARRAY' ? $_[0] : [@_];
313 push @{ $c->{error} }, @$error;
315 elsif ( defined $_[0] ) { $c->{error} = undef }
316 return $c->{error} || [];
323 Returns the current L<Catalyst::Response> object.
327 Returns a hashref to the stash, which may be used to store data and pass
328 it between components during a request. You can also set hash keys by
329 passing arguments. The stash is automatically sent to the view. The
330 stash is cleared at the end of a request; it cannot be used for
333 $c->stash->{foo} = $bar;
334 $c->stash( { moose => 'majestic', qux => 0 } );
335 $c->stash( bar => 1, gorch => 2 ); # equivalent to passing a hashref
337 # stash is automatically passed to the view for use in a template
338 $c->forward( 'MyApp::V::TT' );
345 my $stash = @_ > 1 ? {@_} : $_[0];
346 while ( my ( $key, $val ) = each %$stash ) {
347 $c->{stash}->{$key} = $val;
355 Contains the return value of the last executed action.
359 =head2 Component Accessors
363 =item $c->comp($name)
365 =item $c->component($name)
367 Gets a component object by name. This method is no longer recommended,
368 unless you want to get a specific component by full
369 class. C<$c-E<gt>controller>, C<$c-E<gt>model>, and C<$c-E<gt>view>
370 should be used instead.
381 my $appclass = ref $c || $c;
384 $name, "${appclass}::${name}",
385 map { "${appclass}::${_}::${name}" }
386 qw/Model M Controller C View V/
389 foreach my $try (@names) {
391 if ( exists $c->components->{$try} ) {
393 return $c->components->{$try};
397 foreach my $component ( keys %{ $c->components } ) {
399 return $c->components->{$component} if $component =~ /$name/i;
404 return sort keys %{ $c->components };
407 =item $c->controller($name)
409 Gets a L<Catalyst::Controller> instance by name.
411 $c->controller('Foo')->do_stuff;
416 my ( $c, $name ) = @_;
417 my $controller = $c->comp("Controller::$name");
418 return $controller if $controller;
419 return $c->comp("C::$name");
422 =item $c->model($name)
424 Gets a L<Catalyst::Model> instance by name.
426 $c->model('Foo')->do_stuff;
431 my ( $c, $name ) = @_;
432 my $model = $c->comp("Model::$name");
433 return $model if $model;
434 return $c->comp("M::$name");
437 =item $c->view($name)
439 Gets a L<Catalyst::View> instance by name.
441 $c->view('Foo')->do_stuff;
446 my ( $c, $name ) = @_;
447 my $view = $c->comp("View::$name");
448 return $view if $view;
449 return $c->comp("V::$name");
454 =head2 Class data and helper classes
460 Returns or takes a hashref containing the application's configuration.
462 __PACKAGE__->config({ db => 'dsn:SQLite:foo.db' });
466 Overload to enable debug messages (same as -Debug option).
474 Returns the dispatcher instance. Stringifies to class name. See
475 L<Catalyst::Dispatcher>.
479 Returns the engine instance. Stringifies to the class name. See
484 Returns the logging object instance. Unless it is already set, Catalyst
485 sets this up with a L<Catalyst::Log> object. To use your own log class:
487 $c->log( MyLogger->new );
488 $c->log->info( 'Now logging with my own logger!' );
490 Your log class should implement the methods described in the
491 L<Catalyst::Log> man page.
497 =head2 Utility methods
501 =item $c->path_to(@path)
503 Merges C<@path> with C<$c-E<gt>config-E<gt>{home}> and returns a
504 L<Path::Class> object.
508 $c->path_to( 'db', 'sqlite.db' );
513 my ( $c, @path ) = @_;
514 my $path = dir( $c->config->{home}, @path );
515 if ( -d $path ) { return $path }
516 else { return file( $c->config->{home}, @path ) }
519 =item $c->plugin( $name, $class, @args )
521 Helper method for plugins. It creates a classdata accessor/mutator and
522 loads and instantiates the given class.
524 MyApp->plugin( 'prototype', 'HTML::Prototype' );
526 $c->prototype->define_javascript_functions;
531 my ( $class, $name, $plugin, @args ) = @_;
534 if ( my $error = $UNIVERSAL::require::ERROR ) {
535 Catalyst::Exception->throw(
536 message => qq/Couldn't load instant plugin "$plugin", "$error"/ );
539 eval { $plugin->import };
540 $class->mk_classdata($name);
542 eval { $obj = $plugin->new(@args) };
545 Catalyst::Exception->throw( message =>
546 qq/Couldn't instantiate instant plugin "$plugin", "$@"/ );
550 $class->log->debug(qq/Initialized instant plugin "$plugin" as "$name"/)
556 Initializes the dispatcher and engine, loads any plugins, and loads the
557 model, view, and controller components. You may also specify an array
558 of plugins to load here, if you choose to not load them in the C<use
562 MyApp->setup( qw/-Debug/ );
567 my ( $class, @arguments ) = @_;
569 unless ( $class->isa('Catalyst') ) {
571 Catalyst::Exception->throw(
572 message => qq/'$class' does not inherit from Catalyst/ );
575 if ( $class->arguments ) {
576 @arguments = ( @arguments, @{ $class->arguments } );
582 foreach (@arguments) {
586 ( $flags->{log} ) ? 'debug,' . $flags->{log} : 'debug';
588 elsif (/^-(\w+)=?(.*)$/) {
589 $flags->{ lc $1 } = $2;
592 push @{ $flags->{plugins} }, $_;
596 $class->setup_log( delete $flags->{log} );
597 $class->setup_plugins( delete $flags->{plugins} );
598 $class->setup_dispatcher( delete $flags->{dispatcher} );
599 $class->setup_engine( delete $flags->{engine} );
600 $class->setup_home( delete $flags->{home} );
602 for my $flag ( sort keys %{$flags} ) {
604 if ( my $code = $class->can( 'setup_' . $flag ) ) {
605 &$code( $class, delete $flags->{$flag} );
608 $class->log->warn(qq/Unknown flag "$flag"/);
613 <<"EOF") if ( $ENV{CATALYST_SCRIPT_GEN} && ( $ENV{CATALYST_SCRIPT_GEN} < $Catalyst::CATALYST_SCRIPT_GEN ) );
614 You are running an old script!
616 Please update by running (this will overwrite existing files):
617 catalyst.pl -force -scripts $class
619 or (this will not overwrite existing files):
620 catalyst.pl -scripts $class
623 if ( $class->debug ) {
629 @plugins = grep { /^Catalyst::Plugin/ } @{"$class\::ISA"};
633 my $t = Text::SimpleTable->new(76);
634 $t->row($_) for @plugins;
635 $class->log->debug( "Loaded plugins:\n" . $t->draw );
638 my $dispatcher = $class->dispatcher;
639 my $engine = $class->engine;
640 my $home = $class->config->{home};
642 $class->log->debug(qq/Loaded dispatcher "$dispatcher"/);
643 $class->log->debug(qq/Loaded engine "$engine"/);
647 ? $class->log->debug(qq/Found home "$home"/)
648 : $class->log->debug(qq/Home "$home" doesn't exist/)
649 : $class->log->debug(q/Couldn't find home/);
654 no warnings qw/redefine/;
655 local *setup = sub { };
659 # Initialize our data structure
660 $class->components( {} );
662 $class->setup_components;
664 if ( $class->debug ) {
665 my $t = Text::SimpleTable->new( [ 65, 'Class' ], [ 8, 'Type' ] );
666 for my $comp ( sort keys %{ $class->components } ) {
667 my $type = ref $class->components->{$comp} ? 'instance' : 'class';
668 $t->row( $comp, $type );
670 $class->log->debug( "Loaded components:\n" . $t->draw )
671 if ( keys %{ $class->components } );
674 # Add our self to components, since we are also a component
675 $class->components->{$class} = $class;
677 $class->setup_actions;
679 if ( $class->debug ) {
680 my $name = $class->config->{name} || 'Application';
681 $class->log->info("$name powered by Catalyst $Catalyst::VERSION");
683 $class->log->_flush() if $class->log->can('_flush');
686 =item $c->uri_for( $path, [ @args ] )
688 Merges path with C<$c-E<gt>request-E<gt>base> for absolute uri's and
689 with C<$c-E<gt>namespace> for relative uri's, then returns a
690 normalized L<URI> object. If any args are passed, they are added at the
696 my ( $c, $path, @args ) = @_;
697 my $base = $c->request->base->clone;
698 my $basepath = $base->path;
699 $basepath =~ s/\/$//;
701 my $namespace = $c->namespace;
703 # massage namespace, empty if absolute path
704 $namespace =~ s/^\///;
705 $namespace .= '/' if $namespace;
707 $namespace = '' if $path =~ /^\//;
710 # join args with '/', or a blank string
711 my $args = ( scalar @args ? '/' . join( '/', @args ) : '' );
712 return URI->new_abs( URI->new_abs( "$path$args", "$basepath$namespace" ),
716 =item $c->welcome_message
718 Returns the Catalyst welcome HTML page.
722 sub welcome_message {
724 my $name = $c->config->{name};
725 my $logo = $c->uri_for('/static/images/catalyst_logo.png');
726 my $prefix = Catalyst::Utils::appprefix( ref $c );
727 $c->response->content_type('text/html; charset=utf-8');
729 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
730 "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
731 <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
733 <meta http-equiv="Content-Language" content="en" />
734 <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
735 <title>$name on Catalyst $VERSION</title>
736 <style type="text/css">
739 background-color: #eee;
748 background-color: #ccc;
749 border: 1px solid #aaa;
750 -moz-border-radius: 10px;
755 font-family: verdana, tahoma, sans-serif;
758 font-family: verdana, tahoma, sans-serif;
761 text-decoration: none;
763 border-bottom: 1px dotted #bbb;
765 :link:hover, :visited:hover {
778 background-color: #fff;
779 border: 1px solid #aaa;
780 -moz-border-radius: 10px;
806 <h1><span id="appname">$name</span> on <a href="http://catalyst.perl.org">Catalyst</a>
811 <img src="$logo" alt="Catalyst Logo" />
813 <p>Welcome to the wonderful world of Catalyst.
814 This <a href="http://en.wikipedia.org/wiki/MVC">MVC</a>
815 framework will make web development something you had
816 never expected it to be: Fun, rewarding and quick.</p>
817 <h2>What to do now?</h2>
818 <p>That really depends on what <b>you</b> want to do.
819 We do, however, provide you with a few starting points.</p>
820 <p>If you want to jump right into web development with Catalyst
821 you might want to check out the documentation.</p>
822 <pre><code>perldoc <a href="http://cpansearch.perl.org/dist/Catalyst/lib/Catalyst/Manual/Intro.pod">Catalyst::Manual::Intro</a>
823 perldoc <a href="http://cpansearch.perl.org/dist/Catalyst/lib/Catalyst/Manual.pod">Catalyst::Manual</a></code></pre>
824 <h2>What to do next?</h2>
825 <p>Next it's time to write an actual application. Use the
826 helper scripts to generate <a href="http://cpansearch.perl.org/search?query=Catalyst%3A%3AController%3A%3A&mode=all">controllers</a>,
827 <a href="http://cpansearch.perl.org/search?query=Catalyst%3A%3AModel%3A%3A&mode=all">models</a> and
828 <a href="http://cpansearch.perl.org/search?query=Catalyst%3A%3AView%3A%3A&mode=all">views</a>,
829 they can save you a lot of work.</p>
830 <pre><code>script/${prefix}_create.pl -help</code></pre>
831 <p>Also, be sure to check out the vast and growing
832 collection of <a href="http://cpansearch.perl.org/search?query=Catalyst%3A%3APlugin%3A%3A&mode=all">plugins for Catalyst on CPAN</a>,
833 you are likely to find what you need there.
837 <p>Catalyst has a very active community. Here are the main places to
838 get in touch with us.</p>
841 <a href="http://dev.catalyst.perl.org">Wiki</a>
844 <a href="http://lists.rawmode.org/mailman/listinfo/catalyst">Mailing-List</a>
847 <a href="irc://irc.perl.org/catalyst">IRC channel #catalyst on irc.perl.org</a>
850 <h2>In conclusion</h2>
851 <p>The Catalyst team hopes you will enjoy using Catalyst as much
852 as we enjoyed making it. Please contact us if you have ideas
853 for improvement or other feedback.</p>
863 =head1 INTERNAL METHODS
865 These methods are not meant to be used by end users.
871 Returns a hash of components.
873 =item $c->context_class
875 Returns or sets the context class.
879 Returns a hashref containing coderefs and execution counts (needed for
880 deep recursion detection).
884 Returns the number of actions on the current internal execution stack.
888 Dispatches a request to actions.
892 sub dispatch { my $c = shift; $c->dispatcher->dispatch( $c, @_ ) }
894 =item $c->dispatcher_class
896 Returns or sets the dispatcher class.
900 Returns a list of 2-element array references (name, structure) pairs
901 that will be dumped on the error page in debug mode.
907 [ Request => $c->req ], [ Response => $c->res ], [ Stash => $c->stash ],;
910 =item $c->engine_class
912 Returns or sets the engine class.
914 =item $c->execute( $class, $coderef )
916 Execute a coderef in given class and catch exceptions. Errors are available
922 my ( $c, $class, $code ) = @_;
923 $class = $c->components->{$class} || $class;
927 ( caller(0) )[0]->isa('Catalyst::Action')
934 $action = "/$action" unless $action =~ /\-\>/;
935 $c->counter->{"$code"}++;
937 if ( $c->counter->{"$code"} > $RECURSION ) {
938 my $error = qq/Deep recursion detected in "$action"/;
939 $c->log->error($error);
945 $action = "-> $action" if $callsub =~ /forward$/;
947 push( @{ $c->stack }, $code );
950 $start = [gettimeofday] if $c->debug;
951 eval { $c->state( &$code( $class, $c, @{ $c->req->args } ) || 0 ) };
952 $elapsed = tv_interval($start) if $c->debug;
955 unless ( ( $code->name =~ /^_.*/ )
956 && ( !$c->config->{show_internal_actions} ) )
958 push @{ $c->{stats} }, [ $action, sprintf( '%fs', $elapsed ) ];
961 pop( @{ $c->stack } );
963 if ( my $error = $@ ) {
965 if ( $error eq $DETACH ) { die $DETACH if $c->depth > 1 }
967 unless ( ref $error ) {
969 $error = qq/Caught exception "$error"/;
980 Finalizes the request.
987 for my $error ( @{ $c->error } ) {
988 $c->log->error($error);
991 $c->finalize_uploads;
994 if ( $#{ $c->error } >= 0 ) {
998 $c->finalize_headers;
1001 if ( $c->request->method eq 'HEAD' ) {
1002 $c->response->body('');
1007 return $c->response->status;
1010 =item $c->finalize_body
1016 sub finalize_body { my $c = shift; $c->engine->finalize_body( $c, @_ ) }
1018 =item $c->finalize_cookies
1024 sub finalize_cookies { my $c = shift; $c->engine->finalize_cookies( $c, @_ ) }
1026 =item $c->finalize_error
1032 sub finalize_error { my $c = shift; $c->engine->finalize_error( $c, @_ ) }
1034 =item $c->finalize_headers
1040 sub finalize_headers {
1043 # Check if we already finalized headers
1044 return if $c->response->{_finalized_headers};
1047 if ( my $location = $c->response->redirect ) {
1048 $c->log->debug(qq/Redirecting to "$location"/) if $c->debug;
1049 $c->response->header( Location => $location );
1053 if ( $c->response->body && !$c->response->content_length ) {
1054 $c->response->content_length( bytes::length( $c->response->body ) );
1058 if ( $c->response->status =~ /^(1\d\d|[23]04)$/ ) {
1059 $c->response->headers->remove_header("Content-Length");
1060 $c->response->body('');
1063 $c->finalize_cookies;
1065 $c->engine->finalize_headers( $c, @_ );
1068 $c->response->{_finalized_headers} = 1;
1071 =item $c->finalize_output
1073 An alias for finalize_body.
1075 =item $c->finalize_read
1077 Finalizes the input after reading is complete.
1081 sub finalize_read { my $c = shift; $c->engine->finalize_read( $c, @_ ) }
1083 =item $c->finalize_uploads
1085 Finalizes uploads. Cleans up any temporary files.
1089 sub finalize_uploads { my $c = shift; $c->engine->finalize_uploads( $c, @_ ) }
1091 =item $c->get_action( $action, $namespace )
1093 Gets an action in a given namespace.
1097 sub get_action { my $c = shift; $c->dispatcher->get_action(@_) }
1099 =item $c->get_actions( $action, $namespace )
1101 Gets all actions of a given name in a namespace and all parent
1106 sub get_actions { my $c = shift; $c->dispatcher->get_actions( $c, @_ ) }
1108 =item handle_request( $class, @arguments )
1110 Called to handle each HTTP request.
1114 sub handle_request {
1115 my ( $class, @arguments ) = @_;
1117 # Always expect worst case!
1123 my $c = $class->prepare(@arguments);
1124 $c->{stats} = \@stats;
1126 return $c->finalize;
1129 if ( $class->debug ) {
1130 my $start = [gettimeofday];
1131 $status = &$handler;
1132 my $elapsed = tv_interval $start;
1133 $elapsed = sprintf '%f', $elapsed;
1134 my $av = sprintf '%.3f',
1135 ( $elapsed == 0 ? '??' : ( 1 / $elapsed ) );
1136 my $t = Text::SimpleTable->new( [ 64, 'Action' ], [ 9, 'Time' ] );
1138 for my $stat (@stats) { $t->row( $stat->[0], $stat->[1] ) }
1140 "Request took ${elapsed}s ($av/s)\n" . $t->draw );
1142 else { $status = &$handler }
1146 if ( my $error = $@ ) {
1148 $class->log->error(qq/Caught exception in engine "$error"/);
1152 $class->log->_flush() if $class->log->can('_flush');
1156 =item $c->prepare( @arguments )
1158 Creates a Catalyst context from an engine-specific request (Apache, CGI,
1164 my ( $class, @arguments ) = @_;
1166 $class->context_class( ref $class || $class ) unless $class->context_class;
1167 my $c = $class->context_class->new(
1171 request => $class->request_class->new(
1174 body_parameters => {},
1176 headers => HTTP::Headers->new,
1178 query_parameters => {},
1184 response => $class->response_class->new(
1188 headers => HTTP::Headers->new(),
1197 # For on-demand data
1198 $c->request->{_context} = $c;
1199 $c->response->{_context} = $c;
1200 weaken( $c->request->{_context} );
1201 weaken( $c->response->{_context} );
1204 my $secs = time - $START || 1;
1205 my $av = sprintf '%.3f', $COUNT / $secs;
1206 $c->log->debug('**********************************');
1207 $c->log->debug("* Request $COUNT ($av/s) [$$]");
1208 $c->log->debug('**********************************');
1209 $c->res->headers->header( 'X-Catalyst' => $Catalyst::VERSION );
1212 $c->prepare_request(@arguments);
1213 $c->prepare_connection;
1214 $c->prepare_query_parameters;
1215 $c->prepare_headers;
1216 $c->prepare_cookies;
1220 $c->prepare_body unless $c->config->{parse_on_demand};
1222 my $method = $c->req->method || '';
1223 my $path = $c->req->path || '';
1224 my $address = $c->req->address || '';
1226 $c->log->debug(qq/"$method" request for "$path" from "$address"/)
1234 =item $c->prepare_action
1240 sub prepare_action { my $c = shift; $c->dispatcher->prepare_action( $c, @_ ) }
1242 =item $c->prepare_body
1244 Prepares message body.
1251 # Do we run for the first time?
1252 return if defined $c->request->{_body};
1254 # Initialize on-demand data
1255 $c->engine->prepare_body( $c, @_ );
1256 $c->prepare_parameters;
1257 $c->prepare_uploads;
1259 if ( $c->debug && keys %{ $c->req->body_parameters } ) {
1260 my $t = Text::SimpleTable->new( [ 37, 'Key' ], [ 36, 'Value' ] );
1261 for my $key ( sort keys %{ $c->req->body_parameters } ) {
1262 my $param = $c->req->body_parameters->{$key};
1263 my $value = defined($param) ? $param : '';
1265 ref $value eq 'ARRAY' ? ( join ', ', @$value ) : $value );
1267 $c->log->debug( "Body Parameters are:\n" . $t->draw );
1271 =item $c->prepare_body_chunk( $chunk )
1273 Prepares a chunk of data before sending it to L<HTTP::Body>.
1277 sub prepare_body_chunk {
1279 $c->engine->prepare_body_chunk( $c, @_ );
1282 =item $c->prepare_body_parameters
1284 Prepares body parameters.
1288 sub prepare_body_parameters {
1290 $c->engine->prepare_body_parameters( $c, @_ );
1293 =item $c->prepare_connection
1295 Prepares connection.
1299 sub prepare_connection {
1301 $c->engine->prepare_connection( $c, @_ );
1304 =item $c->prepare_cookies
1310 sub prepare_cookies { my $c = shift; $c->engine->prepare_cookies( $c, @_ ) }
1312 =item $c->prepare_headers
1318 sub prepare_headers { my $c = shift; $c->engine->prepare_headers( $c, @_ ) }
1320 =item $c->prepare_parameters
1322 Prepares parameters.
1326 sub prepare_parameters {
1328 $c->prepare_body_parameters;
1329 $c->engine->prepare_parameters( $c, @_ );
1332 =item $c->prepare_path
1334 Prepares path and base.
1338 sub prepare_path { my $c = shift; $c->engine->prepare_path( $c, @_ ) }
1340 =item $c->prepare_query_parameters
1342 Prepares query parameters.
1346 sub prepare_query_parameters {
1349 $c->engine->prepare_query_parameters( $c, @_ );
1351 if ( $c->debug && keys %{ $c->request->query_parameters } ) {
1352 my $t = Text::SimpleTable->new( [ 37, 'Key' ], [ 36, 'Value' ] );
1353 for my $key ( sort keys %{ $c->req->query_parameters } ) {
1354 my $param = $c->req->query_parameters->{$key};
1355 my $value = defined($param) ? $param : '';
1357 ref $value eq 'ARRAY' ? ( join ', ', @$value ) : $value );
1359 $c->log->debug( "Query Parameters are:\n" . $t->draw );
1363 =item $c->prepare_read
1365 Prepares the input for reading.
1369 sub prepare_read { my $c = shift; $c->engine->prepare_read( $c, @_ ) }
1371 =item $c->prepare_request
1373 Prepares the engine request.
1377 sub prepare_request { my $c = shift; $c->engine->prepare_request( $c, @_ ) }
1379 =item $c->prepare_uploads
1385 sub prepare_uploads {
1388 $c->engine->prepare_uploads( $c, @_ );
1390 if ( $c->debug && keys %{ $c->request->uploads } ) {
1391 my $t = Text::SimpleTable->new(
1397 for my $key ( sort keys %{ $c->request->uploads } ) {
1398 my $upload = $c->request->uploads->{$key};
1399 for my $u ( ref $upload eq 'ARRAY' ? @{$upload} : ($upload) ) {
1400 $t->row( $key, $u->filename, $u->type, $u->size );
1403 $c->log->debug( "File Uploads are:\n" . $t->draw );
1407 =item $c->prepare_write
1409 Prepares the output for writing.
1413 sub prepare_write { my $c = shift; $c->engine->prepare_write( $c, @_ ) }
1415 =item $c->request_class
1417 Returns or sets the request class.
1419 =item $c->response_class
1421 Returns or sets the response class.
1423 =item $c->read( [$maxlength] )
1425 Reads a chunk of data from the request body. This method is designed to
1426 be used in a while loop, reading C<$maxlength> bytes on every call.
1427 C<$maxlength> defaults to the size of the request if not specified.
1429 You have to set C<MyApp-E<gt>config-E<gt>{parse_on_demand}> to use this
1434 sub read { my $c = shift; return $c->engine->read( $c, @_ ) }
1442 sub run { my $c = shift; return $c->engine->run( $c, @_ ) }
1444 =item $c->set_action( $action, $code, $namespace, $attrs )
1446 Sets an action in a given namespace.
1450 sub set_action { my $c = shift; $c->dispatcher->set_action( $c, @_ ) }
1452 =item $c->setup_actions($component)
1454 Sets up actions for a component.
1458 sub setup_actions { my $c = shift; $c->dispatcher->setup_actions( $c, @_ ) }
1460 =item $c->setup_components
1466 sub setup_components {
1469 my $callback = sub {
1470 my ( $component, $context ) = @_;
1472 unless ( $component->isa('Catalyst::Component') ) {
1476 my $suffix = Catalyst::Utils::class2classsuffix($component);
1477 my $config = $class->config->{$suffix} || {};
1481 eval { $instance = $component->new( $context, $config ); };
1483 if ( my $error = $@ ) {
1487 Catalyst::Exception->throw( message =>
1488 qq/Couldn't instantiate component "$component", "$error"/ );
1491 Catalyst::Exception->throw( message =>
1492 qq/Couldn't instantiate component "$component", "new() didn't return a object"/
1494 unless ref $instance;
1498 eval "package $class;\n" . q!Module::Pluggable::Fast->import(
1499 name => '_catalyst_components',
1501 "$class\::Controller", "$class\::C",
1502 "$class\::Model", "$class\::M",
1503 "$class\::View", "$class\::V"
1505 callback => $callback
1509 if ( my $error = $@ ) {
1513 Catalyst::Exception->throw(
1514 message => qq/Couldn't load components "$error"/ );
1517 for my $component ( $class->_catalyst_components($class) ) {
1518 $class->components->{ ref $component || $component } = $component;
1522 =item $c->setup_dispatcher
1528 sub setup_dispatcher {
1529 my ( $class, $dispatcher ) = @_;
1532 $dispatcher = 'Catalyst::Dispatcher::' . $dispatcher;
1535 if ( $ENV{CATALYST_DISPATCHER} ) {
1536 $dispatcher = 'Catalyst::Dispatcher::' . $ENV{CATALYST_DISPATCHER};
1539 if ( $ENV{ uc($class) . '_DISPATCHER' } ) {
1541 'Catalyst::Dispatcher::' . $ENV{ uc($class) . '_DISPATCHER' };
1544 unless ($dispatcher) {
1545 $dispatcher = $class->dispatcher_class;
1548 $dispatcher->require;
1551 Catalyst::Exception->throw(
1552 message => qq/Couldn't load dispatcher "$dispatcher", "$@"/ );
1555 # dispatcher instance
1556 $class->dispatcher( $dispatcher->new );
1559 =item $c->setup_engine
1566 my ( $class, $engine ) = @_;
1569 $engine = 'Catalyst::Engine::' . $engine;
1572 if ( $ENV{CATALYST_ENGINE} ) {
1573 $engine = 'Catalyst::Engine::' . $ENV{CATALYST_ENGINE};
1576 if ( $ENV{ uc($class) . '_ENGINE' } ) {
1577 $engine = 'Catalyst::Engine::' . $ENV{ uc($class) . '_ENGINE' };
1580 if ( !$engine && $ENV{MOD_PERL} ) {
1582 # create the apache method
1585 *{"$class\::apache"} = sub { shift->engine->apache };
1588 my ( $software, $version ) =
1589 $ENV{MOD_PERL} =~ /^(\S+)\/(\d+(?:[\.\_]\d+)+)/;
1592 $version =~ s/(\.[^.]+)\./$1/g;
1594 if ( $software eq 'mod_perl' ) {
1596 if ( $version >= 1.99922 ) {
1597 $engine = 'Catalyst::Engine::Apache2::MP20';
1600 elsif ( $version >= 1.9901 ) {
1601 $engine = 'Catalyst::Engine::Apache2::MP19';
1604 elsif ( $version >= 1.24 ) {
1605 $engine = 'Catalyst::Engine::Apache::MP13';
1609 Catalyst::Exception->throw( message =>
1610 qq/Unsupported mod_perl version: $ENV{MOD_PERL}/ );
1613 # install the correct mod_perl handler
1614 if ( $version >= 1.9901 ) {
1615 *handler = sub : method {
1616 shift->handle_request(@_);
1620 *handler = sub ($$) { shift->handle_request(@_) };
1625 elsif ( $software eq 'Zeus-Perl' ) {
1626 $engine = 'Catalyst::Engine::Zeus';
1630 Catalyst::Exception->throw(
1631 message => qq/Unsupported mod_perl: $ENV{MOD_PERL}/ );
1636 $engine = $class->engine_class;
1642 Catalyst::Exception->throw( message =>
1643 qq/Couldn't load engine "$engine" (maybe you forgot to install it?), "$@"/
1647 # check for old engines that are no longer compatible
1649 if ( $engine->isa('Catalyst::Engine::Apache')
1650 && !Catalyst::Engine::Apache->VERSION )
1655 elsif ( $engine->isa('Catalyst::Engine::Server::Base')
1656 && Catalyst::Engine::Server->VERSION le '0.02' )
1661 elsif ($engine->isa('Catalyst::Engine::HTTP::POE')
1662 && $engine->VERSION eq '0.01' )
1667 elsif ($engine->isa('Catalyst::Engine::Zeus')
1668 && $engine->VERSION eq '0.01' )
1674 Catalyst::Exception->throw( message =>
1675 qq/Engine "$engine" is not supported by this version of Catalyst/
1680 $class->engine( $engine->new );
1683 =item $c->setup_home
1685 Sets up the home directory.
1690 my ( $class, $home ) = @_;
1692 if ( $ENV{CATALYST_HOME} ) {
1693 $home = $ENV{CATALYST_HOME};
1696 if ( $ENV{ uc($class) . '_HOME' } ) {
1697 $home = $ENV{ uc($class) . '_HOME' };
1701 $home = Catalyst::Utils::home($class);
1705 $class->config->{home} ||= $home;
1706 $class->config->{root} ||= dir($home)->subdir('root');
1717 my ( $class, $debug ) = @_;
1719 unless ( $class->log ) {
1720 $class->log( Catalyst::Log->new );
1723 my $app_flag = Catalyst::Utils::class2env($class) . '_DEBUG';
1726 ( defined( $ENV{CATALYST_DEBUG} ) || defined( $ENV{$app_flag} ) )
1727 ? ( $ENV{CATALYST_DEBUG} || $ENV{$app_flag} )
1732 *{"$class\::debug"} = sub { 1 };
1733 $class->log->debug('Debug messages enabled');
1737 =item $c->setup_plugins
1744 my ( $class, $plugins ) = @_;
1747 for my $plugin ( reverse @$plugins ) {
1749 $plugin = "Catalyst::Plugin::$plugin";
1754 Catalyst::Exception->throw(
1755 message => qq/Couldn't load plugin "$plugin", "$@"/ );
1760 unshift @{"$class\::ISA"}, $plugin;
1769 =item $c->write( $data )
1771 Writes $data to the output stream. When using this method directly, you
1772 will need to manually set the C<Content-Length> header to the length of
1773 your output data, if known.
1780 # Finalize headers if someone manually writes output
1781 $c->finalize_headers;
1783 return $c->engine->write( $c, @_ );
1788 Returns the Catalyst version number. Mostly useful for "powered by"
1789 messages in template systems.
1793 sub version { return $Catalyst::VERSION }
1797 =head1 INTERNAL ACTIONS
1799 Catalyst uses internal actions like C<_DISPATCH>, C<_BEGIN>, C<_AUTO>,
1800 C<_ACTION>, and C<_END>. These are by default not shown in the private
1801 action table, but you can make them visible with a config parameter.
1803 MyApp->config->{show_internal_actions} = 1;
1805 =head1 CASE SENSITIVITY
1807 By default Catalyst is not case sensitive, so C<MyApp::C::FOO::Bar> is
1808 mapped to C</foo/bar>. You can activate case sensitivity with a config
1811 MyApp->config->{case_sensitive} = 1;
1813 This causes C<MyApp::C::Foo::Bar> to map to C</Foo/Bar>.
1815 =head1 ON-DEMAND PARSER
1817 The request body is usually parsed at the beginning of a request,
1818 but if you want to handle input yourself or speed things up a bit,
1819 you can enable on-demand parsing with a config parameter.
1821 MyApp->config->{parse_on_demand} = 1;
1823 =head1 PROXY SUPPORT
1825 Many production servers operate using the common double-server approach,
1826 with a lightweight frontend web server passing requests to a larger
1827 backend server. An application running on the backend server must deal
1828 with two problems: the remote user always appears to be C<127.0.0.1> and
1829 the server's hostname will appear to be C<localhost> regardless of the
1830 virtual host that the user connected through.
1832 Catalyst will automatically detect this situation when you are running
1833 the frontend and backend servers on the same machine. The following
1834 changes are made to the request.
1836 $c->req->address is set to the user's real IP address, as read from
1837 the HTTP X-Forwarded-For header.
1839 The host value for $c->req->base and $c->req->uri is set to the real
1840 host, as read from the HTTP X-Forwarded-Host header.
1842 Obviously, your web server must support these headers for this to work.
1844 In a more complex server farm environment where you may have your
1845 frontend proxy server(s) on different machines, you will need to set a
1846 configuration option to tell Catalyst to read the proxied data from the
1849 MyApp->config->{using_frontend_proxy} = 1;
1851 If you do not wish to use the proxy support at all, you may set:
1853 MyApp->config->{ignore_frontend_proxy} = 1;
1855 =head1 THREAD SAFETY
1857 Catalyst has been tested under Apache 2's threading mpm_worker, mpm_winnt,
1858 and the standalone forking HTTP server on Windows. We believe the Catalyst
1859 core to be thread-safe.
1861 If you plan to operate in a threaded environment, remember that all other
1862 modules you are using must also be thread-safe. Some modules, most notably
1863 L<DBD::SQLite>, are not thread-safe.
1869 Join #catalyst on irc.perl.org.
1873 http://lists.rawmode.org/mailman/listinfo/catalyst
1874 http://lists.rawmode.org/mailman/listinfo/catalyst-dev
1878 http://catalyst.perl.org
1882 http://dev.catalyst.perl.org
1888 =item L<Catalyst::Manual> - The Catalyst Manual
1890 =item L<Catalyst::Component>, L<Catalyst::Base> - Base classes for components
1892 =item L<Catalyst::Engine> - Core engine
1894 =item L<Catalyst::Log> - Log class.
1896 =item L<Catalyst::Request> - Request object
1898 =item L<Catalyst::Response> - Response object
1900 =item L<Catalyst::Test> - The test suite.
1972 Sebastian Riedel, C<sri@oook.de>
1976 This library is free software, you can redistribute it and/or modify it under
1977 the same terms as Perl itself.