1 package Catalyst::Dispatcher;
4 use base 'Class::Accessor::Fast';
5 use Catalyst::Exception;
8 use Catalyst::ActionContainer;
9 use Catalyst::DispatchType::Default;
10 use Catalyst::DispatchType::Index;
13 use Tree::Simple::Visitor::FindByPath;
16 use overload '""' => sub { return ref shift }, fallback => 1;
18 __PACKAGE__->mk_accessors(qw/tree dispatch_types/);
20 # Preload these action types
21 our @PRELOAD = qw/Path Regex/;
23 # Postload these action types
24 our @POSTLOAD = qw/Index Default/;
28 Catalyst::Dispatcher - The Catalyst Dispatcher
40 =item $self->detach( $c, $command [, \@arguments ] )
45 my ( $self, $c, $command, @args ) = @_;
46 $c->forward( $command, @args ) if $command;
47 die $Catalyst::DETACH;
50 =item $self->dispatch($c)
55 my ( $self, $c ) = @_;
59 my @containers = $self->get_containers( $c->namespace );
61 foreach my $name (qw/begin auto end/) {
63 # Go down the container list representing each part of the
64 # current namespace inheritance tree, grabbing the actions hash
65 # of the ActionContainer object and looking for actions of the
66 # appropriate name registered to the namespace
70 grep { exists $_->{$name} }
71 map { $_->actions } @containers
75 # Errors break the normal flow and the end action is instantly run
80 if ( my $begin = @{ $actions{begin} }[-1] ) {
82 $error++ if scalar @{ $c->error };
85 # Execute the auto chain
87 for my $auto ( @{ $actions{auto} } ) {
91 $error++ if scalar @{ $c->error };
92 last unless $c->state;
95 # Execute the action or last default
96 my $mkay = $autorun ? $c->state ? 1 : 0 : 1;
99 $c->action->execute($c);
100 $error++ if scalar @{ $c->error };
105 if ( my $end = @{ $actions{end} }[-1] ) {
111 my $path = $c->req->path;
113 ? qq/Unknown resource "$path"/
114 : "No default action defined";
115 $c->log->error($error) if $c->debug;
120 =item $self->forward( $c, $command [, \@arguments ] )
130 $c->log->debug('Nothing to forward to') if $c->debug;
134 # Relative forwards from detach
135 my $caller = ( caller(1) )[0]->isa('Catalyst::Dispatcher')
136 && ( ( caller(2) )[3] =~ /::detach$/ ) ? caller(3) : caller(1);
138 my $arguments = ( ref( $_[-1] ) eq 'ARRAY' ) ? pop(@_) : $c->req->args;
142 my $command_copy = $command;
144 unless ( $command_copy =~ s/^\/// ) {
146 Catalyst::Utils::class2prefix( $caller, $c->config->{case_sensitive} )
148 $command_copy = "${namespace}/${command}";
151 unless ( $command_copy =~ /\// ) {
152 $results = $c->get_action( $command_copy, '/' );
156 DESCEND: while ( $command_copy =~ s/^(.*)\/(\w+)$/$1/ ) {
158 $results = $c->get_action( $tail, $1 );
161 push( @{$arguments}, @extra_args );
164 unshift( @extra_args, $tail );
168 unless ( @{$results} ) {
170 unless ( $c->components->{$command} ) {
172 qq/Couldn't forward to command "$command". Invalid action or component./;
174 $c->log->debug($error) if $c->debug;
178 my $class = $command;
179 my $method = shift || 'process';
181 if ( my $code = $c->components->{$class}->can($method) ) {
182 my $action = Catalyst::Action->new(
186 reverse => "$class->$method",
191 $results = [ [$action] ];
196 qq/Couldn't forward to "$class". Does not implement "$method"/;
198 $c->log->debug($error)
205 local $c->request->{arguments} = [ @{$arguments} ];
207 for my $result ( @{$results} ) {
208 $result->[0]->execute($c);
209 return if scalar @{ $c->error };
210 last unless $c->state;
216 =item $self->prepare_action($c)
221 my ( $self, $c ) = @_;
222 my $path = $c->req->path;
223 my @path = split /\//, $c->req->path;
224 $c->req->args( \my @args );
226 push( @path, '/' ) unless @path; # Root action
228 DESCEND: while (@path) {
229 $path = join '/', @path;
231 $path = '' if $path eq '/'; # Root action
233 # Check out dispatch types to see if any will handle the path at
236 foreach my $type ( @{ $self->dispatch_types } ) {
237 last DESCEND if $type->match( $c, $path );
240 # If not, move the last part path to args
242 unshift @args, pop @path;
245 $c->log->debug( 'Arguments are "' . join( '/', @args ) . '"' )
246 if ( $c->debug && @args );
249 =item $self->get_action( $c, $action, $namespace, $inherit )
254 my ( $self, $c, $action, $namespace, $inherit ) = @_;
255 return [] unless $action;
257 $namespace = '' if $namespace eq '/';
260 my @match = $self->get_containers($namespace);
262 if ($inherit) { # Return [ [ $act_obj ], ... ] for valid containers
264 map { [ $_->{$action} ] } # Make [ $action_obj ]
265 grep { defined $_->{$action} } # If it exists in the container
266 map { $_->actions } # Get action hash for container
271 my $node = $match[-1]->actions; # Only bother looking at the last one
273 if ( defined $node->{$action}
274 && ( $node->{$action}->prefix eq $namespace ) )
276 return [ [ $node->{$action} ] ];
284 =item $self->get_containers( $namespace )
289 my ( $self, $namespace ) = @_;
291 # If the namespace is / just return the root ActionContainer
293 return ( $self->tree->getNodeValue )
294 if ( !$namespace || ( $namespace eq '/' ) );
296 # Use a visitor to recurse down the tree finding the ActionContainers
297 # for each namespace in the chain.
299 my $visitor = Tree::Simple::Visitor::FindByPath->new;
300 my @path = split( '/', $namespace );
301 $visitor->setSearchPath(@path);
302 $self->tree->accept($visitor);
304 my @match = $visitor->getResults;
305 @match = ( $self->tree ) unless @match;
307 if ( !defined $visitor->getResult ) {
309 # If we don't manage to match, the visitor doesn't return the last
310 # node is matched, so foo/bar/baz would only find the 'foo' node,
311 # not the foo and foo/bar nodes as it should. This does another
312 # single-level search to see if that's the case, and the 'last unless'
313 # should catch any failures - or short-circuit this if this *is* a
314 # bug in the visitor and gets fixed.
316 my $extra = $path[ ( scalar @match ) - 1 ];
318 $visitor->setSearchPath($extra);
319 $match[-1]->accept($visitor);
320 push( @match, $visitor->getResult ) if defined $visitor->getResult;
323 return map { $_->getNodeValue } @match;
326 =item $self->set_action( $c, $action, $code, $namespace, $attrs )
331 my ( $self, $c, $method, $code, $namespace, $attrs ) = @_;
334 Catalyst::Utils::class2prefix( $namespace, $c->config->{case_sensitive} )
338 for my $attr ( @{$attrs} ) {
340 # Parse out :Foo(bar) into Foo => bar etc (and arrayify)
343 $initialized{ ref $_ }++ for @{ $self->dispatch_types };
345 if ( my ( $key, $value ) = ( $attr =~ /^(.*?)(?:\(\s*(.+)\s*\))?$/ ) ) {
348 my $class = "Catalyst::DispatchType::$key";
349 unless ( $initialized{$class} ) {
350 eval "require $class";
351 push( @{ $self->dispatch_types }, $class->new ) unless $@;
352 $initialized{$class}++;
355 if ( defined $value ) {
356 ( $value =~ s/^'(.*)'$/$1/ ) || ( $value =~ s/^"(.*)"/$1/ );
358 push( @{ $attributes{$key} }, $value );
362 if ( $attributes{Private} && ( keys %attributes > 1 ) ) {
363 $c->log->debug( 'Bad action definition "'
364 . join( ' ', @{$attrs} )
365 . qq/" for "$namespace->$method"/ )
369 return unless keys %attributes;
371 my $parent = $self->tree;
372 my $visitor = Tree::Simple::Visitor::FindByPath->new;
375 for my $part ( split '/', $prefix ) {
376 $visitor->setSearchPath($part);
377 $parent->accept($visitor);
378 my $child = $visitor->getResult;
382 # Create a new tree node and an ActionContainer to form
386 Catalyst::ActionContainer->new(
387 { part => $part, actions => {} } );
388 $child = $parent->addChild( Tree::Simple->new($container) );
389 $visitor->setSearchPath($part);
390 $parent->accept($visitor);
391 $child = $visitor->getResult;
398 my $reverse = $prefix ? "$prefix/$method" : $method;
400 my $action = Catalyst::Action->new(
405 namespace => $namespace,
407 attributes => \%attributes,
411 # Set the method value
412 $parent->getNodeValue->actions->{$method} = $action;
414 # Pass the action to our dispatch types so they can register it if reqd.
415 foreach my $type ( @{ $self->dispatch_types } ) {
416 $type->register( $c, $action );
420 =item $self->setup_actions( $class, $component )
425 my ( $self, $class ) = @_;
427 $self->dispatch_types( [] );
429 # Preload action types
430 for my $type (@PRELOAD) {
431 my $class = "Catalyst::DispatchType::$type";
432 eval "require $class";
433 Catalyst::Exception->throw( message => qq/Couldn't load "$class"/ )
435 push @{ $self->dispatch_types }, $class->new;
440 Catalyst::ActionContainer->new( { part => '/', actions => {} } );
441 $self->tree( Tree::Simple->new( $container, Tree::Simple->ROOT ) );
443 for my $comp ( keys %{ $class->components } ) {
445 # We only setup components that inherit from Catalyst::Base
446 next unless $comp->isa('Catalyst::Base');
448 for my $action ( @{ Catalyst::Utils::reflect_actions($comp) } ) {
449 my ( $code, $attrs ) = @{$action};
452 my @cache = ( $comp, @{"$comp\::ISA"} );
455 while ( my $namespace = shift @cache ) {
456 $namespaces{$namespace}++;
457 for my $isa ( @{"$comp\::ISA"} ) {
458 next if $namespaces{$isa};
464 for my $namespace ( keys %namespaces ) {
465 for my $sym ( values %{ $namespace . '::' } ) {
466 if ( *{$sym}{CODE} && *{$sym}{CODE} == $code ) {
467 $name = *{$sym}{NAME};
468 $class->set_action( $name, $code, $comp, $attrs );
476 # Postload action types
477 for my $type (@POSTLOAD) {
478 my $class = "Catalyst::DispatchType::$type";
479 eval "require $class";
480 Catalyst::Exception->throw( message => qq/Couldn't load "$class"/ )
482 push @{ $self->dispatch_types }, $class->new;
485 return unless $class->debug;
487 my $privates = Text::ASCIITable->new;
488 $privates->setCols( 'Private', 'Class' );
489 $privates->setColWidth( 'Private', 36, 1 );
490 $privates->setColWidth( 'Class', 37, 1 );
493 my ( $walker, $parent, $prefix ) = @_;
494 $prefix .= $parent->getNodeValue || '';
495 $prefix .= '/' unless $prefix =~ /\/$/;
496 my $node = $parent->getNodeValue->actions;
498 for my $action ( keys %{$node} ) {
499 my $action_obj = $node->{$action};
500 $privates->addRow( "$prefix$action", $action_obj->namespace );
503 $walker->( $walker, $_, $prefix ) for $parent->getAllChildren;
506 $walker->( $walker, $self->tree, '' );
507 $class->log->debug( "Loaded Private actions:\n" . $privates->draw )
508 if ( @{ $privates->{tbl_rows} } );
510 # List all public actions
511 $_->list($class) for @{ $self->dispatch_types };
518 Sebastian Riedel, C<sri@cpan.org>
522 This program is free software, you can redistribute it and/or modify it under
523 the same terms as Perl itself.