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;
18 use namespace::clean -except => 'meta';
21 # do these belong as package vars or should we build these via a builder method?
22 # See Catalyst-Plugin-Server for them being added to, which should be much less ugly.
24 # Preload these action types
25 our @PRELOAD = qw/Index Path Regex/;
27 # Postload these action types
28 our @POSTLOAD = qw/Default/;
30 # Note - see back-compat methods at end of file.
31 has _tree => (is => 'rw', builder => '_build__tree');
32 has dispatch_types => (is => 'rw', default => sub { [] }, required => 1, lazy => 1);
33 has _registered_dispatch_types => (is => 'rw', default => sub { {} }, required => 1, lazy => 1);
34 has _method_action_class => (is => 'rw', default => 'Catalyst::Action');
35 has _action_hash => (is => 'rw', required => 1, lazy => 1, default => sub { {} });
36 has _container_hash => (is => 'rw', required => 1, lazy => 1, default => sub { {} });
38 my %dispatch_types = ( pre => \@PRELOAD, post => \@POSTLOAD );
39 foreach my $type (keys %dispatch_types) {
40 has $type . "load_dispatch_types" => (
41 is => 'rw', required => 1, lazy => 1, default => sub { $dispatch_types{$type} },
42 traits => ['MooseX::Emulate::Class::Accessor::Fast::Meta::Role::Attribute'], # List assignment is CAF style
48 Catalyst::Dispatcher - The Catalyst Dispatcher
56 This is the class that maps public urls to actions in your Catalyst
57 application based on the attributes you set.
63 Construct a new dispatcher.
71 Catalyst::ActionContainer->new( { part => '/', actions => {} } );
73 return Tree::Simple->new($container, Tree::Simple->ROOT);
76 =head2 $self->preload_dispatch_types
78 An arrayref of pre-loaded dispatchtype classes
80 Entries are considered to be available as C<Catalyst::DispatchType::CLASS>
81 To use a custom class outside the regular C<Catalyst> namespace, prefix
82 it with a C<+>, like so:
86 =head2 $self->postload_dispatch_types
88 An arrayref of post-loaded dispatchtype classes
90 Entries are considered to be available as C<Catalyst::DispatchType::CLASS>
91 To use a custom class outside the regular C<Catalyst> namespace, prefix
92 it with a C<+>, like so:
96 =head2 $self->dispatch($c)
98 Delegate the dispatch to the action that matched the url, or return a
99 message about unknown resource
104 my ( $self, $c ) = @_;
105 if ( my $action = $c->action ) {
106 $c->forward( join( '/', '', $action->namespace, '_DISPATCH' ) );
109 my $path = $c->req->path;
111 ? qq/Unknown resource "$path"/
112 : "No default action defined";
113 $c->log->error($error) if $c->debug;
118 # $self->_command2action( $c, $command [, \@arguments ] )
119 # $self->_command2action( $c, $command [, \@captures, \@arguments ] )
120 # Search for an action, from the command and returns C<($action, $args, $captures)> on
121 # success. Returns C<(0)> on error.
123 sub _command2action {
124 my ( $self, $c, $command, @extra_params ) = @_;
127 $c->log->debug('Nothing to go to') if $c->debug;
131 my (@args, @captures);
133 if ( ref( $extra_params[-2] ) eq 'ARRAY' ) {
134 @captures = @{ splice @extra_params, -2, 1 };
137 if ( ref( $extra_params[-1] ) eq 'ARRAY' ) {
138 @args = @{ pop @extra_params }
140 # this is a copy, it may take some abuse from
141 # ->_invoke_as_path if the path had trailing parts
142 @args = @{ $c->request->arguments };
147 # go to a string path ("/foo/bar/gorch")
149 if (blessed($command) && $command->isa('Catalyst::Action')) {
153 $action = $self->_invoke_as_path( $c, "$command", \@args );
156 # go to a component ( "MyApp::*::Foo" or $c->component("...")
157 # - a path or an object)
159 my $method = @extra_params ? $extra_params[0] : "process";
160 $action = $self->_invoke_as_component( $c, $command, $method );
163 return $action, \@args, \@captures;
166 =head2 $self->visit( $c, $command [, \@arguments ] )
168 Documented in L<Catalyst>
174 $self->_do_visit('visit', @_);
180 my ( $c, $command ) = @_;
181 my ( $action, $args, $captures ) = $self->_command2action(@_);
182 my $error = qq/Couldn't $opname("$command"): /;
185 $error .= qq/Couldn't $opname to command "$command": /
186 .qq/Invalid action or component./;
188 elsif (!defined $action->namespace) {
189 $error .= qq/Action has no namespace: cannot $opname() to a plain /
190 .qq/method or component, must be an :Action of some sort./
192 elsif (!$action->class->can('_DISPATCH')) {
193 $error .= qq/Action cannot _DISPATCH. /
194 .qq/Did you try to $opname() a non-controller action?/;
202 $c->log->debug($error) if $c->debug;
206 $action = $self->expand_action($action);
208 local $c->context->request->{arguments} = $args;
209 local $c->context->request->{captures} = $captures;
210 local $c->context->{namespace} = $action->{'namespace'};
211 local $c->context->{action} = $action;
215 =head2 $self->go( $c, $command [, \@arguments ] )
217 Documented in L<Catalyst>
223 $self->_do_visit('go', @_);
224 Catalyst::Exception::Go->throw;
227 =head2 $self->forward( $c, $command [, \@arguments ] )
229 Documented in L<Catalyst>
235 no warnings 'recursion';
236 $self->_do_forward(forward => @_);
242 my ( $c, $command ) = @_;
243 my ( $action, $args, $captures ) = $self->_command2action(@_);
246 my $error .= qq/Couldn't $opname to command "$command": /
247 .qq/Invalid action or component./;
249 $c->log->debug($error) if $c->debug;
254 local $c->request->{arguments} = $args;
255 no warnings 'recursion';
256 $action->dispatch( $c );
261 =head2 $self->detach( $c, $command [, \@arguments ] )
263 Documented in L<Catalyst>
268 my ( $self, $c, $command, @args ) = @_;
269 $self->_do_forward(detach => $c, $command, @args ) if $command;
270 Catalyst::Exception::Detach->throw;
273 sub _action_rel2abs {
274 my ( $self, $c, $path ) = @_;
276 unless ( $path =~ m#^/# ) {
277 my $namespace = $c->stack->[-1]->namespace;
278 $path = "$namespace/$path";
285 sub _invoke_as_path {
286 my ( $self, $c, $rel_path, $args ) = @_;
288 my $path = $self->_action_rel2abs( $c, $rel_path );
290 my ( $tail, @extra_args );
291 while ( ( $path, $tail ) = ( $path =~ m#^(?:(.*)/)?(\w+)?$# ) )
292 { # allow $path to be empty
293 if ( my $action = $c->get_action( $tail, $path ) ) {
294 push @$args, @extra_args;
300 ; # if a match on the global namespace failed then the whole lookup failed
303 unshift @extra_args, $tail;
307 sub _find_component {
308 my ( $self, $c, $component ) = @_;
310 # fugly, why doesn't ->component('MyApp') work?
311 return $c if ($component eq blessed($c));
313 return blessed($component)
315 : $c->component($component);
318 sub _invoke_as_component {
319 my ( $self, $c, $component_or_class, $method ) = @_;
321 my $component = $self->_find_component($c, $component_or_class);
322 my $component_class = blessed $component || return 0;
324 if (my $code = $component_class->can('action_for')) {
325 my $possible_action = $component->$code($method);
326 return $possible_action if $possible_action;
329 if ( my $code = $component_class->can($method) ) {
330 return $self->_method_action_class->new(
334 reverse => "$component_class->$method",
335 class => $component_class,
336 namespace => Catalyst::Utils::class2prefix(
337 $component_class, ref($c)->config->{case_sensitive}
344 qq/Couldn't forward to "$component_class". Does not implement "$method"/;
346 $c->log->debug($error)
352 =head2 $self->prepare_action($c)
354 Find an dispatch type that matches $c->req->path, and set args from it.
359 my ( $self, $c ) = @_;
361 my $path = $req->path;
362 my @path = split /\//, $req->path;
363 $req->args( \my @args );
365 unshift( @path, '' ); # Root action
367 DESCEND: while (@path) {
368 $path = join '/', @path;
371 # Check out dispatch types to see if any will handle the path at
374 foreach my $type ( @{ $self->dispatch_types } ) {
375 last DESCEND if $type->match( $c, $path );
378 # If not, move the last part path to args
379 my $arg = pop(@path);
380 $arg =~ s/%([0-9A-Fa-f]{2})/chr(hex($1))/eg;
384 s/%([0-9A-Fa-f]{2})/chr(hex($1))/eg for grep { defined } @{$req->captures||[]};
386 $c->log->debug( 'Path is "' . $req->match . '"' )
387 if ( $c->debug && defined $req->match && length $req->match );
389 $c->log->debug( 'Arguments are "' . join( '/', @args ) . '"' )
390 if ( $c->debug && @args );
393 =head2 $self->get_action( $action, $namespace )
395 returns a named action from a given namespace.
400 my ( $self, $name, $namespace ) = @_;
403 $namespace = join( "/", grep { length } split '/', ( defined $namespace ? $namespace : "" ) );
405 return $self->_action_hash->{"${namespace}/${name}"};
408 =head2 $self->get_action_by_path( $path );
410 Returns the named action by its full private path.
414 sub get_action_by_path {
415 my ( $self, $path ) = @_;
417 $path = "/$path" unless $path =~ /\//;
418 $self->_action_hash->{$path};
421 =head2 $self->get_actions( $c, $action, $namespace )
426 my ( $self, $c, $action, $namespace ) = @_;
427 return [] unless $action;
429 $namespace = join( "/", grep { length } split '/', $namespace || "" );
431 my @match = $self->get_containers($namespace);
433 return map { $_->get_action($action) } @match;
436 =head2 $self->get_containers( $namespace )
438 Return all the action containers for a given namespace, inclusive
443 my ( $self, $namespace ) = @_;
445 $namespace = '' if $namespace eq '/';
449 if ( length $namespace ) {
451 push @containers, $self->_container_hash->{$namespace};
452 } while ( $namespace =~ s#/[^/]+$## );
455 return reverse grep { defined } @containers, $self->_container_hash->{''};
458 =head2 $self->uri_for_action($action, \@captures)
460 Takes a Catalyst::Action object and action parameters and returns a URI
461 part such that if $c->req->path were this URI part, this action would be
462 dispatched to with $c->req->captures set to the supplied arrayref.
464 If the action object is not available for external dispatch or the dispatcher
465 cannot determine an appropriate URI, this method will return undef.
470 my ( $self, $action, $captures) = @_;
472 foreach my $dispatch_type ( @{ $self->dispatch_types } ) {
473 my $uri = $dispatch_type->uri_for_action( $action, $captures );
474 return( $uri eq '' ? '/' : $uri )
482 expand an action into a full representation of the dispatch.
483 mostly useful for chained, other actions will just return a
489 my ($self, $action) = @_;
491 foreach my $dispatch_type (@{ $self->dispatch_types }) {
492 my $expanded = $dispatch_type->expand_action($action);
493 return $expanded if $expanded;
499 =head2 $self->register( $c, $action )
501 Make sure all required dispatch types for this action are loaded, then
502 pass the action to our dispatch types so they can register it if required.
503 Also, set up the tree with the action containers.
508 my ( $self, $c, $action ) = @_;
510 my $registered = $self->_registered_dispatch_types;
512 #my $priv = 0; #seems to be unused
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 eval { Class::MOP::load_class($class) };
520 push( @{ $self->dispatch_types }, $class->new ) unless $@;
521 $registered->{$class} = 1;
525 my @dtypes = @{ $self->dispatch_types };
527 my @low_precedence_dtypes;
529 for my $type ( @dtypes ) {
530 if ($type->_is_low_precedence) {
531 push @low_precedence_dtypes, $type;
533 push @normal_dtypes, $type;
537 # Pass the action to our dispatch types so they can register it if reqd.
538 my $was_registered = 0;
539 foreach my $type ( @normal_dtypes ) {
540 $was_registered = 1 if $type->register( $c, $action );
543 if (not $was_registered) {
544 foreach my $type ( @low_precedence_dtypes ) {
545 $type->register( $c, $action );
549 my $namespace = $action->namespace;
550 my $name = $action->name;
552 my $container = $self->_find_or_create_action_container($namespace);
554 # Set the method value
555 $container->add_action($action);
557 $self->_action_hash->{"$namespace/$name"} = $action;
558 $self->_container_hash->{$namespace} = $container;
561 sub _find_or_create_action_container {
562 my ( $self, $namespace ) = @_;
564 my $tree ||= $self->_tree;
566 return $tree->getNodeValue unless $namespace;
568 my @namespace = split '/', $namespace;
569 return $self->_find_or_create_namespace_node( $tree, @namespace )
573 sub _find_or_create_namespace_node {
574 my ( $self, $parent, $part, @namespace ) = @_;
576 return $parent unless $part;
579 ( grep { $_->getNodeValue->part eq $part } $parent->getAllChildren )[0];
582 my $container = Catalyst::ActionContainer->new($part);
583 $parent->addChild( $child = Tree::Simple->new($container) );
586 $self->_find_or_create_namespace_node( $child, @namespace );
589 =head2 $self->setup_actions( $class, $context )
591 Loads all of the preload dispatch types, registers their actions and then
592 loads all of the postload dispatch types, and iterates over the tree of
593 actions, displaying the debug information if appropriate.
598 my ( $self, $c ) = @_;
601 $self->_load_dispatch_types( @{ $self->preload_dispatch_types } );
602 @{ $self->_registered_dispatch_types }{@classes} = (1) x @classes;
604 foreach my $comp ( values %{ $c->components } ) {
605 $comp->register_actions($c) if $comp->can('register_actions');
608 $self->_load_dispatch_types( @{ $self->postload_dispatch_types } );
610 return unless $c->debug;
611 $self->_display_action_tables($c);
614 sub _display_action_tables {
617 my $avail_width = Catalyst::Utils::term_width() - 12;
618 my $col1_width = ($avail_width * .25) < 20 ? 20 : int($avail_width * .25);
619 my $col2_width = ($avail_width * .50) < 36 ? 36 : int($avail_width * .50);
620 my $col3_width = $avail_width - $col1_width - $col2_width;
621 my $privates = Text::SimpleTable->new(
622 [ $col1_width, 'Private' ], [ $col2_width, 'Class' ], [ $col3_width, 'Method' ]
627 my ( $walker, $parent, $prefix ) = @_;
628 $prefix .= $parent->getNodeValue || '';
629 $prefix .= '/' unless $prefix =~ /\/$/;
630 my $node = $parent->getNodeValue->actions;
632 for my $action ( keys %{$node} ) {
633 my $action_obj = $node->{$action};
635 if ( ( $action =~ /^_.*/ )
636 && ( !$c->config->{show_internal_actions} ) );
637 $privates->row( "$prefix$action", $action_obj->class, $action );
641 $walker->( $walker, $_, $prefix ) for $parent->getAllChildren;
644 $walker->( $walker, $self->_tree, '' );
645 $c->log->debug( "Loaded Private actions:\n" . $privates->draw . "\n" )
648 # List all public actions
649 $_->list($c) for @{ $self->dispatch_types };
652 sub _load_dispatch_types {
653 my ( $self, @types ) = @_;
656 # Preload action types
657 for my $type (@types) {
658 # first param is undef because we cannot get the appclass
659 my $class = Catalyst::Utils::resolve_namespace(undef, 'Catalyst::DispatchType', $type);
661 eval { Class::MOP::load_class($class) };
662 Catalyst::Exception->throw( message => qq/Couldn't load "$class"/ )
664 push @{ $self->dispatch_types }, $class->new;
666 push @loaded, $class;
672 =head2 $self->dispatch_type( $type )
674 Get the DispatchType object of the relevant type, i.e. passing C<$type> of
675 C<Chained> would return a L<Catalyst::DispatchType::Chained> object (assuming
676 of course it's being used.)
681 my ($self, $name) = @_;
683 # first param is undef because we cannot get the appclass
684 $name = Catalyst::Utils::resolve_namespace(undef, 'Catalyst::DispatchType', $name);
686 for (@{ $self->dispatch_types }) {
687 return $_ if ref($_) eq $name;
694 # 5.70 backwards compatibility hacks.
696 # Various plugins (e.g. Plugin::Server and Plugin::Authorization::ACL)
697 # need the methods here which *should* be private..
699 # You should be able to use get_actions or get_containers appropriately
700 # instead of relying on these methods which expose implementation details
701 # of the dispatcher..
703 # IRC backlog included below, please come ask if this doesn't work for you.
705 # <@t0m> 5.80, the state of. There are things in the dispatcher which have
706 # been deprecated, that we yell at anyone for using, which there isn't
707 # a good alternative for yet..
708 # <@mst> er, get_actions/get_containers provides that doesn't it?
709 # <@mst> DispatchTypes are loaded on demand anyway
710 # <@t0m> I'm thinking of things like _tree which is aliased to 'tree' with
711 # warnings otherwise shit breaks.. We're issuing warnings about the
712 # correct set of things which you shouldn't be calling..
714 # <@mst> basically, I don't see there's a need for a replacement for anything
715 # <@mst> it was never a good idea to call ->tree
716 # <@mst> nothingmuch was the only one who did AFAIK
717 # <@mst> and he admitted it was a hack ;)
719 # See also t/lib/TestApp/Plugin/AddDispatchTypes.pm
721 # Alias _method_name to method_name, add a before modifier to warn..
722 foreach my $public_method_name (qw/
724 registered_dispatch_types
729 my $private_method_name = '_' . $public_method_name;
730 my $meta = __PACKAGE__->meta; # Calling meta method here fine as we happen at compile time.
731 $meta->add_method($public_method_name, $meta->get_method($private_method_name));
733 my %package_hash; # Only warn once per method, per package. These are infrequent enough that
734 # I haven't provided a way to disable them, patches welcome.
735 $meta->add_before_method_modifier($public_method_name, sub {
736 my $class = caller(2);
738 $package_hash{$class}++ || do {
739 warn("Class $class is calling the deprecated method\n"
740 . " Catalyst::Dispatcher::$public_method_name,\n"
741 . " this will be removed in Catalyst 5.9X\n");
746 # End 5.70 backwards compatibility hacks.
748 __PACKAGE__->meta->make_immutable;
756 Catalyst Contributors, see Catalyst.pm
760 This library is free software. You can redistribute it and/or modify it under
761 the same terms as Perl itself.