1 package Catalyst::Dispatcher;
5 with 'MooseX::Emulate::Class::Accessor::Fast';
7 use Catalyst::Exception;
10 use Catalyst::ActionContainer;
11 use Catalyst::DispatchType::Default;
12 use Catalyst::DispatchType::Index;
14 use Text::SimpleTable;
16 use Tree::Simple::Visitor::FindByPath;
17 use Class::Load qw(load_class try_load_class);
19 use namespace::clean -except => 'meta';
22 # do these belong as package vars or should we build these via a builder method?
23 # See Catalyst-Plugin-Server for them being added to, which should be much less ugly.
25 # Preload these action types
26 our @PRELOAD = qw/Index Path/;
28 # Postload these action types
29 our @POSTLOAD = qw/Default/;
31 # Note - see back-compat methods at end of file.
32 has _tree => (is => 'rw', builder => '_build__tree');
33 has dispatch_types => (is => 'rw', default => sub { [] }, required => 1, lazy => 1);
34 has _registered_dispatch_types => (is => 'rw', default => sub { {} }, required => 1, lazy => 1);
35 has _method_action_class => (is => 'rw', default => 'Catalyst::Action');
36 has _action_hash => (is => 'rw', required => 1, lazy => 1, default => sub { {} });
37 has _container_hash => (is => 'rw', required => 1, lazy => 1, default => sub { {} });
39 my %dispatch_types = ( pre => \@PRELOAD, post => \@POSTLOAD );
40 foreach my $type (keys %dispatch_types) {
41 has $type . "load_dispatch_types" => (
42 is => 'rw', required => 1, lazy => 1, default => sub { $dispatch_types{$type} },
43 traits => ['MooseX::Emulate::Class::Accessor::Fast::Meta::Role::Attribute'], # List assignment is CAF style
49 Catalyst::Dispatcher - The Catalyst Dispatcher
57 This is the class that maps public urls to actions in your Catalyst
58 application based on the attributes you set.
64 Construct a new dispatcher.
72 Catalyst::ActionContainer->new( { part => '/', actions => {} } );
74 return Tree::Simple->new($container, Tree::Simple->ROOT);
77 =head2 $self->preload_dispatch_types
79 An arrayref of pre-loaded dispatchtype classes
81 Entries are considered to be available as C<Catalyst::DispatchType::CLASS>
82 To use a custom class outside the regular C<Catalyst> namespace, prefix
83 it with a C<+>, like so:
87 =head2 $self->postload_dispatch_types
89 An arrayref of post-loaded dispatchtype classes
91 Entries are considered to be available as C<Catalyst::DispatchType::CLASS>
92 To use a custom class outside the regular C<Catalyst> namespace, prefix
93 it with a C<+>, like so:
97 =head2 $self->dispatch($c)
99 Delegate the dispatch to the action that matched the url, or return a
100 message about unknown resource
105 my ( $self, $c ) = @_;
106 if ( my $action = $c->action ) {
107 $c->forward( join( '/', '', $action->namespace, '_DISPATCH' ) );
110 my $path = $c->req->path;
112 ? qq/Unknown resource "$path"/
113 : "No default action defined";
114 $c->trace(1, $error);
119 # $self->_command2action( $c, $command [, \@arguments ] )
120 # $self->_command2action( $c, $command [, \@captures, \@arguments ] )
121 # Search for an action, from the command and returns C<($action, $args, $captures)> on
122 # success. Returns C<(0)> on error.
124 sub _command2action {
125 my ( $self, $c, $command, @extra_params ) = @_;
128 $c->trace(1,'Nothing to go to');
132 my (@args, @captures);
134 if ( ref( $extra_params[-2] ) eq 'ARRAY' ) {
135 @captures = @{ splice @extra_params, -2, 1 };
138 if ( ref( $extra_params[-1] ) eq 'ARRAY' ) {
139 @args = @{ pop @extra_params }
141 # this is a copy, it may take some abuse from
142 # ->_invoke_as_path if the path had trailing parts
143 @args = @{ $c->request->arguments };
148 # go to a string path ("/foo/bar/gorch")
150 if (blessed($command) && $command->isa('Catalyst::Action')) {
154 $action = $self->_invoke_as_path( $c, "$command", \@args );
157 # go to a component ( "View::Foo" or $c->component("...")
158 # - a path or an object)
160 my $method = @extra_params ? $extra_params[0] : "process";
161 $action = $self->_invoke_as_component( $c, $command, $method );
164 return $action, \@args, \@captures;
167 =head2 $self->visit( $c, $command [, \@arguments ] )
169 Documented in L<Catalyst>
175 $self->_do_visit('visit', @_);
181 my ( $c, $command ) = @_;
182 my ( $action, $args, $captures ) = $self->_command2action(@_);
183 my $error = qq/Couldn't $opname("$command"): /;
186 $error .= qq/Couldn't $opname to command "$command": /
187 .qq/Invalid action or component./;
189 elsif (!defined $action->namespace) {
190 $error .= qq/Action has no namespace: cannot $opname() to a plain /
191 .qq/method or component, must be an :Action of some sort./
193 elsif (!$action->class->can('_DISPATCH')) {
194 $error .= qq/Action cannot _DISPATCH. /
195 .qq/Did you try to $opname() a non-controller action?/;
207 $action = $self->expand_action($action);
209 local $c->request->{arguments} = $args;
210 local $c->request->{captures} = $captures;
211 local $c->{namespace} = $action->{'namespace'};
212 local $c->{action} = $action;
217 =head2 $self->go( $c, $command [, \@arguments ] )
219 Documented in L<Catalyst>
225 $self->_do_visit('go', @_);
226 Catalyst::Exception::Go->throw;
229 =head2 $self->forward( $c, $command [, \@arguments ] )
231 Documented in L<Catalyst>
237 no warnings 'recursion';
238 $self->_do_forward(forward => @_);
244 my ( $c, $command ) = @_;
245 my ( $action, $args, $captures ) = $self->_command2action(@_);
248 my $error .= qq/Couldn't $opname to command "$command": /
249 .qq/Invalid action or component./;
256 local $c->request->{arguments} = $args;
257 no warnings 'recursion';
258 $action->dispatch( $c );
263 =head2 $self->detach( $c, $command [, \@arguments ] )
265 Documented in L<Catalyst>
270 my ( $self, $c, $command, @args ) = @_;
271 $self->_do_forward(detach => $c, $command, @args ) if $command;
272 Catalyst::Exception::Detach->throw;
275 sub _action_rel2abs {
276 my ( $self, $c, $path ) = @_;
278 unless ( $path =~ m#^/# ) {
279 my $namespace = $c->stack->[-1]->namespace;
280 $path = "$namespace/$path";
287 sub _invoke_as_path {
288 my ( $self, $c, $rel_path, $args ) = @_;
290 my $path = $self->_action_rel2abs( $c, $rel_path );
292 my ( $tail, @extra_args );
293 while ( ( $path, $tail ) = ( $path =~ m#^(?:(.*)/)?(\w+)?$# ) )
294 { # allow $path to be empty
295 if ( my $action = $c->get_action( $tail, $path ) ) {
296 push @$args, @extra_args;
302 ; # if a match on the global namespace failed then the whole lookup failed
305 unshift @extra_args, $tail;
309 sub _find_component {
310 my ( $self, $c, $component ) = @_;
312 # fugly, why doesn't ->component('MyApp') work?
313 return $c if ($component eq blessed($c));
315 return blessed($component)
317 : $c->component($component);
320 sub _invoke_as_component {
321 my ( $self, $c, $component_or_class, $method ) = @_;
323 my $component = $self->_find_component($c, $component_or_class);
324 my $component_class = blessed $component || return 0;
326 if (my $code = $component_class->can('action_for')) {
327 my $possible_action = $component->$code($method);
328 return $possible_action if $possible_action;
331 if ( my $code = $component_class->can($method) ) {
332 return $self->_method_action_class->new(
336 reverse => "$component_class->$method",
337 class => $component_class,
338 namespace => Catalyst::Utils::class2prefix(
339 $component_class, ref($c)->config->{case_sensitive}
346 qq/Couldn't forward to "$component_class". Does not implement "$method"/;
353 =head2 $self->prepare_action($c)
355 Find an dispatch type that matches $c->req->path, and set args from it.
360 my ( $self, $c ) = @_;
362 my $path = $req->path;
363 my @path = split /\//, $req->path;
364 $req->args( \my @args );
366 unshift( @path, '' ); # Root action
368 DESCEND: while (@path) {
369 $path = join '/', @path;
372 # Check out dispatch types to see if any will handle the path at
375 foreach my $type ( @{ $self->dispatch_types } ) {
376 last DESCEND if $type->match( $c, $path );
379 # If not, move the last part path to args
380 my $arg = pop(@path);
381 $arg =~ s/%([0-9A-Fa-f]{2})/chr(hex($1))/eg;
385 s/%([0-9A-Fa-f]{2})/chr(hex($1))/eg for grep { defined } @{$req->captures||[]};
387 $c->trace(1, 'Path is "' . $req->match . '"' )
388 if (defined $req->match && length $req->match );
390 $c->trace(1, 'Arguments are "' . join( '/', @args ) . '"' )
394 =head2 $self->get_action( $action, $namespace )
396 returns a named action from a given namespace.
401 my ( $self, $name, $namespace ) = @_;
404 $namespace = join( "/", grep { length } split '/', ( defined $namespace ? $namespace : "" ) );
406 return $self->_action_hash->{"${namespace}/${name}"};
409 =head2 $self->get_action_by_path( $path );
411 Returns the named action by its full private path.
415 sub get_action_by_path {
416 my ( $self, $path ) = @_;
418 $path = "/$path" unless $path =~ /\//;
419 $self->_action_hash->{$path};
422 =head2 $self->get_actions( $c, $action, $namespace )
427 my ( $self, $c, $action, $namespace ) = @_;
428 return [] unless $action;
430 $namespace = join( "/", grep { length } split '/', $namespace || "" );
432 my @match = $self->get_containers($namespace);
434 return map { $_->get_action($action) } @match;
437 =head2 $self->get_containers( $namespace )
439 Return all the action containers for a given namespace, inclusive
444 my ( $self, $namespace ) = @_;
446 $namespace = '' if $namespace eq '/';
450 if ( length $namespace ) {
452 push @containers, $self->_container_hash->{$namespace};
453 } while ( $namespace =~ s#/[^/]+$## );
456 return reverse grep { defined } @containers, $self->_container_hash->{''};
459 =head2 $self->uri_for_action($action, \@captures)
461 Takes a Catalyst::Action object and action parameters and returns a URI
462 part such that if $c->req->path were this URI part, this action would be
463 dispatched to with $c->req->captures set to the supplied arrayref.
465 If the action object is not available for external dispatch or the dispatcher
466 cannot determine an appropriate URI, this method will return undef.
471 my ( $self, $action, $captures) = @_;
473 foreach my $dispatch_type ( @{ $self->dispatch_types } ) {
474 my $uri = $dispatch_type->uri_for_action( $action, $captures );
475 return( $uri eq '' ? '/' : $uri )
483 expand an action into a full representation of the dispatch.
484 mostly useful for chained, other actions will just return a
490 my ($self, $action) = @_;
492 foreach my $dispatch_type (@{ $self->dispatch_types }) {
493 my $expanded = $dispatch_type->expand_action($action);
494 return $expanded if $expanded;
500 =head2 $self->register( $c, $action )
502 Make sure all required dispatch types for this action are loaded, then
503 pass the action to our dispatch types so they can register it if required.
504 Also, set up the tree with the action containers.
509 my ( $self, $c, $action ) = @_;
511 my $registered = $self->_registered_dispatch_types;
513 foreach my $key ( keys %{ $action->attributes } ) {
514 next if $key eq 'Private';
515 my $class = "Catalyst::DispatchType::$key";
516 unless ( $registered->{$class} ) {
517 # FIXME - Some error checking and re-throwing needed here, as
518 # we eat exceptions loading dispatch types.
519 # see also try_load_class
520 eval { load_class($class) };
521 my $load_failed = $@;
522 $self->_check_deprecated_dispatch_type( $key, $load_failed );
523 push( @{ $self->dispatch_types }, $class->new ) unless $load_failed;
524 $registered->{$class} = 1;
528 my @dtypes = @{ $self->dispatch_types };
530 my @low_precedence_dtypes;
532 for my $type ( @dtypes ) {
533 if ($type->_is_low_precedence) {
534 push @low_precedence_dtypes, $type;
536 push @normal_dtypes, $type;
540 # Pass the action to our dispatch types so they can register it if reqd.
541 my $was_registered = 0;
542 foreach my $type ( @normal_dtypes ) {
543 $was_registered = 1 if $type->register( $c, $action );
546 if (not $was_registered) {
547 foreach my $type ( @low_precedence_dtypes ) {
548 $type->register( $c, $action );
552 my $namespace = $action->namespace;
553 my $name = $action->name;
555 my $container = $self->_find_or_create_action_container($namespace);
557 # Set the method value
558 $container->add_action($action);
560 $self->_action_hash->{"$namespace/$name"} = $action;
561 $self->_container_hash->{$namespace} = $container;
564 sub _find_or_create_action_container {
565 my ( $self, $namespace ) = @_;
567 my $tree ||= $self->_tree;
569 return $tree->getNodeValue unless $namespace;
571 my @namespace = split '/', $namespace;
572 return $self->_find_or_create_namespace_node( $tree, @namespace )
576 sub _find_or_create_namespace_node {
577 my ( $self, $parent, $part, @namespace ) = @_;
579 return $parent unless $part;
582 ( grep { $_->getNodeValue->part eq $part } $parent->getAllChildren )[0];
585 my $container = Catalyst::ActionContainer->new($part);
586 $parent->addChild( $child = Tree::Simple->new($container) );
589 $self->_find_or_create_namespace_node( $child, @namespace );
592 =head2 $self->setup_actions( $class, $context )
594 Loads all of the pre-load dispatch types, registers their actions and then
595 loads all of the post-load dispatch types, and iterates over the tree of
596 actions, displaying the debug information if appropriate.
601 my ( $self, $c ) = @_;
604 $self->_load_dispatch_types( @{ $self->preload_dispatch_types } );
605 @{ $self->_registered_dispatch_types }{@classes} = (1) x @classes;
607 foreach my $comp ( values %{ $c->components } ) {
608 $comp->register_actions($c) if $comp->can('register_actions');
611 $self->_load_dispatch_types( @{ $self->postload_dispatch_types } );
613 return unless $c->trace_level;
614 $self->_display_action_tables($c);
617 sub _display_action_tables {
620 my $avail_width = Catalyst::Utils::term_width() - 12;
621 my $col1_width = ($avail_width * .25) < 20 ? 20 : int($avail_width * .25);
622 my $col2_width = ($avail_width * .50) < 36 ? 36 : int($avail_width * .50);
623 my $col3_width = $avail_width - $col1_width - $col2_width;
624 my $privates = Text::SimpleTable->new(
625 [ $col1_width, 'Private' ], [ $col2_width, 'Class' ], [ $col3_width, 'Method' ]
630 my ( $walker, $parent, $prefix ) = @_;
631 $prefix .= $parent->getNodeValue || '';
632 $prefix .= '/' unless $prefix =~ /\/$/;
633 my $node = $parent->getNodeValue->actions;
635 for my $action ( keys %{$node} ) {
636 my $action_obj = $node->{$action};
638 if ( ( $action =~ /^_.*/ )
639 && ( !$c->config->{show_internal_actions} ) );
640 $privates->row( "$prefix$action", $action_obj->class, $action );
644 $walker->( $walker, $_, $prefix ) for $parent->getAllChildren;
647 $walker->( $walker, $self->_tree, '' );
648 $c->trace(1, "Loaded Private actions:\n" . $privates->draw . "\n" )
651 # List all public actions
652 $_->list($c) for @{ $self->dispatch_types };
655 sub _load_dispatch_types {
656 my ( $self, @types ) = @_;
659 # Preload action types
660 for my $type (@types) {
661 # first param is undef because we cannot get the appclass
662 my $class = Catalyst::Utils::resolve_namespace(undef, 'Catalyst::DispatchType', $type);
664 my ($success, $error) = try_load_class($class);
665 Catalyst::Exception->throw( message => $error ) if not $success;
666 push @{ $self->dispatch_types }, $class->new;
668 push @loaded, $class;
674 =head2 $self->dispatch_type( $type )
676 Get the DispatchType object of the relevant type, i.e. passing C<$type> of
677 C<Chained> would return a L<Catalyst::DispatchType::Chained> object (assuming
678 of course it's being used.)
683 my ($self, $name) = @_;
685 # first param is undef because we cannot get the appclass
686 $name = Catalyst::Utils::resolve_namespace(undef, 'Catalyst::DispatchType', $name);
688 for (@{ $self->dispatch_types }) {
689 return $_ if ref($_) eq $name;
694 sub _check_deprecated_dispatch_type {
695 my ($self, $key, $load_failed) = @_;
697 return unless $key =~ /^(Local)?Regexp?/;
699 # TODO: Should these throw an exception rather than just warning?
701 warn( "Attempt to use deprecated $key dispatch type.\n"
702 . " Use Chained methods or install the standalone\n"
703 . " Catalyst::DispatchType::Regex if necessary.\n" );
704 } elsif ( !defined $Catalyst::DispatchType::Regex::VERSION
705 || $Catalyst::DispatchType::Regex::VERSION le '5.90020' ) {
706 # We loaded the old core version of the Regex module this will break
707 warn( "The $key DispatchType has been removed from Catalyst core.\n"
708 . " An old version of the core Catalyst::DispatchType::Regex\n"
709 . " has been loaded and will likely fail. Please remove\n"
710 . " $INC{'Catalyst/DispatchType/Regex.pm'}\n"
711 . " and use Chained methods or install the standalone\n"
712 . " Catalyst::DispatchType::Regex if necessary.\n" );
718 # 5.70 backwards compatibility hacks.
720 # Various plugins (e.g. Plugin::Server and Plugin::Authorization::ACL)
721 # need the methods here which *should* be private..
723 # You should be able to use get_actions or get_containers appropriately
724 # instead of relying on these methods which expose implementation details
725 # of the dispatcher..
727 # IRC backlog included below, please come ask if this doesn't work for you.
729 # <@t0m> 5.80, the state of. There are things in the dispatcher which have
730 # been deprecated, that we yell at anyone for using, which there isn't
731 # a good alternative for yet..
732 # <@mst> er, get_actions/get_containers provides that doesn't it?
733 # <@mst> DispatchTypes are loaded on demand anyway
734 # <@t0m> I'm thinking of things like _tree which is aliased to 'tree' with
735 # warnings otherwise shit breaks.. We're issuing warnings about the
736 # correct set of things which you shouldn't be calling..
738 # <@mst> basically, I don't see there's a need for a replacement for anything
739 # <@mst> it was never a good idea to call ->tree
740 # <@mst> nothingmuch was the only one who did AFAIK
741 # <@mst> and he admitted it was a hack ;)
743 # See also t/lib/TestApp/Plugin/AddDispatchTypes.pm
745 # Alias _method_name to method_name, add a before modifier to warn..
746 foreach my $public_method_name (qw/
748 registered_dispatch_types
753 my $private_method_name = '_' . $public_method_name;
754 my $meta = __PACKAGE__->meta; # Calling meta method here fine as we happen at compile time.
755 $meta->add_method($public_method_name, $meta->get_method($private_method_name));
757 my %package_hash; # Only warn once per method, per package. These are infrequent enough that
758 # I haven't provided a way to disable them, patches welcome.
759 $meta->add_before_method_modifier($public_method_name, sub {
760 my $class = caller(2);
762 $package_hash{$class}++ || do {
763 warn("Class $class is calling the deprecated method\n"
764 . " Catalyst::Dispatcher::$public_method_name,\n"
765 . " this will be removed in Catalyst 5.9\n");
770 # End 5.70 backwards compatibility hacks.
772 __PACKAGE__->meta->make_immutable;
780 Catalyst Contributors, see Catalyst.pm
784 This library is free software. You can redistribute it and/or modify it under
785 the same terms as Perl itself.