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 ) = @_;
58 $c->forward( join('/', '', $c->namespace, '_DISPATCH') );
62 my $path = $c->req->path;
64 ? qq/Unknown resource "$path"/
65 : "No default action defined";
66 $c->log->error($error) if $c->debug;
71 =item $self->forward( $c, $command [, \@arguments ] )
81 $c->log->debug('Nothing to forward to') if $c->debug;
85 # Relative forwards from detach
86 my $caller = ( caller(1) )[0]->isa('Catalyst::Dispatcher')
87 && ( ( caller(2) )[3] =~ /::detach$/ ) ? caller(3) : caller(1);
89 my $arguments = ( ref( $_[-1] ) eq 'ARRAY' ) ? pop(@_) : $c->req->args;
93 my $command_copy = $command;
95 unless ( $command_copy =~ s/^\/// ) {
97 Catalyst::Utils::class2prefix( $caller, $c->config->{case_sensitive} )
99 $command_copy = "${namespace}/${command}";
102 unless ( $command_copy =~ /\// ) {
103 $results = $c->get_action( $command_copy, '/' );
107 DESCEND: while ( $command_copy =~ s/^(.*)\/(\w+)$/$1/ ) {
109 $results = $c->get_action( $tail, $1 );
112 push( @{$arguments}, @extra_args );
115 unshift( @extra_args, $tail );
119 unless ( @{$results} ) {
121 unless ( $c->components->{$command} ) {
123 qq/Couldn't forward to command "$command". Invalid action or component./;
125 $c->log->debug($error) if $c->debug;
129 my $class = $command;
130 my $method = shift || 'process';
132 if ( my $code = $c->components->{$class}->can($method) ) {
133 my $action = Catalyst::Action->new(
137 reverse => "$class->$method",
142 $results = [ [$action] ];
147 qq/Couldn't forward to "$class". Does not implement "$method"/;
149 $c->log->debug($error)
156 local $c->request->{arguments} = [ @{$arguments} ];
158 for my $result ( @{$results} ) {
159 $result->[0]->execute($c);
160 return if scalar @{ $c->error };
161 last unless $c->state;
167 =item $self->prepare_action($c)
172 my ( $self, $c ) = @_;
173 my $path = $c->req->path;
174 my @path = split /\//, $c->req->path;
175 $c->req->args( \my @args );
177 push( @path, '/' ) unless @path; # Root action
179 DESCEND: while (@path) {
180 $path = join '/', @path;
182 $path = '' if $path eq '/'; # Root action
184 # Check out dispatch types to see if any will handle the path at
187 foreach my $type ( @{ $self->dispatch_types } ) {
188 last DESCEND if $type->match( $c, $path );
191 # If not, move the last part path to args
193 unshift @args, pop @path;
196 $c->log->debug( 'Arguments are "' . join( '/', @args ) . '"' )
197 if ( $c->debug && @args );
200 =item $self->get_action( $c, $action, $namespace, $inherit )
205 my ( $self, $c, $action, $namespace, $inherit ) = @_;
206 return [] unless $action;
208 $namespace = '' if $namespace eq '/';
211 my @match = $self->get_containers($namespace);
213 if ($inherit) { # Return [ [ $act_obj ], ... ] for valid containers
215 map { [ $_->{$action} ] } # Make [ $action_obj ]
216 grep { defined $_->{$action} } # If it exists in the container
217 map { $_->actions } # Get action hash for container
222 my $node = $match[-1]->actions; # Only bother looking at the last one
224 if ( defined $node->{$action}
225 && ( $node->{$action}->namespace eq $namespace ) )
227 return [ [ $node->{$action} ] ];
235 =item $self->get_containers( $namespace )
240 my ( $self, $namespace ) = @_;
242 # If the namespace is / just return the root ActionContainer
244 return ( $self->tree->getNodeValue )
245 if ( !$namespace || ( $namespace eq '/' ) );
247 # Use a visitor to recurse down the tree finding the ActionContainers
248 # for each namespace in the chain.
250 my $visitor = Tree::Simple::Visitor::FindByPath->new;
251 my @path = split( '/', $namespace );
252 $visitor->setSearchPath(@path);
253 $self->tree->accept($visitor);
255 my @match = $visitor->getResults;
256 @match = ( $self->tree ) unless @match;
258 if ( !defined $visitor->getResult ) {
260 # If we don't manage to match, the visitor doesn't return the last
261 # node is matched, so foo/bar/baz would only find the 'foo' node,
262 # not the foo and foo/bar nodes as it should. This does another
263 # single-level search to see if that's the case, and the 'last unless'
264 # should catch any failures - or short-circuit this if this *is* a
265 # bug in the visitor and gets fixed.
267 my $extra = $path[ ( scalar @match ) - 1 ];
269 $visitor->setSearchPath($extra);
270 $match[-1]->accept($visitor);
271 push( @match, $visitor->getResult ) if defined $visitor->getResult;
274 return map { $_->getNodeValue } @match;
277 =item $self->set_action( $c, $action, $code, $class, $attrs )
282 my ( $self, $c, $method, $code, $class, $attrs ) = @_;
285 Catalyst::Utils::class2prefix( $class, $c->config->{case_sensitive} )
289 for my $attr ( @{$attrs} ) {
291 # Parse out :Foo(bar) into Foo => bar etc (and arrayify)
294 $initialized{ ref $_ }++ for @{ $self->dispatch_types };
296 if ( my ( $key, $value ) = ( $attr =~ /^(.*?)(?:\(\s*(.+)\s*\))?$/ ) ) {
299 my $class = "Catalyst::DispatchType::$key";
300 unless ( $initialized{$class} ) {
301 eval "require $class";
302 push( @{ $self->dispatch_types }, $class->new ) unless $@;
303 $initialized{$class}++;
306 if ( defined $value ) {
307 ( $value =~ s/^'(.*)'$/$1/ ) || ( $value =~ s/^"(.*)"/$1/ );
309 push( @{ $attributes{$key} }, $value );
313 if ( $attributes{Private} && ( keys %attributes > 1 ) ) {
314 $c->log->debug( 'Bad action definition "'
315 . join( ' ', @{$attrs} )
316 . qq/" for "$class->$method"/ )
320 return unless keys %attributes;
322 my $parent = $self->tree;
323 my $visitor = Tree::Simple::Visitor::FindByPath->new;
326 for my $part ( split '/', $namespace ) {
327 $visitor->setSearchPath($part);
328 $parent->accept($visitor);
329 my $child = $visitor->getResult;
333 # Create a new tree node and an ActionContainer to form
337 Catalyst::ActionContainer->new(
338 { part => $part, actions => {} } );
339 $child = $parent->addChild( Tree::Simple->new($container) );
340 $visitor->setSearchPath($part);
341 $parent->accept($visitor);
342 $child = $visitor->getResult;
349 my $reverse = $namespace ? "$namespace/$method" : $method;
351 my $action = Catalyst::Action->new(
356 namespace => $namespace,
358 attributes => \%attributes,
362 # Set the method value
363 $parent->getNodeValue->actions->{$method} = $action;
365 # Pass the action to our dispatch types so they can register it if reqd.
366 foreach my $type ( @{ $self->dispatch_types } ) {
367 $type->register( $c, $action );
371 =item $self->setup_actions( $class, $component )
376 my ( $self, $c ) = @_;
378 $self->dispatch_types( [] );
380 # Preload action types
381 for my $type (@PRELOAD) {
382 my $class = "Catalyst::DispatchType::$type";
383 eval "require $class";
384 Catalyst::Exception->throw( message => qq/Couldn't load "$class"/ )
386 push @{ $self->dispatch_types }, $class->new;
391 Catalyst::ActionContainer->new( { part => '/', actions => {} } );
392 $self->tree( Tree::Simple->new( $container, Tree::Simple->ROOT ) );
394 for my $comp ( keys %{ $c->components } ) {
396 # We only setup components that inherit from Catalyst::Base
397 next unless $comp->isa('Catalyst::Base');
399 for my $action ( @{ Catalyst::Utils::reflect_actions($comp) } ) {
400 my ( $code, $attrs ) = @{$action};
403 my @cache = ( $comp, @{"$comp\::ISA"} );
406 while ( my $class = shift @cache ) {
408 for my $isa ( @{"$class\::ISA"} ) {
409 next if $classes{$isa};
415 for my $class ( keys %classes ) {
416 for my $sym ( values %{ $class . '::' } ) {
417 if ( *{$sym}{CODE} && *{$sym}{CODE} == $code ) {
418 $name = *{$sym}{NAME};
419 $self->set_action( $c, $name, $code, $comp, $attrs );
427 # Postload action types
428 for my $type (@POSTLOAD) {
429 my $class = "Catalyst::DispatchType::$type";
430 eval "require $class";
431 Catalyst::Exception->throw( message => qq/Couldn't load "$class"/ )
433 push @{ $self->dispatch_types }, $class->new;
436 return unless $c->debug;
438 my $privates = Text::ASCIITable->new;
439 $privates->setCols( 'Private', 'Class' );
440 $privates->setColWidth( 'Private', 36, 1 );
441 $privates->setColWidth( 'Class', 37, 1 );
444 my ( $walker, $parent, $prefix ) = @_;
445 $prefix .= $parent->getNodeValue || '';
446 $prefix .= '/' unless $prefix =~ /\/$/;
447 my $node = $parent->getNodeValue->actions;
449 for my $action ( keys %{$node} ) {
450 my $action_obj = $node->{$action};
451 $privates->addRow( "$prefix$action", $action_obj->class );
454 $walker->( $walker, $_, $prefix ) for $parent->getAllChildren;
457 $walker->( $walker, $self->tree, '' );
458 $c->log->debug( "Loaded Private actions:\n" . $privates->draw )
459 if ( @{ $privates->{tbl_rows} } );
461 # List all public actions
462 $_->list($c) for @{ $self->dispatch_types };
469 Sebastian Riedel, C<sri@cpan.org>
473 This program is free software, you can redistribute it and/or modify it under
474 the same terms as Perl itself.