3 # we don't need really need this, but if we load it before MRO::Compat gets
4 # loaded (via Moose and Class::MOP), we can avoid some nasty warnings
8 use Class::MOP::Object ();
9 extends 'Catalyst::Component';
11 use Catalyst::Exception;
13 use Catalyst::Request;
14 use Catalyst::Request::Upload;
15 use Catalyst::Response;
17 use Catalyst::Controller;
18 use Devel::InnerPackage ();
20 use Module::Pluggable::Object ();
21 use Text::SimpleTable ();
22 use Path::Class::Dir ();
23 use Path::Class::File ();
24 use Time::HiRes qw/gettimeofday tv_interval/;
28 use Scalar::Util qw/weaken blessed/;
29 use Tree::Simple qw/use_weak_refs/;
30 use Tree::Simple::Visitor::FindByUID;
33 use Carp qw/croak carp/;
35 BEGIN { require 5.008001; }
37 # FIXME lazy => 1 here makes C::P::Auth tests pass?!?
38 has stack => (is => 'ro', default => sub { [] });
39 has stash => (is => 'rw', default => sub { {} });
40 has state => (is => 'rw', default => 0);
41 has stats => (is => 'rw');
42 has action => (is => 'rw');
43 has counter => (is => 'rw', default => sub { {} });
44 has request => (is => 'rw', default => sub { $_[0]->request_class->new({}) }, required => 1, lazy => 1);
45 has response => (is => 'rw', default => sub { $_[0]->response_class->new({}) }, required => 1, lazy => 1);
46 has namespace => (is => 'rw');
48 sub depth { scalar @{ shift->stack || [] }; }
49 sub comp { shift->component(@_) }
52 # carp "the use of req() is deprecated in favour of request()";
53 my $self = shift; return $self->request(@_);
56 # carp "the use of res() is deprecated in favour of response()";
57 my $self = shift; return $self->response(@_);
60 # For backwards compatibility
61 sub finalize_output { shift->finalize_body(@_) };
66 our $RECURSION = 1000;
67 our $DETACH = "catalyst_detach\n";
68 our $GO = "catalyst_go\n";
70 #I imagine that very few of these really need to be class variables. if any.
71 #maybe we should just make them attributes with a default?
72 __PACKAGE__->mk_classdata($_)
73 for qw/components arguments dispatcher engine log dispatcher_class
74 engine_class context_class request_class response_class stats_class
77 __PACKAGE__->dispatcher_class('Catalyst::Dispatcher');
78 __PACKAGE__->engine_class('Catalyst::Engine::CGI');
79 __PACKAGE__->request_class('Catalyst::Request');
80 __PACKAGE__->response_class('Catalyst::Response');
81 __PACKAGE__->stats_class('Catalyst::Stats');
83 # Remember to update this in Catalyst::Runtime as well!
85 our $VERSION = '5.8000_04';
88 my ( $class, @arguments ) = @_;
90 # We have to limit $class to Catalyst to avoid pushing Catalyst upon every
92 return unless $class eq 'Catalyst';
94 my $caller = caller();
95 return if $caller eq 'main';
96 my $meta = Moose::Meta::Class->initialize($caller);
97 #Moose->import({ into => $caller }); #do we want to do this?
99 unless ( $caller->isa('Catalyst') ) {
100 my @superclasses = ($meta->superclasses, $class, 'Catalyst::Controller');
101 $meta->superclasses(@superclasses);
103 unless( $meta->has_method('meta') ){
104 $meta->add_method(meta => sub { Moose::Meta::Class->initialize("${caller}") } );
107 $caller->arguments( [@arguments] );
113 Catalyst - The Elegant MVC Web Application Framework
117 See the L<Catalyst::Manual> distribution for comprehensive
118 documentation and tutorials.
120 # Install Catalyst::Devel for helpers and other development tools
121 # use the helper to create a new application
124 # add models, views, controllers
125 script/myapp_create.pl model MyDatabase DBIC::Schema create=static dbi:SQLite:/path/to/db
126 script/myapp_create.pl view MyTemplate TT
127 script/myapp_create.pl controller Search
129 # built in testserver -- use -r to restart automatically on changes
130 # --help to see all available options
131 script/myapp_server.pl
133 # command line testing interface
134 script/myapp_test.pl /yada
137 use Catalyst qw/-Debug/; # include plugins here as well
139 ### In lib/MyApp/Controller/Root.pm (autocreated)
140 sub foo : Global { # called for /foo, /foo/1, /foo/1/2, etc.
141 my ( $self, $c, @args ) = @_; # args are qw/1 2/ for /foo/1/2
142 $c->stash->{template} = 'foo.tt'; # set the template
143 # lookup something from db -- stash vars are passed to TT
145 $c->model('Database::Foo')->search( { country => $args[0] } );
146 if ( $c->req->params->{bar} ) { # access GET or POST parameters
147 $c->forward( 'bar' ); # process another action
148 # do something else after forward returns
152 # The foo.tt TT template can use the stash data from the database
153 [% WHILE (item = data.next) %]
157 # called for /bar/of/soap, /bar/of/soap/10, etc.
158 sub bar : Path('/bar/of/soap') { ... }
160 # called for all actions, from the top-most controller downwards
162 my ( $self, $c ) = @_;
163 if ( !$c->user_exists ) { # Catalyst::Plugin::Authentication
164 $c->res->redirect( '/login' ); # require login
165 return 0; # abort request and go immediately to end()
167 return 1; # success; carry on to next action
170 # called after all actions are finished
172 my ( $self, $c ) = @_;
173 if ( scalar @{ $c->error } ) { ... } # handle errors
174 return if $c->res->body; # already have a response
175 $c->forward( 'MyApp::View::TT' ); # render template
178 ### in MyApp/Controller/Foo.pm
179 # called for /foo/bar
180 sub bar : Local { ... }
182 # called for /blargle
183 sub blargle : Global { ... }
185 # an index action matches /foo, but not /foo/1, etc.
186 sub index : Private { ... }
188 ### in MyApp/Controller/Foo/Bar.pm
189 # called for /foo/bar/baz
190 sub baz : Local { ... }
192 # first Root auto is called, then Foo auto, then this
193 sub auto : Private { ... }
195 # powerful regular expression paths are also possible
196 sub details : Regex('^product/(\w+)/details$') {
197 my ( $self, $c ) = @_;
198 # extract the (\w+) from the URI
199 my $product = $c->req->captures->[0];
202 See L<Catalyst::Manual::Intro> for additional information.
206 Catalyst is a modern framework for making web applications without the
207 pain usually associated with this process. This document is a reference
208 to the main Catalyst application. If you are a new user, we suggest you
209 start with L<Catalyst::Manual::Tutorial> or L<Catalyst::Manual::Intro>.
211 See L<Catalyst::Manual> for more documentation.
213 Catalyst plugins can be loaded by naming them as arguments to the "use
214 Catalyst" statement. Omit the C<Catalyst::Plugin::> prefix from the
215 plugin name, i.e., C<Catalyst::Plugin::My::Module> becomes
218 use Catalyst qw/My::Module/;
220 If your plugin starts with a name other than C<Catalyst::Plugin::>, you can
221 fully qualify the name by using a unary plus:
225 +Fully::Qualified::Plugin::Name
228 Special flags like C<-Debug> and C<-Engine> can also be specified as
229 arguments when Catalyst is loaded:
231 use Catalyst qw/-Debug My::Module/;
233 The position of plugins and flags in the chain is important, because
234 they are loaded in the order in which they appear.
236 The following flags are supported:
240 Enables debug output. You can also force this setting from the system
241 environment with CATALYST_DEBUG or <MYAPP>_DEBUG. The environment
242 settings override the application, with <MYAPP>_DEBUG having the highest
247 Forces Catalyst to use a specific engine. Omit the
248 C<Catalyst::Engine::> prefix of the engine name, i.e.:
250 use Catalyst qw/-Engine=CGI/;
254 Forces Catalyst to use a specific home directory, e.g.:
256 use Catalyst qw[-Home=/usr/mst];
258 This can also be done in the shell environment by setting either the
259 C<CATALYST_HOME> environment variable or C<MYAPP_HOME>; where C<MYAPP>
260 is replaced with the uppercased name of your application, any "::" in
261 the name will be replaced with underscores, e.g. MyApp::Web should use
262 MYAPP_WEB_HOME. If both variables are set, the MYAPP_HOME one will be used.
266 use Catalyst '-Log=warn,fatal,error';
268 Specifies a comma-delimited list of log levels.
272 Enables statistics collection and reporting. You can also force this setting
273 from the system environment with CATALYST_STATS or <MYAPP>_STATS. The
274 environment settings override the application, with <MYAPP>_STATS having the
279 use Catalyst qw/-Stats=1/
283 =head2 INFORMATION ABOUT THE CURRENT REQUEST
287 Returns a L<Catalyst::Action> object for the current action, which
288 stringifies to the action name. See L<Catalyst::Action>.
292 Returns the namespace of the current action, i.e., the URI prefix
293 corresponding to the controller of the current action. For example:
295 # in Controller::Foo::Bar
296 $c->namespace; # returns 'foo/bar';
302 Returns the current L<Catalyst::Request> object, giving access to
303 information about the current client request (including parameters,
304 cookies, HTTP headers, etc.). See L<Catalyst::Request>.
306 =head2 REQUEST FLOW HANDLING
308 =head2 $c->forward( $action [, \@arguments ] )
310 =head2 $c->forward( $class, $method, [, \@arguments ] )
312 Forwards processing to another action, by its private name. If you give a
313 class name but no method, C<process()> is called. You may also optionally
314 pass arguments in an arrayref. The action will receive the arguments in
315 C<@_> and C<< $c->req->args >>. Upon returning from the function,
316 C<< $c->req->args >> will be restored to the previous values.
318 Any data C<return>ed from the action forwarded to, will be returned by the
321 my $foodata = $c->forward('/foo');
322 $c->forward('index');
323 $c->forward(qw/MyApp::Model::DBIC::Foo do_stuff/);
324 $c->forward('MyApp::View::TT');
326 Note that forward implies an C<<eval { }>> around the call (actually
327 C<execute> does), thus de-fatalizing all 'dies' within the called
328 action. If you want C<die> to propagate you need to do something like:
331 die $c->error if $c->error;
333 Or make sure to always return true values from your actions and write
336 $c->forward('foo') || return;
340 sub forward { my $c = shift; no warnings 'recursion'; $c->dispatcher->forward( $c, @_ ) }
342 =head2 $c->detach( $action [, \@arguments ] )
344 =head2 $c->detach( $class, $method, [, \@arguments ] )
348 The same as C<forward>, but doesn't return to the previous action when
349 processing is finished.
351 When called with no arguments it escapes the processing chain entirely.
355 sub detach { my $c = shift; $c->dispatcher->detach( $c, @_ ) }
357 =head2 $c->visit( $action [, \@arguments ] )
359 =head2 $c->visit( $class, $method, [, \@arguments ] )
361 Almost the same as C<forward>, but does a full dispatch, instead of just
362 calling the new C<$action> / C<$class-E<gt>$method>. This means that C<begin>,
363 C<auto> and the method you go to are called, just like a new request.
365 C<$c-E<gt>stash> is kept unchanged.
367 In effect, C<visit> allows you to "wrap" another action, just as it
368 would have been called by dispatching from a URL, while the analogous
369 C<go> allows you to transfer control to another action as if it had
370 been reached directly from a URL.
374 sub visit { my $c = shift; $c->dispatcher->visit( $c, @_ ) }
376 =head2 $c->go( $action [, \@arguments ] )
378 =head2 $c->go( $class, $method, [, \@arguments ] )
380 Almost the same as C<detach>, but does a full dispatch like C<visit>,
381 instead of just calling the new C<$action> /
382 C<$class-E<gt>$method>. This means that C<begin>, C<auto> and the
383 method you visit are called, just like a new request.
385 C<$c-E<gt>stash> is kept unchanged.
389 sub go { my $c = shift; $c->dispatcher->go( $c, @_ ) }
395 Returns the current L<Catalyst::Response> object, see there for details.
399 Returns a hashref to the stash, which may be used to store data and pass
400 it between components during a request. You can also set hash keys by
401 passing arguments. The stash is automatically sent to the view. The
402 stash is cleared at the end of a request; it cannot be used for
403 persistent storage (for this you must use a session; see
404 L<Catalyst::Plugin::Session> for a complete system integrated with
407 $c->stash->{foo} = $bar;
408 $c->stash( { moose => 'majestic', qux => 0 } );
409 $c->stash( bar => 1, gorch => 2 ); # equivalent to passing a hashref
411 # stash is automatically passed to the view for use in a template
412 $c->forward( 'MyApp::View::TT' );
416 around stash => sub {
419 my $stash = $orig->($c);
421 my $new_stash = @_ > 1 ? {@_} : $_[0];
422 croak('stash takes a hash or hashref') unless ref $new_stash;
423 foreach my $key ( keys %$new_stash ) {
424 $stash->{$key} = $new_stash->{$key};
434 =head2 $c->error($error, ...)
436 =head2 $c->error($arrayref)
438 Returns an arrayref containing error messages. If Catalyst encounters an
439 error while processing a request, it stores the error in $c->error. This
440 method should only be used to store fatal error messages.
442 my @error = @{ $c->error };
446 $c->error('Something bad happened');
453 my $error = ref $_[0] eq 'ARRAY' ? $_[0] : [@_];
454 croak @$error unless ref $c;
455 push @{ $c->{error} }, @$error;
457 elsif ( defined $_[0] ) { $c->{error} = undef }
458 return $c->{error} || [];
464 Contains the return value of the last executed action.
466 =head2 $c->clear_errors
468 Clear errors. You probably don't want to clear the errors unless you are
469 implementing a custom error screen.
471 This is equivalent to running
482 # search components given a name and some prefixes
483 sub _comp_search_prefixes {
484 my ( $c, $name, @prefixes ) = @_;
485 my $appclass = ref $c || $c;
486 my $filter = "^${appclass}::(" . join( '|', @prefixes ) . ')::';
488 # map the original component name to the sub part that we will search against
489 my %eligible = map { my $n = $_; $n =~ s{^$appclass\::[^:]+::}{}; $_ => $n; }
490 grep { /$filter/ } keys %{ $c->components };
492 # undef for a name will return all
493 return keys %eligible if !defined $name;
495 my $query = ref $name ? $name : qr/^$name$/i;
496 my @result = grep { $eligible{$_} =~ m{$query} } keys %eligible;
498 return map { $c->components->{ $_ } } @result if @result;
500 # if we were given a regexp to search against, we're done.
505 @result = map { $c->components->{ $_ } } grep { $eligible{ $_ } =~ m{$query} } keys %eligible;
507 # no results? try against full names
509 @result = map { $c->components->{ $_ } } grep { m{$query} } keys %eligible;
512 # don't warn if we didn't find any results, it just might not exist
514 $c->log->warn( qq(Found results for "${name}" using regexp fallback.) );
515 $c->log->warn( 'Relying on the regexp fallback behavior for component resolution is unreliable and unsafe.' );
516 $c->log->warn( 'If you really want to search, pass in a regexp as the argument.' );
522 # Find possible names for a prefix
524 my ( $c, @prefixes ) = @_;
525 my $appclass = ref $c || $c;
527 my $filter = "^${appclass}::(" . join( '|', @prefixes ) . ')::';
529 my @names = map { s{$filter}{}; $_; } $c->_comp_search_prefixes( undef, @prefixes );
533 # Filter a component before returning by calling ACCEPT_CONTEXT if available
534 sub _filter_component {
535 my ( $c, $comp, @args ) = @_;
537 if ( eval { $comp->can('ACCEPT_CONTEXT'); } ) {
538 return $comp->ACCEPT_CONTEXT( $c, @args );
544 =head2 COMPONENT ACCESSORS
546 =head2 $c->controller($name)
548 Gets a L<Catalyst::Controller> instance by name.
550 $c->controller('Foo')->do_stuff;
552 If the name is omitted, will return the controller for the dispatched
555 If you want to search for controllers, pass in a regexp as the argument.
557 # find all controllers that start with Foo
558 my @foo_controllers = $c->controller(qr{^Foo});
564 my ( $c, $name, @args ) = @_;
567 my @result = $c->_comp_search_prefixes( $name, qw/Controller C/ );
568 return map { $c->_filter_component( $_, @args ) } @result if ref $name;
569 return $c->_filter_component( $result[ 0 ], @args );
572 return $c->component( $c->action->class );
575 =head2 $c->model($name)
577 Gets a L<Catalyst::Model> instance by name.
579 $c->model('Foo')->do_stuff;
581 Any extra arguments are directly passed to ACCEPT_CONTEXT.
583 If the name is omitted, it will look for
584 - a model object in $c->stash->{current_model_instance}, then
585 - a model name in $c->stash->{current_model}, then
586 - a config setting 'default_model', or
587 - check if there is only one model, and return it if that's the case.
589 If you want to search for models, pass in a regexp as the argument.
591 # find all models that start with Foo
592 my @foo_models = $c->model(qr{^Foo});
597 my ( $c, $name, @args ) = @_;
600 my @result = $c->_comp_search_prefixes( $name, qw/Model M/ );
601 return map { $c->_filter_component( $_, @args ) } @result if ref $name;
602 return $c->_filter_component( $result[ 0 ], @args );
606 return $c->stash->{current_model_instance}
607 if $c->stash->{current_model_instance};
608 return $c->model( $c->stash->{current_model} )
609 if $c->stash->{current_model};
611 return $c->model( $c->config->{default_model} )
612 if $c->config->{default_model};
614 my( $comp, $rest ) = $c->_comp_search_prefixes( undef, qw/Model M/);
617 $c->log->warn( 'Calling $c->model() will return a random model unless you specify one of:' );
618 $c->log->warn( '* $c->config->{default_model} # the name of the default model to use' );
619 $c->log->warn( '* $c->stash->{current_model} # the name of the model to use for this request' );
620 $c->log->warn( '* $c->stash->{current_model_instance} # the instance of the model to use for this request' );
621 $c->log->warn( 'NB: in version 5.80, the "random" behavior will not work at all.' );
624 return $c->_filter_component( $comp );
628 =head2 $c->view($name)
630 Gets a L<Catalyst::View> instance by name.
632 $c->view('Foo')->do_stuff;
634 Any extra arguments are directly passed to ACCEPT_CONTEXT.
636 If the name is omitted, it will look for
637 - a view object in $c->stash->{current_view_instance}, then
638 - a view name in $c->stash->{current_view}, then
639 - a config setting 'default_view', or
640 - check if there is only one view, and return it if that's the case.
642 If you want to search for views, pass in a regexp as the argument.
644 # find all views that start with Foo
645 my @foo_views = $c->view(qr{^Foo});
650 my ( $c, $name, @args ) = @_;
653 my @result = $c->_comp_search_prefixes( $name, qw/View V/ );
654 return map { $c->_filter_component( $_, @args ) } @result if ref $name;
655 return $c->_filter_component( $result[ 0 ], @args );
659 return $c->stash->{current_view_instance}
660 if $c->stash->{current_view_instance};
661 return $c->view( $c->stash->{current_view} )
662 if $c->stash->{current_view};
664 return $c->view( $c->config->{default_view} )
665 if $c->config->{default_view};
667 my( $comp, $rest ) = $c->_comp_search_prefixes( undef, qw/View V/);
670 $c->log->warn( 'Calling $c->view() will return a random view unless you specify one of:' );
671 $c->log->warn( '* $c->config->{default_view} # the name of the default view to use' );
672 $c->log->warn( '* $c->stash->{current_view} # the name of the view to use for this request' );
673 $c->log->warn( '* $c->stash->{current_view_instance} # the instance of the view to use for this request' );
674 $c->log->warn( 'NB: in version 5.80, the "random" behavior will not work at all.' );
677 return $c->_filter_component( $comp );
680 =head2 $c->controllers
682 Returns the available names which can be passed to $c->controller
688 return $c->_comp_names(qw/Controller C/);
693 Returns the available names which can be passed to $c->model
699 return $c->_comp_names(qw/Model M/);
705 Returns the available names which can be passed to $c->view
711 return $c->_comp_names(qw/View V/);
714 =head2 $c->comp($name)
716 =head2 $c->component($name)
718 Gets a component object by name. This method is not recommended,
719 unless you want to get a specific component by full
720 class. C<< $c->controller >>, C<< $c->model >>, and C<< $c->view >>
721 should be used instead.
723 If C<$name> is a regexp, a list of components matched against the full
724 component name will be returned.
729 my ( $c, $name, @args ) = @_;
732 my $comps = $c->components;
735 # is it the exact name?
736 return $c->_filter_component( $comps->{ $name }, @args )
737 if exists $comps->{ $name };
739 # perhaps we just omitted "MyApp"?
740 my $composed = ( ref $c || $c ) . "::${name}";
741 return $c->_filter_component( $comps->{ $composed }, @args )
742 if exists $comps->{ $composed };
744 # search all of the models, views and controllers
745 my( $comp ) = $c->_comp_search_prefixes( $name, qw/Model M Controller C View V/ );
746 return $c->_filter_component( $comp, @args ) if $comp;
749 # This is here so $c->comp( '::M::' ) works
750 my $query = ref $name ? $name : qr{$name}i;
752 my @result = grep { m{$query} } keys %{ $c->components };
753 return map { $c->_filter_component( $_, @args ) } @result if ref $name;
756 $c->log->warn( qq(Found results for "${name}" using regexp fallback.) );
757 $c->log->warn( 'Relying on the regexp fallback behavior for component resolution' );
758 $c->log->warn( 'is unreliable and unsafe. You have been warned' );
759 return $c->_filter_component( $result[ 0 ], @args );
762 # I would expect to return an empty list here, but that breaks back-compat
766 return sort keys %{ $c->components };
769 =head2 CLASS DATA AND HELPER CLASSES
773 Returns or takes a hashref containing the application's configuration.
775 __PACKAGE__->config( { db => 'dsn:SQLite:foo.db' } );
777 You can also use a C<YAML>, C<XML> or C<Config::General> config file
778 like myapp.yml in your applications home directory. See
779 L<Catalyst::Plugin::ConfigLoader>.
782 db: dsn:SQLite:foo.db
787 around config => sub {
791 $c->log->warn("Setting config after setup has been run is not a good idea.")
792 if ( @_ and $c->setup_finished );
799 Returns the logging object instance. Unless it is already set, Catalyst
800 sets this up with a L<Catalyst::Log> object. To use your own log class,
801 set the logger with the C<< __PACKAGE__->log >> method prior to calling
802 C<< __PACKAGE__->setup >>.
804 __PACKAGE__->log( MyLogger->new );
809 $c->log->info( 'Now logging with my own logger!' );
811 Your log class should implement the methods described in
817 Overload to enable debug messages (same as -Debug option).
819 Note that this is a static method, not an accessor and should be overloaded
820 by declaring "sub debug { 1 }" in your MyApp.pm, not by calling $c->debug(1).
826 =head2 $c->dispatcher
828 Returns the dispatcher instance. Stringifies to class name. See
829 L<Catalyst::Dispatcher>.
833 Returns the engine instance. Stringifies to the class name. See
837 =head2 UTILITY METHODS
839 =head2 $c->path_to(@path)
841 Merges C<@path> with C<< $c->config->{home} >> and returns a
842 L<Path::Class::Dir> object.
846 $c->path_to( 'db', 'sqlite.db' );
851 my ( $c, @path ) = @_;
852 my $path = Path::Class::Dir->new( $c->config->{home}, @path );
853 if ( -d $path ) { return $path }
854 else { return Path::Class::File->new( $c->config->{home}, @path ) }
857 =head2 $c->plugin( $name, $class, @args )
859 Helper method for plugins. It creates a classdata accessor/mutator and
860 loads and instantiates the given class.
862 MyApp->plugin( 'prototype', 'HTML::Prototype' );
864 $c->prototype->define_javascript_functions;
869 my ( $class, $name, $plugin, @args ) = @_;
870 $class->_register_plugin( $plugin, 1 );
872 eval { $plugin->import };
873 $class->mk_classdata($name);
875 eval { $obj = $plugin->new(@args) };
878 Catalyst::Exception->throw( message =>
879 qq/Couldn't instantiate instant plugin "$plugin", "$@"/ );
883 $class->log->debug(qq/Initialized instant plugin "$plugin" as "$name"/)
889 Initializes the dispatcher and engine, loads any plugins, and loads the
890 model, view, and controller components. You may also specify an array
891 of plugins to load here, if you choose to not load them in the C<use
895 MyApp->setup( qw/-Debug/ );
900 my ( $class, @arguments ) = @_;
901 $class->log->warn("Running setup twice is not a good idea.")
902 if ( $class->setup_finished );
904 unless ( $class->isa('Catalyst') ) {
906 Catalyst::Exception->throw(
907 message => qq/'$class' does not inherit from Catalyst/ );
910 if ( $class->arguments ) {
911 @arguments = ( @arguments, @{ $class->arguments } );
917 foreach (@arguments) {
921 ( $flags->{log} ) ? 'debug,' . $flags->{log} : 'debug';
923 elsif (/^-(\w+)=?(.*)$/) {
924 $flags->{ lc $1 } = $2;
927 push @{ $flags->{plugins} }, $_;
931 $class->setup_home( delete $flags->{home} );
933 $class->setup_log( delete $flags->{log} );
934 $class->setup_plugins( delete $flags->{plugins} );
935 $class->setup_dispatcher( delete $flags->{dispatcher} );
936 $class->setup_engine( delete $flags->{engine} );
937 $class->setup_stats( delete $flags->{stats} );
939 for my $flag ( sort keys %{$flags} ) {
941 if ( my $code = $class->can( 'setup_' . $flag ) ) {
942 &$code( $class, delete $flags->{$flag} );
945 $class->log->warn(qq/Unknown flag "$flag"/);
949 eval { require Catalyst::Devel; };
950 if( !$@ && $ENV{CATALYST_SCRIPT_GEN} && ( $ENV{CATALYST_SCRIPT_GEN} < $Catalyst::Devel::CATALYST_SCRIPT_GEN ) ) {
951 $class->log->warn(<<"EOF");
952 You are running an old script!
954 Please update by running (this will overwrite existing files):
955 catalyst.pl -force -scripts $class
957 or (this will not overwrite existing files):
958 catalyst.pl -scripts $class
963 if ( $class->debug ) {
964 my @plugins = map { "$_ " . ( $_->VERSION || '' ) } $class->registered_plugins;
967 my $t = Text::SimpleTable->new(74);
968 $t->row($_) for @plugins;
969 $class->log->debug( "Loaded plugins:\n" . $t->draw . "\n" );
972 my $dispatcher = $class->dispatcher;
973 my $engine = $class->engine;
974 my $home = $class->config->{home};
976 $class->log->debug(qq/Loaded dispatcher "$dispatcher"/);
977 $class->log->debug(qq/Loaded engine "$engine"/);
981 ? $class->log->debug(qq/Found home "$home"/)
982 : $class->log->debug(qq/Home "$home" doesn't exist/)
983 : $class->log->debug(q/Couldn't find home/);
988 no warnings qw/redefine/;
989 local *setup = sub { };
993 # Initialize our data structure
994 $class->components( {} );
996 $class->setup_components;
998 if ( $class->debug ) {
999 my $t = Text::SimpleTable->new( [ 63, 'Class' ], [ 8, 'Type' ] );
1000 for my $comp ( sort keys %{ $class->components } ) {
1001 my $type = ref $class->components->{$comp} ? 'instance' : 'class';
1002 $t->row( $comp, $type );
1004 $class->log->debug( "Loaded components:\n" . $t->draw . "\n" )
1005 if ( keys %{ $class->components } );
1008 # Add our self to components, since we are also a component
1009 if( $class->isa('Catalyst::Controller') ){
1010 $class->components->{$class} = $class;
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");
1019 $class->log->_flush() if $class->log->can('_flush');
1021 $class->setup_finished(1);
1024 =head2 $c->uri_for( $action, \@captures?, @args?, \%query_values? )
1026 =head2 $c->uri_for( $path, @args?, \%query_values? )
1032 A Catalyst::Action object representing the Catalyst action you want to
1033 create a URI for. To get one for an action in the current controller,
1034 use C<< $c->action('someactionname') >>. To get one from different
1035 controller, fetch the controller using C<< $c->controller() >>, then
1036 call C<action_for> on it.
1038 You can maintain the arguments captured by an action (e.g.: Regex, Chained)
1039 using C<< $c->req->captures >>.
1041 # For the current action
1042 $c->uri_for($c->action, $c->req->captures);
1044 # For the Foo action in the Bar controller
1045 $c->uri_for($c->controller->('Bar')->action_for('Foo'), $c->req->captures);
1052 my ( $c, $path, @args ) = @_;
1054 if ( Scalar::Util::blessed($path) ) { # action object
1055 my $captures = ( scalar @args && ref $args[0] eq 'ARRAY'
1058 $path = $c->dispatcher->uri_for_action($path, $captures);
1059 return undef unless defined($path);
1060 $path = '/' if $path eq '';
1063 undef($path) if (defined $path && $path eq '');
1066 ( scalar @args && ref $args[$#args] eq 'HASH' ? pop @args : {} );
1068 carp "uri_for called with undef argument" if grep { ! defined $_ } @args;
1069 s/([^$URI::uric])/$URI::Escape::escapes{$1}/go for @args;
1071 unshift(@args, $path);
1073 unless (defined $path && $path =~ s!^/!!) { # in-place strip
1074 my $namespace = $c->namespace;
1075 if (defined $path) { # cheesy hack to handle path '../foo'
1076 $namespace =~ s{(?:^|/)[^/]+$}{} while $args[0] =~ s{^\.\./}{};
1078 unshift(@args, $namespace || '');
1081 # join args with '/', or a blank string
1082 my $args = join('/', grep { defined($_) } @args);
1083 $args =~ s/\?/%3F/g; # STUPID STUPID SPECIAL CASE
1085 my $base = $c->req->base;
1086 my $class = ref($base);
1087 $base =~ s{(?<!/)$}{/};
1091 if (my @keys = keys %$params) {
1092 # somewhat lifted from URI::_query's query_form
1093 $query = '?'.join('&', map {
1094 my $val = $params->{$_};
1095 s/([;\/?:@&=+,\$\[\]%])/$URI::Escape::escapes{$1}/go;
1098 $val = '' unless defined $val;
1101 utf8::encode( $_ ) if utf8::is_utf8($_);
1102 # using the URI::Escape pattern here so utf8 chars survive
1103 s/([^A-Za-z0-9\-_.!~*'() ])/$URI::Escape::escapes{$1}/go;
1105 "${key}=$_"; } ( ref $val eq 'ARRAY' ? @$val : $val ));
1109 my $res = bless(\"${base}${args}${query}", $class);
1113 =head2 $c->welcome_message
1115 Returns the Catalyst welcome HTML page.
1119 sub welcome_message {
1121 my $name = $c->config->{name};
1122 my $logo = $c->uri_for('/static/images/catalyst_logo.png');
1123 my $prefix = Catalyst::Utils::appprefix( ref $c );
1124 $c->response->content_type('text/html; charset=utf-8');
1126 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
1127 "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
1128 <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
1130 <meta http-equiv="Content-Language" content="en" />
1131 <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
1132 <title>$name on Catalyst $VERSION</title>
1133 <style type="text/css">
1136 background-color: #eee;
1143 margin-bottom: 10px;
1145 background-color: #ccc;
1146 border: 1px solid #aaa;
1151 font-family: verdana, tahoma, sans-serif;
1154 font-family: verdana, tahoma, sans-serif;
1157 text-decoration: none;
1159 border-bottom: 1px dotted #bbb;
1161 :link:hover, :visited:hover {
1174 background-color: #fff;
1175 border: 1px solid #aaa;
1179 font-weight: normal;
1201 <h1><span id="appname">$name</span> on <a href="http://catalyst.perl.org">Catalyst</a>
1206 <img src="$logo" alt="Catalyst Logo" />
1208 <p>Welcome to the world of Catalyst.
1209 This <a href="http://en.wikipedia.org/wiki/MVC">MVC</a>
1210 framework will make web development something you had
1211 never expected it to be: Fun, rewarding, and quick.</p>
1212 <h2>What to do now?</h2>
1213 <p>That really depends on what <b>you</b> want to do.
1214 We do, however, provide you with a few starting points.</p>
1215 <p>If you want to jump right into web development with Catalyst
1216 you might want to start with a tutorial.</p>
1217 <pre>perldoc <a href="http://cpansearch.perl.org/dist/Catalyst-Manual/lib/Catalyst/Manual/Tutorial.pod">Catalyst::Manual::Tutorial</a></code>
1219 <p>Afterwards you can go on to check out a more complete look at our features.</p>
1221 <code>perldoc <a href="http://cpansearch.perl.org/dist/Catalyst-Manual/lib/Catalyst/Manual/Intro.pod">Catalyst::Manual::Intro</a>
1222 <!-- Something else should go here, but the Catalyst::Manual link seems unhelpful -->
1224 <h2>What to do next?</h2>
1225 <p>Next it's time to write an actual application. Use the
1226 helper scripts to generate <a href="http://cpansearch.perl.org/search?query=Catalyst%3A%3AController%3A%3A&mode=all">controllers</a>,
1227 <a href="http://cpansearch.perl.org/search?query=Catalyst%3A%3AModel%3A%3A&mode=all">models</a>, and
1228 <a href="http://cpansearch.perl.org/search?query=Catalyst%3A%3AView%3A%3A&mode=all">views</a>;
1229 they can save you a lot of work.</p>
1230 <pre><code>script/${prefix}_create.pl -help</code></pre>
1231 <p>Also, be sure to check out the vast and growing
1232 collection of <a href="http://cpansearch.perl.org/search?query=Catalyst%3A%3APlugin%3A%3A&mode=all">plugins for Catalyst on CPAN</a>;
1233 you are likely to find what you need there.
1237 <p>Catalyst has a very active community. Here are the main places to
1238 get in touch with us.</p>
1241 <a href="http://dev.catalyst.perl.org">Wiki</a>
1244 <a href="http://lists.scsys.co.uk/cgi-bin/mailman/listinfo/catalyst">Mailing-List</a>
1247 <a href="irc://irc.perl.org/catalyst">IRC channel #catalyst on irc.perl.org</a>
1250 <h2>In conclusion</h2>
1251 <p>The Catalyst team hopes you will enjoy using Catalyst as much
1252 as we enjoyed making it. Please contact us if you have ideas
1253 for improvement or other feedback.</p>
1261 =head1 INTERNAL METHODS
1263 These methods are not meant to be used by end users.
1265 =head2 $c->components
1267 Returns a hash of components.
1269 =head2 $c->context_class
1271 Returns or sets the context class.
1275 Returns a hashref containing coderefs and execution counts (needed for
1276 deep recursion detection).
1280 Returns the number of actions on the current internal execution stack.
1284 Dispatches a request to actions.
1288 sub dispatch { my $c = shift; $c->dispatcher->dispatch( $c, @_ ) }
1290 =head2 $c->dispatcher_class
1292 Returns or sets the dispatcher class.
1294 =head2 $c->dump_these
1296 Returns a list of 2-element array references (name, structure) pairs
1297 that will be dumped on the error page in debug mode.
1303 [ Request => $c->req ],
1304 [ Response => $c->res ],
1305 [ Stash => $c->stash ],
1306 [ Config => $c->config ];
1309 =head2 $c->engine_class
1311 Returns or sets the engine class.
1313 =head2 $c->execute( $class, $coderef )
1315 Execute a coderef in given class and catch exceptions. Errors are available
1321 my ( $c, $class, $code ) = @_;
1322 $class = $c->component($class) || $class;
1325 if ( $c->depth >= $RECURSION ) {
1326 my $action = $code->reverse();
1327 $action = "/$action" unless $action =~ /->/;
1328 my $error = qq/Deep recursion detected calling "${action}"/;
1329 $c->log->error($error);
1335 my $stats_info = $c->_stats_start_execute( $code ) if $c->use_stats;
1337 push( @{ $c->stack }, $code );
1339 eval { $c->state( $code->execute( $class, $c, @{ $c->req->args } ) || 0 ) };
1341 $c->_stats_finish_execute( $stats_info ) if $c->use_stats and $stats_info;
1343 my $last = pop( @{ $c->stack } );
1345 if ( my $error = $@ ) {
1346 if ( !ref($error) and $error eq $DETACH ) {
1347 die $DETACH if($c->depth > 1);
1349 elsif ( !ref($error) and $error eq $GO ) {
1350 die $GO if($c->depth > 0);
1353 unless ( ref $error ) {
1354 no warnings 'uninitialized';
1356 my $class = $last->class;
1357 my $name = $last->name;
1358 $error = qq/Caught exception in $class->$name "$error"/;
1367 sub _stats_start_execute {
1368 my ( $c, $code ) = @_;
1370 return if ( ( $code->name =~ /^_.*/ )
1371 && ( !$c->config->{show_internal_actions} ) );
1373 my $action_name = $code->reverse();
1374 $c->counter->{$action_name}++;
1376 my $action = $action_name;
1377 $action = "/$action" unless $action =~ /->/;
1379 # determine if the call was the result of a forward
1380 # this is done by walking up the call stack and looking for a calling
1381 # sub of Catalyst::forward before the eval
1383 for my $index ( 2 .. 11 ) {
1385 if ( ( caller($index) )[0] eq 'Catalyst'
1386 && ( caller($index) )[3] eq '(eval)' );
1388 if ( ( caller($index) )[3] =~ /forward$/ ) {
1389 $callsub = ( caller($index) )[3];
1390 $action = "-> $action";
1395 my $uid = $action_name . $c->counter->{$action_name};
1397 # is this a root-level call or a forwarded call?
1398 if ( $callsub =~ /forward$/ ) {
1400 # forward, locate the caller
1401 if ( my $parent = $c->stack->[-1] ) {
1404 parent => "$parent" . $c->counter->{"$parent"},
1410 # forward with no caller may come from a plugin
1429 sub _stats_finish_execute {
1430 my ( $c, $info ) = @_;
1431 $c->stats->profile( end => $info );
1434 =head2 $c->_localize_fields( sub { }, \%keys );
1438 #Why does this exist? This is no longer safe and WILL NOT WORK.
1439 # it doesnt seem to be used anywhere. can we remove it?
1440 sub _localize_fields {
1441 my ( $c, $localized, $code ) = ( @_ );
1443 my $request = delete $localized->{request} || {};
1444 my $response = delete $localized->{response} || {};
1446 local @{ $c }{ keys %$localized } = values %$localized;
1447 local @{ $c->request }{ keys %$request } = values %$request;
1448 local @{ $c->response }{ keys %$response } = values %$response;
1455 Finalizes the request.
1462 for my $error ( @{ $c->error } ) {
1463 $c->log->error($error);
1466 # Allow engine to handle finalize flow (for POE)
1467 my $engine = $c->engine;
1468 if ( my $code = $engine->can('finalize') ) {
1473 $c->finalize_uploads;
1476 if ( $#{ $c->error } >= 0 ) {
1480 $c->finalize_headers;
1483 if ( $c->request->method eq 'HEAD' ) {
1484 $c->response->body('');
1490 if ($c->use_stats) {
1491 my $elapsed = sprintf '%f', $c->stats->elapsed;
1492 my $av = $elapsed == 0 ? '??' : sprintf '%.3f', 1 / $elapsed;
1494 "Request took ${elapsed}s ($av/s)\n" . $c->stats->report . "\n" );
1497 return $c->response->status;
1500 =head2 $c->finalize_body
1506 sub finalize_body { my $c = shift; $c->engine->finalize_body( $c, @_ ) }
1508 =head2 $c->finalize_cookies
1514 sub finalize_cookies { my $c = shift; $c->engine->finalize_cookies( $c, @_ ) }
1516 =head2 $c->finalize_error
1522 sub finalize_error { my $c = shift; $c->engine->finalize_error( $c, @_ ) }
1524 =head2 $c->finalize_headers
1530 sub finalize_headers {
1533 my $response = $c->response; #accessor calls can add up?
1535 # Check if we already finalized headers
1536 return if $response->finalized_headers;
1539 if ( my $location = $response->redirect ) {
1540 $c->log->debug(qq/Redirecting to "$location"/) if $c->debug;
1541 $response->header( Location => $location );
1543 if ( !$response->has_body ) {
1544 # Add a default body if none is already present
1546 qq{<html><body><p>This item has moved <a href="$location">here</a>.</p></body></html>}
1552 if ( $response->body && !$response->content_length ) {
1554 # get the length from a filehandle
1555 if ( blessed( $response->body ) && $response->body->can('read') )
1557 my $stat = stat $response->body;
1558 if ( $stat && $stat->size > 0 ) {
1559 $response->content_length( $stat->size );
1562 $c->log->warn('Serving filehandle without a content-length');
1566 # everything should be bytes at this point, but just in case
1567 $response->content_length( bytes::length( $response->body ) );
1572 if ( $response->status =~ /^(1\d\d|[23]04)$/ ) {
1573 $response->headers->remove_header("Content-Length");
1574 $response->body('');
1577 $c->finalize_cookies;
1579 $c->engine->finalize_headers( $c, @_ );
1582 $response->finalized_headers(1);
1585 =head2 $c->finalize_output
1587 An alias for finalize_body.
1589 =head2 $c->finalize_read
1591 Finalizes the input after reading is complete.
1595 sub finalize_read { my $c = shift; $c->engine->finalize_read( $c, @_ ) }
1597 =head2 $c->finalize_uploads
1599 Finalizes uploads. Cleans up any temporary files.
1603 sub finalize_uploads { my $c = shift; $c->engine->finalize_uploads( $c, @_ ) }
1605 =head2 $c->get_action( $action, $namespace )
1607 Gets an action in a given namespace.
1611 sub get_action { my $c = shift; $c->dispatcher->get_action(@_) }
1613 =head2 $c->get_actions( $action, $namespace )
1615 Gets all actions of a given name in a namespace and all parent
1620 sub get_actions { my $c = shift; $c->dispatcher->get_actions( $c, @_ ) }
1622 =head2 $c->handle_request( $class, @arguments )
1624 Called to handle each HTTP request.
1628 sub handle_request {
1629 my ( $class, @arguments ) = @_;
1631 # Always expect worst case!
1634 if ($class->debug) {
1635 my $secs = time - $START || 1;
1636 my $av = sprintf '%.3f', $COUNT / $secs;
1637 my $time = localtime time;
1638 $class->log->info("*** Request $COUNT ($av/s) [$$] [$time] ***");
1641 my $c = $class->prepare(@arguments);
1643 $status = $c->finalize;
1646 if ( my $error = $@ ) {
1648 $class->log->error(qq/Caught exception in engine "$error"/);
1653 if(my $coderef = $class->log->can('_flush')){
1654 $class->log->$coderef();
1659 =head2 $c->prepare( @arguments )
1661 Creates a Catalyst context from an engine-specific request (Apache, CGI,
1667 my ( $class, @arguments ) = @_;
1670 # After the app/ctxt split, this should become an attribute based on something passed
1671 # into the application.
1672 $class->context_class( ref $class || $class ) unless $class->context_class;
1674 my $c = $class->context_class->new({});
1676 # For on-demand data
1677 $c->request->_context($c);
1678 $c->response->_context($c);
1680 #surely this is not the most efficient way to do things...
1681 $c->stats($class->stats_class->new)->enable($c->use_stats);
1683 $c->res->headers->header( 'X-Catalyst' => $Catalyst::VERSION );
1686 #XXX reuse coderef from can
1687 # Allow engine to direct the prepare flow (for POE)
1688 if ( $c->engine->can('prepare') ) {
1689 $c->engine->prepare( $c, @arguments );
1692 $c->prepare_request(@arguments);
1693 $c->prepare_connection;
1694 $c->prepare_query_parameters;
1695 $c->prepare_headers;
1696 $c->prepare_cookies;
1699 # Prepare the body for reading, either by prepare_body
1700 # or the user, if they are using $c->read
1703 # Parse the body unless the user wants it on-demand
1704 unless ( $c->config->{parse_on_demand} ) {
1709 my $method = $c->req->method || '';
1710 my $path = $c->req->path;
1711 $path = '/' unless length $path;
1712 my $address = $c->req->address || '';
1714 $c->log->debug(qq/"$method" request for "$path" from "$address"/)
1722 =head2 $c->prepare_action
1724 Prepares action. See L<Catalyst::Dispatcher>.
1728 sub prepare_action { my $c = shift; $c->dispatcher->prepare_action( $c, @_ ) }
1730 =head2 $c->prepare_body
1732 Prepares message body.
1739 #Moose TODO: what is _body ??
1740 # Do we run for the first time?
1741 return if defined $c->request->{_body};
1743 # Initialize on-demand data
1744 $c->engine->prepare_body( $c, @_ );
1745 $c->prepare_parameters;
1746 $c->prepare_uploads;
1748 if ( $c->debug && keys %{ $c->req->body_parameters } ) {
1749 my $t = Text::SimpleTable->new( [ 35, 'Parameter' ], [ 36, 'Value' ] );
1750 for my $key ( sort keys %{ $c->req->body_parameters } ) {
1751 my $param = $c->req->body_parameters->{$key};
1752 my $value = defined($param) ? $param : '';
1754 ref $value eq 'ARRAY' ? ( join ', ', @$value ) : $value );
1756 $c->log->debug( "Body Parameters are:\n" . $t->draw );
1760 =head2 $c->prepare_body_chunk( $chunk )
1762 Prepares a chunk of data before sending it to L<HTTP::Body>.
1764 See L<Catalyst::Engine>.
1768 sub prepare_body_chunk {
1770 $c->engine->prepare_body_chunk( $c, @_ );
1773 =head2 $c->prepare_body_parameters
1775 Prepares body parameters.
1779 sub prepare_body_parameters {
1781 $c->engine->prepare_body_parameters( $c, @_ );
1784 =head2 $c->prepare_connection
1786 Prepares connection.
1790 sub prepare_connection {
1792 $c->engine->prepare_connection( $c, @_ );
1795 =head2 $c->prepare_cookies
1801 sub prepare_cookies { my $c = shift; $c->engine->prepare_cookies( $c, @_ ) }
1803 =head2 $c->prepare_headers
1809 sub prepare_headers { my $c = shift; $c->engine->prepare_headers( $c, @_ ) }
1811 =head2 $c->prepare_parameters
1813 Prepares parameters.
1817 sub prepare_parameters {
1819 $c->prepare_body_parameters;
1820 $c->engine->prepare_parameters( $c, @_ );
1823 =head2 $c->prepare_path
1825 Prepares path and base.
1829 sub prepare_path { my $c = shift; $c->engine->prepare_path( $c, @_ ) }
1831 =head2 $c->prepare_query_parameters
1833 Prepares query parameters.
1837 sub prepare_query_parameters {
1840 $c->engine->prepare_query_parameters( $c, @_ );
1842 if ( $c->debug && keys %{ $c->request->query_parameters } ) {
1843 my $t = Text::SimpleTable->new( [ 35, 'Parameter' ], [ 36, 'Value' ] );
1844 for my $key ( sort keys %{ $c->req->query_parameters } ) {
1845 my $param = $c->req->query_parameters->{$key};
1846 my $value = defined($param) ? $param : '';
1848 ref $value eq 'ARRAY' ? ( join ', ', @$value ) : $value );
1850 $c->log->debug( "Query Parameters are:\n" . $t->draw );
1854 =head2 $c->prepare_read
1856 Prepares the input for reading.
1860 sub prepare_read { my $c = shift; $c->engine->prepare_read( $c, @_ ) }
1862 =head2 $c->prepare_request
1864 Prepares the engine request.
1868 sub prepare_request { my $c = shift; $c->engine->prepare_request( $c, @_ ) }
1870 =head2 $c->prepare_uploads
1876 sub prepare_uploads {
1879 $c->engine->prepare_uploads( $c, @_ );
1881 if ( $c->debug && keys %{ $c->request->uploads } ) {
1882 my $t = Text::SimpleTable->new(
1883 [ 12, 'Parameter' ],
1888 for my $key ( sort keys %{ $c->request->uploads } ) {
1889 my $upload = $c->request->uploads->{$key};
1890 for my $u ( ref $upload eq 'ARRAY' ? @{$upload} : ($upload) ) {
1891 $t->row( $key, $u->filename, $u->type, $u->size );
1894 $c->log->debug( "File Uploads are:\n" . $t->draw );
1898 =head2 $c->prepare_write
1900 Prepares the output for writing.
1904 sub prepare_write { my $c = shift; $c->engine->prepare_write( $c, @_ ) }
1906 =head2 $c->request_class
1908 Returns or sets the request class.
1910 =head2 $c->response_class
1912 Returns or sets the response class.
1914 =head2 $c->read( [$maxlength] )
1916 Reads a chunk of data from the request body. This method is designed to
1917 be used in a while loop, reading C<$maxlength> bytes on every call.
1918 C<$maxlength> defaults to the size of the request if not specified.
1920 You have to set C<< MyApp->config->{parse_on_demand} >> to use this
1923 Warning: If you use read(), Catalyst will not process the body,
1924 so you will not be able to access POST parameters or file uploads via
1925 $c->request. You must handle all body parsing yourself.
1929 sub read { my $c = shift; return $c->engine->read( $c, @_ ) }
1937 sub run { my $c = shift; return $c->engine->run( $c, @_ ) }
1939 =head2 $c->set_action( $action, $code, $namespace, $attrs )
1941 Sets an action in a given namespace.
1945 sub set_action { my $c = shift; $c->dispatcher->set_action( $c, @_ ) }
1947 =head2 $c->setup_actions($component)
1949 Sets up actions for a component.
1953 sub setup_actions { my $c = shift; $c->dispatcher->setup_actions( $c, @_ ) }
1955 =head2 $c->setup_components
1957 Sets up components. Specify a C<setup_components> config option to pass
1958 additional options directly to L<Module::Pluggable>. To add additional
1959 search paths, specify a key named C<search_extra> as an array
1960 reference. Items in the array beginning with C<::> will have the
1961 application class name prepended to them.
1963 All components found will also have any
1964 L<Devel::InnerPackage|inner packages> loaded and set up as components.
1965 Note, that modules which are B<not> an I<inner package> of the main
1966 file namespace loaded will not be instantiated as components.
1970 sub setup_components {
1973 my @paths = qw( ::Controller ::C ::Model ::M ::View ::V );
1974 my $config = $class->config->{ setup_components };
1975 my $extra = delete $config->{ search_extra } || [];
1977 push @paths, @$extra;
1979 my $locator = Module::Pluggable::Object->new(
1980 search_path => [ map { s/^(?=::)/$class/; $_; } @paths ],
1984 my @comps = sort { length $a <=> length $b } $locator->plugins;
1985 my %comps = map { $_ => 1 } @comps;
1987 for my $component ( @comps ) {
1989 # We pass ignore_loaded here so that overlay files for (e.g.)
1990 # Model::DBI::Schema sub-classes are loaded - if it's in @comps
1991 # we know M::P::O found a file on disk so this is safe
1993 Catalyst::Utils::ensure_class_loaded( $component, { ignore_loaded => 1 } );
1994 #Class::MOP::load_class($component);
1996 my $module = $class->setup_component( $component );
1998 $component => $module,
2000 $_ => $class->setup_component( $_ )
2002 not exists $comps{$_}
2003 } Devel::InnerPackage::list_packages( $component )
2006 for my $key ( keys %modules ) {
2007 $class->components->{ $key } = $modules{ $key };
2012 =head2 $c->setup_component
2016 sub setup_component {
2017 my( $class, $component ) = @_;
2019 unless ( $component->can( 'COMPONENT' ) ) {
2023 my $suffix = Catalyst::Utils::class2classsuffix( $component );
2024 my $config = $class->config->{ $suffix } || {};
2026 my $instance = eval { $component->COMPONENT( $class, $config ); };
2028 if ( my $error = $@ ) {
2030 Catalyst::Exception->throw(
2031 message => qq/Couldn't instantiate component "$component", "$error"/
2035 Catalyst::Exception->throw(
2037 qq/Couldn't instantiate component "$component", "COMPONENT() didn't return an object-like value"/
2038 ) unless blessed($instance);
2043 =head2 $c->setup_dispatcher
2049 sub setup_dispatcher {
2050 my ( $class, $dispatcher ) = @_;
2053 $dispatcher = 'Catalyst::Dispatcher::' . $dispatcher;
2056 if ( my $env = Catalyst::Utils::env_value( $class, 'DISPATCHER' ) ) {
2057 $dispatcher = 'Catalyst::Dispatcher::' . $env;
2060 unless ($dispatcher) {
2061 $dispatcher = $class->dispatcher_class;
2064 Class::MOP::load_class($dispatcher);
2066 # dispatcher instance
2067 $class->dispatcher( $dispatcher->new );
2070 =head2 $c->setup_engine
2077 my ( $class, $engine ) = @_;
2080 $engine = 'Catalyst::Engine::' . $engine;
2083 if ( my $env = Catalyst::Utils::env_value( $class, 'ENGINE' ) ) {
2084 $engine = 'Catalyst::Engine::' . $env;
2087 if ( $ENV{MOD_PERL} ) {
2088 my $meta = $class->Class::MOP::Object::meta();
2090 # create the apache method
2091 $meta->add_method('apache' => sub { shift->engine->apache });
2093 my ( $software, $version ) =
2094 $ENV{MOD_PERL} =~ /^(\S+)\/(\d+(?:[\.\_]\d+)+)/;
2097 $version =~ s/(\.[^.]+)\./$1/g;
2099 if ( $software eq 'mod_perl' ) {
2103 if ( $version >= 1.99922 ) {
2104 $engine = 'Catalyst::Engine::Apache2::MP20';
2107 elsif ( $version >= 1.9901 ) {
2108 $engine = 'Catalyst::Engine::Apache2::MP19';
2111 elsif ( $version >= 1.24 ) {
2112 $engine = 'Catalyst::Engine::Apache::MP13';
2116 Catalyst::Exception->throw( message =>
2117 qq/Unsupported mod_perl version: $ENV{MOD_PERL}/ );
2122 # install the correct mod_perl handler
2123 if ( $version >= 1.9901 ) {
2124 *handler = sub : method {
2125 shift->handle_request(@_);
2129 *handler = sub ($$) { shift->handle_request(@_) };
2134 elsif ( $software eq 'Zeus-Perl' ) {
2135 $engine = 'Catalyst::Engine::Zeus';
2139 Catalyst::Exception->throw(
2140 message => qq/Unsupported mod_perl: $ENV{MOD_PERL}/ );
2145 $engine = $class->engine_class;
2148 Class::MOP::load_class($engine);
2150 # check for old engines that are no longer compatible
2152 if ( $engine->isa('Catalyst::Engine::Apache')
2153 && !Catalyst::Engine::Apache->VERSION )
2158 elsif ( $engine->isa('Catalyst::Engine::Server::Base')
2159 && Catalyst::Engine::Server->VERSION le '0.02' )
2164 elsif ($engine->isa('Catalyst::Engine::HTTP::POE')
2165 && $engine->VERSION eq '0.01' )
2170 elsif ($engine->isa('Catalyst::Engine::Zeus')
2171 && $engine->VERSION eq '0.01' )
2177 Catalyst::Exception->throw( message =>
2178 qq/Engine "$engine" is not supported by this version of Catalyst/
2183 $class->engine( $engine->new );
2186 =head2 $c->setup_home
2188 Sets up the home directory.
2193 my ( $class, $home ) = @_;
2195 if ( my $env = Catalyst::Utils::env_value( $class, 'HOME' ) ) {
2199 $home ||= Catalyst::Utils::home($class);
2202 #I remember recently being scolded for assigning config values like this
2203 $class->config->{home} ||= $home;
2204 $class->config->{root} ||= Path::Class::Dir->new($home)->subdir('root');
2208 =head2 $c->setup_log
2210 Sets up log by instantiating a L<Catalyst::Log|Catalyst::Log> object and
2211 passing it to C<log()>. Pass in a comma-delimited list of levels to set the
2214 This method also installs a C<debug> method that returns a true value into the
2215 catalyst subclass if the "debug" level is passed in the comma-delimited list,
2216 or if the C<$CATALYST_DEBUG> environment variable is set to a true value.
2218 Note that if the log has already been setup, by either a previous call to
2219 C<setup_log> or by a call such as C<< __PACKAGE__->log( MyLogger->new ) >>,
2220 that this method won't actually set up the log.
2225 my ( $class, $levels ) = @_;
2228 unless ( $class->log ) {
2230 $levels =~ s/^\s+//;
2231 $levels =~ s/\s+$//;
2232 %levels = map { $_ => 1 } split /\s*,\s*/, $levels || '';
2233 $class->log( Catalyst::Log->new(keys %levels) );
2236 my $env_debug = Catalyst::Utils::env_value( $class, 'DEBUG' );
2237 if ( defined($env_debug) or $levels{debug} ) {
2238 $class->Class::MOP::Object::meta()->add_method('debug' => sub { 1 });
2239 $class->log->debug('Debug messages enabled');
2243 =head2 $c->setup_plugins
2249 =head2 $c->setup_stats
2251 Sets up timing statistics class.
2256 my ( $class, $stats ) = @_;
2258 Catalyst::Utils::ensure_class_loaded($class->stats_class);
2260 my $env = Catalyst::Utils::env_value( $class, 'STATS' );
2261 if ( defined($env) ? $env : ($stats || $class->debug ) ) {
2262 $class->Class::MOP::Object::meta()->add_method('use_stats' => sub { 1 });
2263 $class->log->debug('Statistics enabled');
2268 =head2 $c->registered_plugins
2270 Returns a sorted list of the plugins which have either been stated in the
2271 import list or which have been added via C<< MyApp->plugin(@args); >>.
2273 If passed a given plugin name, it will report a boolean value indicating
2274 whether or not that plugin is loaded. A fully qualified name is required if
2275 the plugin name does not begin with C<Catalyst::Plugin::>.
2277 if ($c->registered_plugins('Some::Plugin')) {
2285 sub registered_plugins {
2287 return sort keys %{ $proto->_plugins } unless @_;
2289 return 1 if exists $proto->_plugins->{$plugin};
2290 return exists $proto->_plugins->{"Catalyst::Plugin::$plugin"};
2293 sub _register_plugin {
2294 my ( $proto, $plugin, $instant ) = @_;
2295 my $class = ref $proto || $proto;
2297 # no ignore_loaded here, the plugin may already have been
2298 # defined in memory and we don't want to error on "no file" if so
2300 Class::MOP::load_class( $plugin );
2302 $proto->_plugins->{$plugin} = 1;
2305 if ( my $meta = $class->Class::MOP::Object::meta() ) {
2306 my @superclasses = ($plugin, $meta->superclasses );
2307 $meta->superclasses(@superclasses);
2309 unshift @{"$class\::ISA"}, $plugin;
2316 my ( $class, $plugins ) = @_;
2318 $class->_plugins( {} ) unless $class->_plugins;
2320 for my $plugin ( reverse @$plugins ) {
2322 unless ( $plugin =~ s/\A\+// ) {
2323 $plugin = "Catalyst::Plugin::$plugin";
2326 $class->_register_plugin($plugin);
2333 Returns an arrayref of the internal execution stack (actions that are
2334 currently executing).
2336 =head2 $c->stats_class
2338 Returns or sets the stats (timing statistics) class.
2340 =head2 $c->use_stats
2342 Returns 1 when stats collection is enabled. Stats collection is enabled
2343 when the -Stats options is set, debug is on or when the <MYAPP>_STATS
2344 environment variable is set.
2346 Note that this is a static method, not an accessor and should be overloaded
2347 by declaring "sub use_stats { 1 }" in your MyApp.pm, not by calling $c->use_stats(1).
2354 =head2 $c->write( $data )
2356 Writes $data to the output stream. When using this method directly, you
2357 will need to manually set the C<Content-Length> header to the length of
2358 your output data, if known.
2365 # Finalize headers if someone manually writes output
2366 $c->finalize_headers;
2368 return $c->engine->write( $c, @_ );
2373 Returns the Catalyst version number. Mostly useful for "powered by"
2374 messages in template systems.
2378 sub version { return $Catalyst::VERSION }
2380 =head1 INTERNAL ACTIONS
2382 Catalyst uses internal actions like C<_DISPATCH>, C<_BEGIN>, C<_AUTO>,
2383 C<_ACTION>, and C<_END>. These are by default not shown in the private
2384 action table, but you can make them visible with a config parameter.
2386 MyApp->config->{show_internal_actions} = 1;
2388 =head1 CASE SENSITIVITY
2390 By default Catalyst is not case sensitive, so C<MyApp::C::FOO::Bar> is
2391 mapped to C</foo/bar>. You can activate case sensitivity with a config
2394 MyApp->config->{case_sensitive} = 1;
2396 This causes C<MyApp::C::Foo::Bar> to map to C</Foo/Bar>.
2398 =head1 ON-DEMAND PARSER
2400 The request body is usually parsed at the beginning of a request,
2401 but if you want to handle input yourself, you can enable on-demand
2402 parsing with a config parameter.
2404 MyApp->config->{parse_on_demand} = 1;
2406 =head1 PROXY SUPPORT
2408 Many production servers operate using the common double-server approach,
2409 with a lightweight frontend web server passing requests to a larger
2410 backend server. An application running on the backend server must deal
2411 with two problems: the remote user always appears to be C<127.0.0.1> and
2412 the server's hostname will appear to be C<localhost> regardless of the
2413 virtual host that the user connected through.
2415 Catalyst will automatically detect this situation when you are running
2416 the frontend and backend servers on the same machine. The following
2417 changes are made to the request.
2419 $c->req->address is set to the user's real IP address, as read from
2420 the HTTP X-Forwarded-For header.
2422 The host value for $c->req->base and $c->req->uri is set to the real
2423 host, as read from the HTTP X-Forwarded-Host header.
2425 Obviously, your web server must support these headers for this to work.
2427 In a more complex server farm environment where you may have your
2428 frontend proxy server(s) on different machines, you will need to set a
2429 configuration option to tell Catalyst to read the proxied data from the
2432 MyApp->config->{using_frontend_proxy} = 1;
2434 If you do not wish to use the proxy support at all, you may set:
2436 MyApp->config->{ignore_frontend_proxy} = 1;
2438 =head1 THREAD SAFETY
2440 Catalyst has been tested under Apache 2's threading C<mpm_worker>,
2441 C<mpm_winnt>, and the standalone forking HTTP server on Windows. We
2442 believe the Catalyst core to be thread-safe.
2444 If you plan to operate in a threaded environment, remember that all other
2445 modules you are using must also be thread-safe. Some modules, most notably
2446 L<DBD::SQLite>, are not thread-safe.
2452 Join #catalyst on irc.perl.org.
2456 http://lists.scsys.co.uk/cgi-bin/mailman/listinfo/catalyst
2457 http://lists.scsys.co.uk/cgi-bin/mailman/listinfo/catalyst-dev
2461 http://catalyst.perl.org
2465 http://dev.catalyst.perl.org
2469 =head2 L<Task::Catalyst> - All you need to start with Catalyst
2471 =head2 L<Catalyst::Manual> - The Catalyst Manual
2473 =head2 L<Catalyst::Component>, L<Catalyst::Base> - Base classes for components
2475 =head2 L<Catalyst::Engine> - Core engine
2477 =head2 L<Catalyst::Log> - Log class.
2479 =head2 L<Catalyst::Request> - Request object
2481 =head2 L<Catalyst::Response> - Response object
2483 =head2 L<Catalyst::Test> - The test suite.
2485 =head1 PROJECT FOUNDER
2487 sri: Sebastian Riedel <sri@cpan.org>
2493 acme: Leon Brocard <leon@astray.com>
2501 andyg: Andy Grundman <andy@hybridized.org>
2503 audreyt: Audrey Tang
2505 bricas: Brian Cassidy <bricas@cpan.org>
2507 Caelum: Rafael Kitover <rkitover@io.com>
2509 chansen: Christian Hansen
2511 chicks: Christopher Hicks
2515 dkubb: Dan Kubb <dan.kubb-cpan@onautopilot.com>
2519 esskar: Sascha Kiefer
2521 fireartist: Carl Franks <cfranks@cpan.org>
2523 gabb: Danijel Milicevic
2529 ilmari: Dagfinn Ilmari Mannsåker <ilmari@ilmari.org>
2531 jcamacho: Juan Camacho
2537 jon: Jon Schutz <jjschutz@cpan.org>
2539 marcus: Marcus Ramberg <mramberg@cpan.org>
2541 miyagawa: Tatsuhiko Miyagawa <miyagawa@bulknews.net>
2543 mst: Matt S. Trout <mst@shadowcatsystems.co.uk>
2547 naughton: David Naughton
2549 ningu: David Kamholz <dkamholz@cpan.org>
2551 nothingmuch: Yuval Kogman <nothingmuch@woobling.org>
2553 numa: Dan Sully <daniel@cpan.org>
2557 omega: Andreas Marienborg
2559 phaylon: Robert Sedlacek <phaylon@dunkelheit.at>
2561 rafl: Florian Ragwitz <rafl@debian.org>
2565 the_jester: Jesse Sheidlower
2569 willert: Sebastian Willert <willert@cpan.org>
2573 This library is free software, you can redistribute it and/or modify it under
2574 the same terms as Perl itself.
2580 __PACKAGE__->meta->make_immutable;