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 { {} });
37 has preload_dispatch_types => (is => 'rw', required => 1, lazy => 1, default => sub { [@PRELOAD] });
39 has postload_dispatch_types => (is => 'rw', required => 1, lazy => 1, default => sub { [@POSTLOAD] });
41 # Wrap accessors so you can assign a list and it will capture a list ref.
42 around qw/preload_dispatch_types postload_dispatch_types/ => sub {
45 return $self->$orig([@_]) if (scalar @_ && ref $_[0] ne 'ARRAY');
46 return $self->$orig(@_);
51 Catalyst::Dispatcher - The Catalyst Dispatcher
59 This is the class that maps public urls to actions in your Catalyst
60 application based on the attributes you set.
66 Construct a new dispatcher.
74 Catalyst::ActionContainer->new( { part => '/', actions => {} } );
76 return Tree::Simple->new($container, Tree::Simple->ROOT);
79 =head2 $self->preload_dispatch_types
81 An arrayref of pre-loaded dispatchtype classes
83 Entries are considered to be available as C<Catalyst::DispatchType::CLASS>
84 To use a custom class outside the regular C<Catalyst> namespace, prefix
85 it with a C<+>, like so:
89 =head2 $self->postload_dispatch_types
91 An arrayref of post-loaded dispatchtype classes
93 Entries are considered to be available as C<Catalyst::DispatchType::CLASS>
94 To use a custom class outside the regular C<Catalyst> namespace, prefix
95 it with a C<+>, like so:
99 =head2 $self->dispatch($c)
101 Delegate the dispatch to the action that matched the url, or return a
102 message about unknown resource
107 my ( $self, $c ) = @_;
108 if ( my $action = $c->action ) {
109 $c->forward( join( '/', '', $action->namespace, '_DISPATCH' ) );
112 my $path = $c->req->path;
114 ? qq/Unknown resource "$path"/
115 : "No default action defined";
116 $c->log->error($error) if $c->debug;
121 # $self->_command2action( $c, $command [, \@arguments ] )
122 # $self->_command2action( $c, $command [, \@captures, \@arguments ] )
123 # Search for an action, from the command and returns C<($action, $args, $captures)> on
124 # success. Returns C<(0)> on error.
126 sub _command2action {
127 my ( $self, $c, $command, @extra_params ) = @_;
130 $c->log->debug('Nothing to go to') if $c->debug;
134 my (@args, @captures);
136 if ( ref( $extra_params[-2] ) eq 'ARRAY' ) {
137 @captures = @{ pop @extra_params };
140 if ( ref( $extra_params[-1] ) eq 'ARRAY' ) {
141 @args = @{ pop @extra_params }
143 # this is a copy, it may take some abuse from
144 # ->_invoke_as_path if the path had trailing parts
145 @args = @{ $c->request->arguments };
150 # go to a string path ("/foo/bar/gorch")
152 if (blessed($command) && $command->isa('Catalyst::Action')) {
156 $action = $self->_invoke_as_path( $c, "$command", \@args );
159 # go to a component ( "MyApp::*::Foo" or $c->component("...")
160 # - a path or an object)
162 my $method = @extra_params ? $extra_params[0] : "process";
163 $action = $self->_invoke_as_component( $c, $command, $method );
166 return $action, \@args, \@captures;
169 =head2 $self->visit( $c, $command [, \@arguments ] )
171 Documented in L<Catalyst>
177 $self->_do_visit('visit', @_);
183 my ( $c, $command ) = @_;
184 my ( $action, $args, $captures ) = $self->_command2action(@_);
185 my $error = qq/Couldn't $opname("$command"): /;
188 $error .= qq/Couldn't $opname to command "$command": /
189 .qq/Invalid action or component./;
191 elsif (!defined $action->namespace) {
192 $error .= qq/Action has no namespace: cannot $opname() to a plain /
193 .qq/method or component, must be an :Action of some sort./
195 elsif (!$action->class->can('_DISPATCH')) {
196 $error .= qq/Action cannot _DISPATCH. /
197 .qq/Did you try to $opname() a non-controller action?/;
205 $c->log->debug($error) if $c->debug;
209 $action = $self->expand_action($action);
211 local $c->request->{arguments} = $args;
212 local $c->request->{captures} = $captures;
213 local $c->{namespace} = $action->{'namespace'};
214 local $c->{action} = $action;
219 =head2 $self->go( $c, $command [, \@arguments ] )
221 Documented in L<Catalyst>
227 $self->_do_visit('go', @_);
231 =head2 $self->forward( $c, $command [, \@arguments ] )
233 Documented in L<Catalyst>
239 no warnings 'recursion';
240 $self->_do_forward(forward => @_);
246 my ( $c, $command ) = @_;
247 my ( $action, $args, $captures ) = $self->_command2action(@_);
250 my $error .= qq/Couldn't $opname to command "$command": /
251 .qq/Invalid action or component./;
253 $c->log->debug($error) if $c->debug;
258 local $c->request->{arguments} = $args;
259 no warnings 'recursion';
260 $action->dispatch( $c );
265 =head2 $self->detach( $c, $command [, \@arguments ] )
267 Documented in L<Catalyst>
272 my ( $self, $c, $command, @args ) = @_;
273 $self->_do_forward(detach => $c, $command, @args ) if $command;
274 die $Catalyst::DETACH;
277 sub _action_rel2abs {
278 my ( $self, $c, $path ) = @_;
280 unless ( $path =~ m#^/# ) {
281 my $namespace = $c->stack->[-1]->namespace;
282 $path = "$namespace/$path";
289 sub _invoke_as_path {
290 my ( $self, $c, $rel_path, $args ) = @_;
292 my $path = $self->_action_rel2abs( $c, $rel_path );
294 my ( $tail, @extra_args );
295 while ( ( $path, $tail ) = ( $path =~ m#^(?:(.*)/)?(\w+)?$# ) )
296 { # allow $path to be empty
297 if ( my $action = $c->get_action( $tail, $path ) ) {
298 push @$args, @extra_args;
304 ; # if a match on the global namespace failed then the whole lookup failed
307 unshift @extra_args, $tail;
311 sub _find_component {
312 my ( $self, $c, $component ) = @_;
314 # fugly, why doesn't ->component('MyApp') work?
315 return $c if ($component eq blessed($c));
317 return blessed($component)
319 : $c->component($component);
322 sub _invoke_as_component {
323 my ( $self, $c, $component_or_class, $method ) = @_;
325 my $component = $self->_find_component($c, $component_or_class);
326 my $component_class = blessed $component || return 0;
328 if (my $code = $component_class->can('action_for')) {
329 my $possible_action = $component->$code($method);
330 return $possible_action if $possible_action;
333 if ( my $code = $component_class->can($method) ) {
334 return $self->_method_action_class->new(
338 reverse => "$component_class->$method",
339 class => $component_class,
340 namespace => Catalyst::Utils::class2prefix(
341 $component_class, $c->config->{case_sensitive}
348 qq/Couldn't forward to "$component_class". Does not implement "$method"/;
350 $c->log->debug($error)
356 =head2 $self->prepare_action($c)
358 Find an dispatch type that matches $c->req->path, and set args from it.
363 my ( $self, $c ) = @_;
365 my $path = $req->path;
366 my @path = split /\//, $req->path;
367 $req->args( \my @args );
369 unshift( @path, '' ); # Root action
371 DESCEND: while (@path) {
372 $path = join '/', @path;
375 # Check out dispatch types to see if any will handle the path at
378 foreach my $type ( @{ $self->_dispatch_types } ) {
379 last DESCEND if $type->match( $c, $path );
382 # If not, move the last part path to args
383 my $arg = pop(@path);
384 $arg =~ s/%([0-9A-Fa-f]{2})/chr(hex($1))/eg;
388 s/%([0-9A-Fa-f]{2})/chr(hex($1))/eg for grep { defined } @{$req->captures||[]};
390 $c->log->debug( 'Path is "' . $req->match . '"' )
391 if ( $c->debug && defined $req->match && length $req->match );
393 $c->log->debug( 'Arguments are "' . join( '/', @args ) . '"' )
394 if ( $c->debug && @args );
397 =head2 $self->get_action( $action, $namespace )
399 returns a named action from a given namespace.
404 my ( $self, $name, $namespace ) = @_;
407 $namespace = join( "/", grep { length } split '/', ( defined $namespace ? $namespace : "" ) );
409 return $self->_action_hash->{"${namespace}/${name}"};
412 =head2 $self->get_action_by_path( $path );
414 Returns the named action by its full private path.
418 sub get_action_by_path {
419 my ( $self, $path ) = @_;
421 $path = "/$path" unless $path =~ /\//;
422 $self->_action_hash->{$path};
425 =head2 $self->get_actions( $c, $action, $namespace )
430 my ( $self, $c, $action, $namespace ) = @_;
431 return [] unless $action;
433 $namespace = join( "/", grep { length } split '/', $namespace || "" );
435 my @match = $self->get_containers($namespace);
437 return map { $_->get_action($action) } @match;
440 =head2 $self->get_containers( $namespace )
442 Return all the action containers for a given namespace, inclusive
447 my ( $self, $namespace ) = @_;
449 $namespace = '' if $namespace eq '/';
453 if ( length $namespace ) {
455 push @containers, $self->_container_hash->{$namespace};
456 } while ( $namespace =~ s#/[^/]+$## );
459 return reverse grep { defined } @containers, $self->_container_hash->{''};
462 =head2 $self->uri_for_action($action, \@captures)
464 Takes a Catalyst::Action object and action parameters and returns a URI
465 part such that if $c->req->path were this URI part, this action would be
466 dispatched to with $c->req->captures set to the supplied arrayref.
468 If the action object is not available for external dispatch or the dispatcher
469 cannot determine an appropriate URI, this method will return undef.
474 my ( $self, $action, $captures) = @_;
476 foreach my $dispatch_type ( @{ $self->_dispatch_types } ) {
477 my $uri = $dispatch_type->uri_for_action( $action, $captures );
478 return( $uri eq '' ? '/' : $uri )
486 expand an action into a full representation of the dispatch.
487 mostly useful for chained, other actions will just return a
493 my ($self, $action) = @_;
495 foreach my $dispatch_type (@{ $self->_dispatch_types }) {
496 my $expanded = $dispatch_type->expand_action($action);
497 return $expanded if $expanded;
503 =head2 $self->register( $c, $action )
505 Make sure all required dispatch types for this action are loaded, then
506 pass the action to our dispatch types so they can register it if required.
507 Also, set up the tree with the action containers.
512 my ( $self, $c, $action ) = @_;
514 my $registered = $self->_registered_dispatch_types;
516 #my $priv = 0; #seems to be unused
517 foreach my $key ( keys %{ $action->attributes } ) {
518 next if $key eq 'Private';
519 my $class = "Catalyst::DispatchType::$key";
520 unless ( $registered->{$class} ) {
521 # FIXME - Some error checking and re-throwing needed here, as
522 # we eat exceptions loading dispatch types.
523 eval { Class::MOP::load_class($class) };
524 push( @{ $self->_dispatch_types }, $class->new ) unless $@;
525 $registered->{$class} = 1;
529 my @dtypes = @{ $self->_dispatch_types };
531 my @low_precedence_dtypes;
533 for my $type ( @dtypes ) {
534 if ($type->_is_low_precedence) {
535 push @low_precedence_dtypes, $type;
537 push @normal_dtypes, $type;
541 # Pass the action to our dispatch types so they can register it if reqd.
542 my $was_registered = 0;
543 foreach my $type ( @normal_dtypes ) {
544 $was_registered = 1 if $type->register( $c, $action );
547 if (not $was_registered) {
548 foreach my $type ( @low_precedence_dtypes ) {
549 $type->register( $c, $action );
553 my $namespace = $action->namespace;
554 my $name = $action->name;
556 my $container = $self->_find_or_create_action_container($namespace);
558 # Set the method value
559 $container->add_action($action);
561 $self->_action_hash->{"$namespace/$name"} = $action;
562 $self->_container_hash->{$namespace} = $container;
565 sub _find_or_create_action_container {
566 my ( $self, $namespace ) = @_;
568 my $tree ||= $self->_tree;
570 return $tree->getNodeValue unless $namespace;
572 my @namespace = split '/', $namespace;
573 return $self->_find_or_create_namespace_node( $tree, @namespace )
577 sub _find_or_create_namespace_node {
578 my ( $self, $parent, $part, @namespace ) = @_;
580 return $parent unless $part;
583 ( grep { $_->getNodeValue->part eq $part } $parent->getAllChildren )[0];
586 my $container = Catalyst::ActionContainer->new($part);
587 $parent->addChild( $child = Tree::Simple->new($container) );
590 $self->_find_or_create_namespace_node( $child, @namespace );
593 =head2 $self->setup_actions( $class, $context )
595 Loads all of the preload dispatch types, registers their actions and then
596 loads all of the postload dispatch types, and iterates over the tree of
597 actions, displaying the debug information if appropriate.
602 my ( $self, $c ) = @_;
605 $self->_load_dispatch_types( @{ $self->preload_dispatch_types } );
606 @{ $self->_registered_dispatch_types }{@classes} = (1) x @classes;
608 foreach my $comp ( values %{ $c->components } ) {
609 $comp->register_actions($c) if $comp->can('register_actions');
612 $self->_load_dispatch_types( @{ $self->postload_dispatch_types } );
614 return unless $c->debug;
615 $self->_display_action_tables($c);
618 sub _display_action_tables {
621 my $column_width = Catalyst::Utils::term_width() - 20 - 36 - 12;
622 my $privates = Text::SimpleTable->new(
623 [ 20, 'Private' ], [ 36, 'Class' ], [ $column_width, 'Method' ]
628 my ( $walker, $parent, $prefix ) = @_;
629 $prefix .= $parent->getNodeValue || '';
630 $prefix .= '/' unless $prefix =~ /\/$/;
631 my $node = $parent->getNodeValue->actions;
633 for my $action ( keys %{$node} ) {
634 my $action_obj = $node->{$action};
636 if ( ( $action =~ /^_.*/ )
637 && ( !$c->config->{show_internal_actions} ) );
638 $privates->row( "$prefix$action", $action_obj->class, $action );
642 $walker->( $walker, $_, $prefix ) for $parent->getAllChildren;
645 $walker->( $walker, $self->_tree, '' );
646 $c->log->debug( "Loaded Private actions:\n" . $privates->draw . "\n" )
649 # List all public actions
650 $_->list($c) for @{ $self->_dispatch_types };
653 sub _load_dispatch_types {
654 my ( $self, @types ) = @_;
657 # Preload action types
658 for my $type (@types) {
659 # first param is undef because we cannot get the appclass
660 my $class = Catalyst::Utils::resolve_namespace(undef, 'Catalyst::DispatchType', $type);
662 eval { Class::MOP::load_class($class) };
663 Catalyst::Exception->throw( message => qq/Couldn't load "$class"/ )
665 push @{ $self->_dispatch_types }, $class->new;
667 push @loaded, $class;
673 =head2 $self->dispatch_type( $type )
675 Get the DispatchType object of the relevant type, i.e. passing C<$type> of
676 C<Chained> would return a L<Catalyst::DispatchType::Chained> object (assuming
677 of course it's being used.)
682 my ($self, $name) = @_;
684 # first param is undef because we cannot get the appclass
685 $name = Catalyst::Utils::resolve_namespace(undef, 'Catalyst::DispatchType', $name);
687 for (@{ $self->_dispatch_types }) {
688 return $_ if ref($_) eq $name;
695 # 5.70 backwards compatibility hacks.
697 # Various plugins (e.g. Plugin::Server and Plugin::Authorization::ACL)
698 # need the methods here which *should* be private..
700 # However we can't really take them away until there is a sane API for
701 # building actions and configuring / introspecting the dispatcher.
702 # In 5.90, we should build that infrastructure, port the plugins which
703 # use it, and then take the crap below away.
704 # See also t/lib/TestApp/Plugin/AddDispatchTypes.pm
706 # Alias _method_name to method_name, add a before modifier to warn..
707 foreach my $public_method_name (qw/
710 registered_dispatch_types
715 my $private_method_name = '_' . $public_method_name;
716 my $meta = __PACKAGE__->meta; # Calling meta method here fine as we happen at compile time.
717 $meta->add_method($public_method_name, $meta->get_method($private_method_name));
719 my %package_hash; # Only warn once per method, per package. These are infrequent enough that
720 # I haven't provided a way to disable them, patches welcome.
721 $meta->add_before_method_modifier($public_method_name, sub {
722 my $class = caller(2);
724 $package_hash{$class}++ || do {
725 warn("Class $class is calling the deprecated method\n"
726 . " Catalyst::Dispatcher::$public_method_name,\n"
727 . " this will be removed in Catalyst 5.9X\n");
732 # End 5.70 backwards compatibility hacks.
734 __PACKAGE__->meta->make_immutable;
742 Catalyst Contributors, see Catalyst.pm
746 This library is free software. You can redistribute it and/or modify it under
747 the same terms as Perl itself.