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->request->{arguments} = $args;
209 local $c->request->{captures} = $captures;
210 local $c->{namespace} = $action->{'namespace'};
211 local $c->{action} = $action;
216 =head2 $self->go( $c, $command [, \@arguments ] )
218 Documented in L<Catalyst>
224 $self->_do_visit('go', @_);
225 Catalyst::Exception::Go->throw;
228 =head2 $self->forward( $c, $command [, \@arguments ] )
230 Documented in L<Catalyst>
236 no warnings 'recursion';
237 $self->_do_forward(forward => @_);
243 my ( $c, $command ) = @_;
244 my ( $action, $args, $captures ) = $self->_command2action(@_);
247 my $error .= qq/Couldn't $opname to command "$command": /
248 .qq/Invalid action or component./;
250 $c->log->debug($error) if $c->debug;
255 local $c->request->{arguments} = $args;
256 no warnings 'recursion';
257 $action->dispatch( $c );
262 =head2 $self->detach( $c, $command [, \@arguments ] )
264 Documented in L<Catalyst>
269 my ( $self, $c, $command, @args ) = @_;
270 $self->_do_forward(detach => $c, $command, @args ) if $command;
271 Catalyst::Exception::Detach->throw;
274 sub _action_rel2abs {
275 my ( $self, $c, $path ) = @_;
277 unless ( $path =~ m#^/# ) {
278 my $namespace = $c->stack->[-1]->namespace;
279 $path = "$namespace/$path";
286 sub _invoke_as_path {
287 my ( $self, $c, $rel_path, $args ) = @_;
289 my $path = $self->_action_rel2abs( $c, $rel_path );
291 my ( $tail, @extra_args );
292 while ( ( $path, $tail ) = ( $path =~ m#^(?:(.*)/)?(\w+)?$# ) )
293 { # allow $path to be empty
294 if ( my $action = $c->get_action( $tail, $path ) ) {
295 push @$args, @extra_args;
301 ; # if a match on the global namespace failed then the whole lookup failed
304 unshift @extra_args, $tail;
308 sub _find_component {
309 my ( $self, $c, $component ) = @_;
311 # fugly, why doesn't ->component('MyApp') work?
312 return $c if ($component eq blessed($c));
314 return blessed($component)
316 : $c->component($component);
319 sub _invoke_as_component {
320 my ( $self, $c, $component_or_class, $method ) = @_;
322 if( $component_or_class eq blessed($c->application) ){
323 my $possible_action = $c->application->action_for($method);
324 return $possible_action if $possible_action;
325 if( my $code = $c->application->can($method) ){
326 return $self->_method_action_class->new( {
329 reverse => "$component_or_class->$method",
330 class => $component_or_class,
331 namespace => Catalyst::Utils::class2prefix( $component_or_class ),
336 my $component = $self->_find_component($c, $component_or_class);
337 my $component_class = blessed $component || return 0;
339 if (my $code = $component_class->can('action_for')) {
340 my $possible_action = $component->$code($method);
341 return $possible_action if $possible_action;
344 if ( my $code = $component_class->can($method) ) {
345 return $self->_method_action_class->new(
349 reverse => "$component_class->$method",
350 class => $component_class,
351 namespace => Catalyst::Utils::class2prefix( $component_class ),
357 qq/Couldn't forward to "$component_class". Does not implement "$method"/;
359 $c->log->debug($error)
365 =head2 $self->prepare_action($c)
367 Find an dispatch type that matches $c->req->path, and set args from it.
372 my ( $self, $c ) = @_;
374 my $path = $req->path;
375 my @path = split /\//, $req->path;
376 $req->args( \my @args );
378 unshift( @path, '' ); # Root action
380 DESCEND: while (@path) {
381 $path = join '/', @path;
384 # Check out dispatch types to see if any will handle the path at
387 foreach my $type ( @{ $self->dispatch_types } ) {
388 last DESCEND if $type->match( $c, $path );
391 # If not, move the last part path to args
392 my $arg = pop(@path);
393 $arg =~ s/%([0-9A-Fa-f]{2})/chr(hex($1))/eg;
397 s/%([0-9A-Fa-f]{2})/chr(hex($1))/eg for grep { defined } @{$req->captures||[]};
399 $c->log->debug( 'Path is "' . $req->match . '"' )
400 if ( $c->debug && defined $req->match && length $req->match );
402 $c->log->debug( 'Arguments are "' . join( '/', @args ) . '"' )
403 if ( $c->debug && @args );
406 =head2 $self->get_action( $action, $namespace )
408 returns a named action from a given namespace.
413 my ( $self, $name, $namespace ) = @_;
416 $namespace = join( "/", grep { length } split '/', ( defined $namespace ? $namespace : "" ) );
418 return $self->_action_hash->{"${namespace}/${name}"};
421 =head2 $self->get_action_by_path( $path );
423 Returns the named action by its full private path.
427 sub get_action_by_path {
428 my ( $self, $path ) = @_;
430 $path = "/$path" unless $path =~ /\//;
431 $self->_action_hash->{$path};
434 =head2 $self->get_actions( $c, $action, $namespace )
439 my ( $self, $c, $action, $namespace ) = @_;
440 return [] unless $action;
442 $namespace = join( "/", grep { length } split '/', $namespace || "" );
444 my @match = $self->get_containers($namespace);
446 return map { $_->get_action($action) } @match;
449 =head2 $self->get_containers( $namespace )
451 Return all the action containers for a given namespace, inclusive
456 my ( $self, $namespace ) = @_;
458 $namespace = '' if $namespace eq '/';
462 if ( length $namespace ) {
464 push @containers, $self->_container_hash->{$namespace};
465 } while ( $namespace =~ s#/[^/]+$## );
468 return reverse grep { defined } @containers, $self->_container_hash->{''};
471 =head2 $self->uri_for_action($action, \@captures)
473 Takes a Catalyst::Action object and action parameters and returns a URI
474 part such that if $c->req->path were this URI part, this action would be
475 dispatched to with $c->req->captures set to the supplied arrayref.
477 If the action object is not available for external dispatch or the dispatcher
478 cannot determine an appropriate URI, this method will return undef.
483 my ( $self, $action, $captures) = @_;
485 foreach my $dispatch_type ( @{ $self->dispatch_types } ) {
486 my $uri = $dispatch_type->uri_for_action( $action, $captures );
487 return( $uri eq '' ? '/' : $uri )
495 expand an action into a full representation of the dispatch.
496 mostly useful for chained, other actions will just return a
502 my ($self, $action) = @_;
504 foreach my $dispatch_type (@{ $self->dispatch_types }) {
505 my $expanded = $dispatch_type->expand_action($action);
506 return $expanded if $expanded;
512 =head2 $self->register( $c, $action )
514 Make sure all required dispatch types for this action are loaded, then
515 pass the action to our dispatch types so they can register it if required.
516 Also, set up the tree with the action containers.
521 my ( $self, $c, $action ) = @_;
523 my $registered = $self->_registered_dispatch_types;
525 #my $priv = 0; #seems to be unused
526 foreach my $key ( keys %{ $action->attributes } ) {
527 next if $key eq 'Private';
528 my $class = "Catalyst::DispatchType::$key";
529 unless ( $registered->{$class} ) {
530 # FIXME - Some error checking and re-throwing needed here, as
531 # we eat exceptions loading dispatch types.
532 eval { Class::MOP::load_class($class) };
533 push( @{ $self->dispatch_types }, $class->new ) unless $@;
534 $registered->{$class} = 1;
538 my @dtypes = @{ $self->dispatch_types };
540 my @low_precedence_dtypes;
542 for my $type ( @dtypes ) {
543 if ($type->_is_low_precedence) {
544 push @low_precedence_dtypes, $type;
546 push @normal_dtypes, $type;
550 # Pass the action to our dispatch types so they can register it if reqd.
551 my $was_registered = 0;
552 foreach my $type ( @normal_dtypes ) {
553 $was_registered = 1 if $type->register( $c, $action );
556 if (not $was_registered) {
557 foreach my $type ( @low_precedence_dtypes ) {
558 $type->register( $c, $action );
562 my $namespace = $action->namespace;
563 my $name = $action->name;
565 my $container = $self->_find_or_create_action_container($namespace);
567 # Set the method value
568 $container->add_action($action);
570 $self->_action_hash->{"$namespace/$name"} = $action;
571 $self->_container_hash->{$namespace} = $container;
574 sub _find_or_create_action_container {
575 my ( $self, $namespace ) = @_;
577 my $tree ||= $self->_tree;
579 return $tree->getNodeValue unless $namespace;
581 my @namespace = split '/', $namespace;
582 return $self->_find_or_create_namespace_node( $tree, @namespace )
586 sub _find_or_create_namespace_node {
587 my ( $self, $parent, $part, @namespace ) = @_;
589 return $parent unless $part;
592 ( grep { $_->getNodeValue->part eq $part } $parent->getAllChildren )[0];
595 my $container = Catalyst::ActionContainer->new($part);
596 $parent->addChild( $child = Tree::Simple->new($container) );
599 $self->_find_or_create_namespace_node( $child, @namespace );
602 =head2 $self->setup_actions( $class, $context )
604 Loads all of the preload dispatch types, registers their actions and then
605 loads all of the postload dispatch types, and iterates over the tree of
606 actions, displaying the debug information if appropriate.
611 my ( $self, $c ) = @_;
614 $self->_load_dispatch_types( @{ $self->preload_dispatch_types } );
615 @{ $self->_registered_dispatch_types }{@classes} = (1) x @classes;
617 foreach my $comp ( values %{ $c->components } ) {
618 $comp->register_actions($c) if $comp->can('register_actions');
621 $self->_load_dispatch_types( @{ $self->postload_dispatch_types } );
623 return unless $c->debug;
624 $self->_display_action_tables($c);
627 sub _display_action_tables {
630 my $avail_width = Catalyst::Utils::term_width() - 12;
631 my $col1_width = ($avail_width * .25) < 20 ? 20 : int($avail_width * .25);
632 my $col2_width = ($avail_width * .50) < 36 ? 36 : int($avail_width * .50);
633 my $col3_width = $avail_width - $col1_width - $col2_width;
634 my $privates = Text::SimpleTable->new(
635 [ $col1_width, 'Private' ], [ $col2_width, 'Class' ], [ $col3_width, 'Method' ]
640 my ( $walker, $parent, $prefix ) = @_;
641 $prefix .= $parent->getNodeValue || '';
642 $prefix .= '/' unless $prefix =~ /\/$/;
643 my $node = $parent->getNodeValue->actions;
645 for my $action ( keys %{$node} ) {
646 my $action_obj = $node->{$action};
648 if ( ( $action =~ /^_.*/ )
649 && ( !$c->config->{show_internal_actions} ) );
650 $privates->row( "$prefix$action", $action_obj->class, $action );
654 $walker->( $walker, $_, $prefix ) for $parent->getAllChildren;
657 $walker->( $walker, $self->_tree, '' );
658 $c->log->debug( "Loaded Private actions:\n" . $privates->draw . "\n" )
661 # List all public actions
662 $_->list($c) for @{ $self->dispatch_types };
665 sub _load_dispatch_types {
666 my ( $self, @types ) = @_;
669 # Preload action types
670 for my $type (@types) {
671 # first param is undef because we cannot get the appclass
672 my $class = Catalyst::Utils::resolve_namespace(undef, 'Catalyst::DispatchType', $type);
674 eval { Class::MOP::load_class($class) };
675 Catalyst::Exception->throw( message => qq/Couldn't load "$class"/ )
677 push @{ $self->dispatch_types }, $class->new;
679 push @loaded, $class;
685 =head2 $self->dispatch_type( $type )
687 Get the DispatchType object of the relevant type, i.e. passing C<$type> of
688 C<Chained> would return a L<Catalyst::DispatchType::Chained> object (assuming
689 of course it's being used.)
694 my ($self, $name) = @_;
696 # first param is undef because we cannot get the appclass
697 $name = Catalyst::Utils::resolve_namespace(undef, 'Catalyst::DispatchType', $name);
699 for (@{ $self->dispatch_types }) {
700 return $_ if ref($_) eq $name;
707 # 5.70 backwards compatibility hacks.
709 # Various plugins (e.g. Plugin::Server and Plugin::Authorization::ACL)
710 # need the methods here which *should* be private..
712 # You should be able to use get_actions or get_containers appropriately
713 # instead of relying on these methods which expose implementation details
714 # of the dispatcher..
716 # IRC backlog included below, please come ask if this doesn't work for you.
718 # <@t0m> 5.80, the state of. There are things in the dispatcher which have
719 # been deprecated, that we yell at anyone for using, which there isn't
720 # a good alternative for yet..
721 # <@mst> er, get_actions/get_containers provides that doesn't it?
722 # <@mst> DispatchTypes are loaded on demand anyway
723 # <@t0m> I'm thinking of things like _tree which is aliased to 'tree' with
724 # warnings otherwise shit breaks.. We're issuing warnings about the
725 # correct set of things which you shouldn't be calling..
727 # <@mst> basically, I don't see there's a need for a replacement for anything
728 # <@mst> it was never a good idea to call ->tree
729 # <@mst> nothingmuch was the only one who did AFAIK
730 # <@mst> and he admitted it was a hack ;)
732 # See also t/lib/TestApp/Plugin/AddDispatchTypes.pm
734 # Alias _method_name to method_name, add a before modifier to warn..
735 foreach my $public_method_name (qw/
737 registered_dispatch_types
742 my $private_method_name = '_' . $public_method_name;
743 my $meta = __PACKAGE__->meta; # Calling meta method here fine as we happen at compile time.
744 $meta->add_method($public_method_name, $meta->get_method($private_method_name));
746 my %package_hash; # Only warn once per method, per package. These are infrequent enough that
747 # I haven't provided a way to disable them, patches welcome.
748 $meta->add_before_method_modifier($public_method_name, sub {
749 my $class = caller(2);
751 $package_hash{$class}++ || do {
752 warn("Class $class is calling the deprecated method\n"
753 . " Catalyst::Dispatcher::$public_method_name,\n"
754 . " this will be removed in Catalyst 5.9X\n");
759 # End 5.70 backwards compatibility hacks.
761 __PACKAGE__->meta->make_immutable;
769 Catalyst Contributors, see Catalyst.pm
773 This library is free software. You can redistribute it and/or modify it under
774 the same terms as Perl itself.