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;
13 use Text::SimpleTable;
15 use Tree::Simple::Visitor::FindByPath;
18 #do these belong as package vars or should we build these via a builder method?
19 # Preload these action types
20 our @PRELOAD = qw/Index Path Regex/;
22 # Postload these action types
23 our @POSTLOAD = qw/Default/;
25 has _tree => (is => 'rw');
26 has _dispatch_types => (is => 'rw', default => sub { [] }, required => 1, lazy => 1);
27 has _registered_dispatch_types => (is => 'rw', default => sub { {} }, required => 1, lazy => 1);
28 has _method_action_class => (is => 'rw', default => 'Catalyst::Action');
29 has _action_container_class => (is => 'rw', default => 'Catalyst::ActionContainer');
31 has preload_dispatch_types => (is => 'rw', required => 1, lazy => 1, default => sub { [@PRELOAD] });
32 has postload_dispatch_types => (is => 'rw', required => 1, lazy => 1, default => sub { [@POSTLOAD] });
33 has _action_hash => (is => 'rw', required => 1, lazy => 1, default => sub { {} });
34 has _container_hash => (is => 'rw', required => 1, lazy => 1, default => sub { {} });
40 Catalyst::Dispatcher - The Catalyst Dispatcher
48 This is the class that maps public urls to actions in your Catalyst
49 application based on the attributes you set.
55 Construct a new dispatcher.
60 my ($self, $params) = @_;
63 Catalyst::ActionContainer->new( { part => '/', actions => {} } );
65 $self->_tree( Tree::Simple->new( $container, Tree::Simple->ROOT ) );
68 =head2 $self->preload_dispatch_types
70 An arrayref of pre-loaded dispatchtype classes
72 Entries are considered to be available as C<Catalyst::DispatchType::CLASS>
73 To use a custom class outside the regular C<Catalyst> namespace, prefix
74 it with a C<+>, like so:
78 =head2 $self->postload_dispatch_types
80 An arrayref of post-loaded dispatchtype classes
82 Entries are considered to be available as C<Catalyst::DispatchType::CLASS>
83 To use a custom class outside the regular C<Catalyst> namespace, prefix
84 it with a C<+>, like so:
88 =head2 $self->dispatch($c)
90 Delegate the dispatch to the action that matched the url, or return a
91 message about unknown resource
97 my ( $self, $c ) = @_;
98 if ( my $action = $c->action ) {
99 $c->forward( join( '/', '', $action->namespace, '_DISPATCH' ) );
103 my $path = $c->req->path;
105 ? qq/Unknown resource "$path"/
106 : "No default action defined";
107 $c->log->error($error) if $c->debug;
112 # $self->_command2action( $c, $command [, \@arguments ] )
113 # Search for an action, from the command and returns C<($action, $args)> on
114 # success. Returns C<(0)> on error.
116 sub _command2action {
117 my ( $self, $c, $command, @extra_params ) = @_;
120 $c->log->debug('Nothing to go to') if $c->debug;
126 if ( ref( $extra_params[-1] ) eq 'ARRAY' ) {
127 @args = @{ pop @extra_params }
129 # this is a copy, it may take some abuse from
130 # ->_invoke_as_path if the path had trailing parts
131 @args = @{ $c->request->arguments };
136 # go to a string path ("/foo/bar/gorch")
138 if (Scalar::Util::blessed($command) && $command->isa('Catalyst::Action')) {
142 $action = $self->_invoke_as_path( $c, "$command", \@args );
145 # go to a component ( "MyApp::*::Foo" or $c->component("...")
146 # - a path or an object)
148 my $method = @extra_params ? $extra_params[0] : "process";
149 $action = $self->_invoke_as_component( $c, $command, $method );
152 return $action, \@args;
155 =head2 $self->visit( $c, $command [, \@arguments ] )
157 Documented in L<Catalyst>
163 $self->_do_visit('visit', @_);
169 my ( $c, $command ) = @_;
170 my ( $action, $args ) = $self->_command2action(@_);
171 my $error = qq/Couldn't $opname("$command"): /;
174 $error .= qq/Couldn't $opname to command "$command": /
175 .qq/Invalid action or component./;
177 elsif (!defined $action->namespace) {
178 $error .= qq/Action has no namespace: cannot $opname() to a plain /
179 .qq/method or component, must be a :Action or some sort./
181 elsif (!$action->class->can('_DISPATCH')) {
182 $error .= qq/Action cannot _DISPATCH. /
183 .qq/Did you try to $opname() a non-controller action?/;
191 $c->log->debug($error) if $c->debug;
195 $action = $self->expand_action($action);
197 local $c->request->{arguments} = $args;
198 local $c->{namespace} = $action->{'namespace'};
199 local $c->{action} = $action;
204 =head2 $self->go( $c, $command [, \@arguments ] )
206 Documented in L<Catalyst>
212 $self->_do_visit('go', @_);
216 =head2 $self->forward( $c, $command [, \@arguments ] )
218 Documented in L<Catalyst>
224 $self->_do_forward(forward => @_);
230 my ( $c, $command ) = @_;
231 my ( $action, $args ) = $self->_command2action(@_);
234 my $error .= qq/Couldn't $opname to command "$command": /
235 .qq/Invalid action or component./;
237 $c->log->debug($error) if $c->debug;
241 no warnings 'recursion';
243 my $orig_args = $c->request->arguments();
244 $c->request->arguments($args);
245 $action->dispatch( $c );
246 $c->request->arguments($orig_args);
251 =head2 $self->detach( $c, $command [, \@arguments ] )
253 Documented in L<Catalyst>
258 my ( $self, $c, $command, @args ) = @_;
259 $self->_do_forward(detach => $c, $command, @args ) if $command;
260 die $Catalyst::DETACH;
263 sub _action_rel2abs {
264 my ( $self, $c, $path ) = @_;
266 unless ( $path =~ m#^/# ) {
267 my $namespace = $c->stack->[-1]->namespace;
268 $path = "$namespace/$path";
275 sub _invoke_as_path {
276 my ( $self, $c, $rel_path, $args ) = @_;
278 my $path = $self->_action_rel2abs( $c, $rel_path );
280 my ( $tail, @extra_args );
281 while ( ( $path, $tail ) = ( $path =~ m#^(?:(.*)/)?(\w+)?$# ) )
282 { # allow $path to be empty
283 if ( my $action = $c->get_action( $tail, $path ) ) {
284 push @$args, @extra_args;
290 ; # if a match on the global namespace failed then the whole lookup failed
293 unshift @extra_args, $tail;
297 sub _find_component_class {
298 my ( $self, $c, $component ) = @_;
300 return ref($component)
301 || ref( $c->component($component) )
302 || $c->component($component);
305 sub _invoke_as_component {
306 my ( $self, $c, $component, $method ) = @_;
308 my $class = $self->_find_component_class( $c, $component ) || return 0;
310 if ( my $code = $class->can($method) ) {
311 return $self->_method_action_class->new(
315 reverse => "$class->$method",
317 namespace => Catalyst::Utils::class2prefix(
318 $class, $c->config->{case_sensitive}
325 qq/Couldn't forward to "$class". Does not implement "$method"/;
327 $c->log->debug($error)
333 =head2 $self->prepare_action($c)
335 Find an dispatch type that matches $c->req->path, and set args from it.
340 my ( $self, $c ) = @_;
342 my $path = $req->path;
343 my @path = split /\//, $req->path;
344 $req->args( \my @args );
346 unshift( @path, '' ); # Root action
348 DESCEND: while (@path) {
349 $path = join '/', @path;
352 $path = '' if $path eq '/'; # Root action
354 # Check out dispatch types to see if any will handle the path at
357 foreach my $type ( @{ $self->_dispatch_types } ) {
358 last DESCEND if $type->match( $c, $path );
361 # If not, move the last part path to args
362 my $arg = pop(@path);
363 $arg =~ s/%([0-9A-Fa-f]{2})/chr(hex($1))/eg;
367 s/%([0-9A-Fa-f]{2})/chr(hex($1))/eg for grep { defined } @{$req->captures||[]};
369 $c->log->debug( 'Path is "' . $req->match . '"' )
370 if ( $c->debug && defined $req->match && length $req->match );
372 $c->log->debug( 'Arguments are "' . join( '/', @args ) . '"' )
373 if ( $c->debug && @args );
376 =head2 $self->get_action( $action, $namespace )
378 returns a named action from a given namespace.
383 my ( $self, $name, $namespace ) = @_;
386 $namespace = join( "/", grep { length } split '/', ( defined $namespace ? $namespace : "" ) );
388 return $self->_action_hash->{"${namespace}/${name}"};
391 =head2 $self->get_action_by_path( $path );
393 Returns the named action by its full path.
397 sub get_action_by_path {
398 my ( $self, $path ) = @_;
400 $path = "/$path" unless $path =~ /\//;
401 $self->_action_hash->{$path};
404 =head2 $self->get_actions( $c, $action, $namespace )
409 my ( $self, $c, $action, $namespace ) = @_;
410 return [] unless $action;
412 $namespace = join( "/", grep { length } split '/', $namespace || "" );
414 my @match = $self->get_containers($namespace);
416 return map { $_->get_action($action) } @match;
419 =head2 $self->get_containers( $namespace )
421 Return all the action containers for a given namespace, inclusive
426 my ( $self, $namespace ) = @_;
428 $namespace = '' if $namespace eq '/';
432 if ( length $namespace ) {
434 push @containers, $self->_container_hash->{$namespace};
435 } while ( $namespace =~ s#/[^/]+$## );
438 return reverse grep { defined } @containers, $self->_container_hash->{''};
440 #return (split '/', $namespace); # isnt this more clear?
441 my @parts = split '/', $namespace;
444 =head2 $self->uri_for_action($action, \@captures)
446 Takes a Catalyst::Action object and action parameters and returns a URI
447 part such that if $c->req->path were this URI part, this action would be
448 dispatched to with $c->req->captures set to the supplied arrayref.
450 If the action object is not available for external dispatch or the dispatcher
451 cannot determine an appropriate URI, this method will return undef.
456 my ( $self, $action, $captures) = @_;
458 foreach my $dispatch_type ( @{ $self->_dispatch_types } ) {
459 my $uri = $dispatch_type->uri_for_action( $action, $captures );
460 return( $uri eq '' ? '/' : $uri )
468 expand an action into a full representation of the dispatch.
469 mostly useful for chained, other actions will just return a
475 my ($self, $action) = @_;
477 foreach my $dispatch_type (@{ $self->_dispatch_types }) {
478 my $expanded = $dispatch_type->expand_action($action);
479 return $expanded if $expanded;
485 =head2 $self->register( $c, $action )
487 Make sure all required dispatch types for this action are loaded, then
488 pass the action to our dispatch types so they can register it if required.
489 Also, set up the tree with the action containers.
494 my ( $self, $c, $action ) = @_;
496 my $registered = $self->_registered_dispatch_types;
498 #my $priv = 0; #seems to be unused
499 foreach my $key ( keys %{ $action->attributes } ) {
500 next if $key eq 'Private';
501 my $class = "Catalyst::DispatchType::$key";
502 unless ( $registered->{$class} ) {
503 #some error checking rethrowing here wouldn't hurt.
504 eval { Class::MOP::load_class($class) };
505 push( @{ $self->_dispatch_types }, $class->new ) unless $@;
506 $registered->{$class} = 1;
510 # Pass the action to our dispatch types so they can register it if reqd.
511 foreach my $type ( @{ $self->_dispatch_types } ) {
512 $type->register( $c, $action );
515 my $namespace = $action->namespace;
516 my $name = $action->name;
518 my $container = $self->_find_or_create_action_container($namespace);
520 # Set the method value
521 $container->add_action($action);
523 $self->_action_hash->{"$namespace/$name"} = $action;
524 $self->_container_hash->{$namespace} = $container;
527 sub _find_or_create_action_container {
528 my ( $self, $namespace ) = @_;
530 my $tree ||= $self->_tree;
532 return $tree->getNodeValue unless $namespace;
534 my @namespace = split '/', $namespace;
535 return $self->_find_or_create_namespace_node( $tree, @namespace )
539 sub _find_or_create_namespace_node {
540 my ( $self, $parent, $part, @namespace ) = @_;
542 return $parent unless $part;
545 ( grep { $_->getNodeValue->part eq $part } $parent->getAllChildren )[0];
548 my $container = Catalyst::ActionContainer->new($part);
549 $parent->addChild( $child = Tree::Simple->new($container) );
552 $self->_find_or_create_namespace_node( $child, @namespace );
555 =head2 $self->setup_actions( $class, $context )
561 my ( $self, $c ) = @_;
565 $self->_load_dispatch_types( @{ $self->preload_dispatch_types } );
566 @{ $self->_registered_dispatch_types }{@classes} = (1) x @classes;
568 foreach my $comp ( values %{ $c->components } ) {
569 $comp->register_actions($c) if $comp->can('register_actions');
572 $self->_load_dispatch_types( @{ $self->postload_dispatch_types } );
574 return unless $c->debug;
576 my $privates = Text::SimpleTable->new(
584 my ( $walker, $parent, $prefix ) = @_;
585 $prefix .= $parent->getNodeValue || '';
586 $prefix .= '/' unless $prefix =~ /\/$/;
587 my $node = $parent->getNodeValue->actions;
589 for my $action ( keys %{$node} ) {
590 my $action_obj = $node->{$action};
592 if ( ( $action =~ /^_.*/ )
593 && ( !$c->config->{show_internal_actions} ) );
594 $privates->row( "$prefix$action", $action_obj->class, $action );
598 $walker->( $walker, $_, $prefix ) for $parent->getAllChildren;
601 $walker->( $walker, $self->_tree, '' );
602 $c->log->debug( "Loaded Private actions:\n" . $privates->draw . "\n" )
605 # List all public actions
606 $_->list($c) for @{ $self->_dispatch_types };
609 sub _load_dispatch_types {
610 my ( $self, @types ) = @_;
614 # Preload action types
615 for my $type (@types) {
617 ( $type =~ /^\+(.*)$/ ) ? $1 : "Catalyst::DispatchType::${type}";
619 eval { Class::MOP::load_class($class) };
620 Catalyst::Exception->throw( message => qq/Couldn't load "$class"/ )
622 push @{ $self->_dispatch_types }, $class->new;
624 push @loaded, $class;
631 __PACKAGE__->meta->make_immutable;
639 Catalyst Contributors, see Catalyst.pm
643 This program is free software, you can redistribute it and/or modify it under
644 the same terms as Perl itself.