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 $result = $c->get_action( $command_copy, '/' );
107 DESCEND: while ( $command_copy =~ s/^(.*)\/(\w+)$/$1/ ) {
109 $result = $c->get_action( $tail, $1 );
112 push( @{$arguments}, @extra_args );
115 unshift( @extra_args, $tail );
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",
147 qq/Couldn't forward to "$class". Does not implement "$method"/;
149 $c->log->debug($error)
156 local $c->request->{arguments} = [ @{$arguments} ];
158 $result->execute($c);
163 =item $self->prepare_action($c)
168 my ( $self, $c ) = @_;
169 my $path = $c->req->path;
170 my @path = split /\//, $c->req->path;
171 $c->req->args( \my @args );
173 push( @path, '/' ) unless @path; # Root action
175 DESCEND: while (@path) {
176 $path = join '/', @path;
178 $path = '' if $path eq '/'; # Root action
180 # Check out dispatch types to see if any will handle the path at
183 foreach my $type ( @{ $self->dispatch_types } ) {
184 last DESCEND if $type->match( $c, $path );
187 # If not, move the last part path to args
189 unshift @args, pop @path;
192 $c->log->debug( 'Arguments are "' . join( '/', @args ) . '"' )
193 if ( $c->debug && @args );
196 =item $self->get_action( $c, $action, $namespace )
201 my ( $self, $c, $action, $namespace ) = @_;
202 return [] unless $action;
204 $namespace = '' if $namespace eq '/';
206 my @match = $self->get_containers($namespace);
208 my $node = $match[-1]->actions; # Only bother looking at the last one
210 if ( defined $node->{$action}
211 && ( $node->{$action}->namespace eq $namespace ) )
213 return $node->{$action};
217 =item $self->get_actions( $c, $action, $namespace )
222 my ( $self, $c, $action, $namespace ) = @_;
223 return [] unless $action;
225 $namespace = '' if $namespace eq '/';
227 my @match = $self->get_containers($namespace);
230 map { $_->{$action} }
231 grep { defined $_->{$action} } # If it exists in the container
232 map { $_->actions } # Get action hash for container
236 =item $self->get_containers( $namespace )
241 my ( $self, $namespace ) = @_;
243 # If the namespace is / just return the root ActionContainer
245 return ( $self->tree->getNodeValue )
246 if ( !$namespace || ( $namespace eq '/' ) );
248 # Use a visitor to recurse down the tree finding the ActionContainers
249 # for each namespace in the chain.
251 my $visitor = Tree::Simple::Visitor::FindByPath->new;
252 my @path = split( '/', $namespace );
253 $visitor->setSearchPath(@path);
254 $self->tree->accept($visitor);
256 my @match = $visitor->getResults;
257 @match = ( $self->tree ) unless @match;
259 if ( !defined $visitor->getResult ) {
261 # If we don't manage to match, the visitor doesn't return the last
262 # node is matched, so foo/bar/baz would only find the 'foo' node,
263 # not the foo and foo/bar nodes as it should. This does another
264 # single-level search to see if that's the case, and the 'last unless'
265 # should catch any failures - or short-circuit this if this *is* a
266 # bug in the visitor and gets fixed.
268 my $extra = $path[ ( scalar @match ) - 1 ];
270 $visitor->setSearchPath($extra);
271 $match[-1]->accept($visitor);
272 push( @match, $visitor->getResult ) if defined $visitor->getResult;
275 return map { $_->getNodeValue } @match;
278 =item $self->set_action( $c, $action, $code, $class, $attrs )
283 my ( $self, $c, $method, $code, $class, $attrs ) = @_;
286 Catalyst::Utils::class2prefix( $class, $c->config->{case_sensitive} )
290 for my $attr ( @{$attrs} ) {
292 # Parse out :Foo(bar) into Foo => bar etc (and arrayify)
295 $initialized{ ref $_ }++ for @{ $self->dispatch_types };
297 if ( my ( $key, $value ) = ( $attr =~ /^(.*?)(?:\(\s*(.+)\s*\))?$/ ) ) {
300 my $class = "Catalyst::DispatchType::$key";
301 unless ( $initialized{$class} ) {
302 eval "require $class";
303 push( @{ $self->dispatch_types }, $class->new ) unless $@;
304 $initialized{$class}++;
307 if ( defined $value ) {
308 ( $value =~ s/^'(.*)'$/$1/ ) || ( $value =~ s/^"(.*)"/$1/ );
310 push( @{ $attributes{$key} }, $value );
314 if ( $attributes{Private} && ( keys %attributes > 1 ) ) {
315 $c->log->debug( 'Bad action definition "'
316 . join( ' ', @{$attrs} )
317 . qq/" for "$class->$method"/ )
321 return unless keys %attributes;
323 my $parent = $self->tree;
324 my $visitor = Tree::Simple::Visitor::FindByPath->new;
327 for my $part ( split '/', $namespace ) {
328 $visitor->setSearchPath($part);
329 $parent->accept($visitor);
330 my $child = $visitor->getResult;
334 # Create a new tree node and an ActionContainer to form
338 Catalyst::ActionContainer->new(
339 { part => $part, actions => {} } );
340 $child = $parent->addChild( Tree::Simple->new($container) );
341 $visitor->setSearchPath($part);
342 $parent->accept($visitor);
343 $child = $visitor->getResult;
350 my $reverse = $namespace ? "$namespace/$method" : $method;
352 my $action = Catalyst::Action->new(
357 namespace => $namespace,
359 attributes => \%attributes,
363 # Set the method value
364 $parent->getNodeValue->actions->{$method} = $action;
366 # Pass the action to our dispatch types so they can register it if reqd.
367 foreach my $type ( @{ $self->dispatch_types } ) {
368 $type->register( $c, $action );
372 =item $self->setup_actions( $class, $component )
377 my ( $self, $c ) = @_;
379 $self->dispatch_types( [] );
381 # Preload action types
382 for my $type (@PRELOAD) {
383 my $class = "Catalyst::DispatchType::$type";
384 eval "require $class";
385 Catalyst::Exception->throw( message => qq/Couldn't load "$class"/ )
387 push @{ $self->dispatch_types }, $class->new;
392 Catalyst::ActionContainer->new( { part => '/', actions => {} } );
393 $self->tree( Tree::Simple->new( $container, Tree::Simple->ROOT ) );
395 for my $comp ( keys %{ $c->components } ) {
397 # We only setup components that inherit from Catalyst::Base
398 next unless $comp->isa('Catalyst::Base');
400 for my $action ( @{ Catalyst::Utils::reflect_actions($comp) } ) {
401 my ( $code, $attrs ) = @{$action};
404 my @cache = ( $comp, @{"$comp\::ISA"} );
407 while ( my $class = shift @cache ) {
409 for my $isa ( @{"$class\::ISA"} ) {
410 next if $classes{$isa};
416 for my $class ( keys %classes ) {
417 for my $sym ( values %{ $class . '::' } ) {
418 if ( *{$sym}{CODE} && *{$sym}{CODE} == $code ) {
419 $name = *{$sym}{NAME};
420 $self->set_action( $c, $name, $code, $comp, $attrs );
428 # Postload action types
429 for my $type (@POSTLOAD) {
430 my $class = "Catalyst::DispatchType::$type";
431 eval "require $class";
432 Catalyst::Exception->throw( message => qq/Couldn't load "$class"/ )
434 push @{ $self->dispatch_types }, $class->new;
437 return unless $c->debug;
439 my $privates = Text::ASCIITable->new;
440 $privates->setCols( 'Private', 'Class' );
441 $privates->setColWidth( 'Private', 36, 1 );
442 $privates->setColWidth( 'Class', 37, 1 );
445 my ( $walker, $parent, $prefix ) = @_;
446 $prefix .= $parent->getNodeValue || '';
447 $prefix .= '/' unless $prefix =~ /\/$/;
448 my $node = $parent->getNodeValue->actions;
450 for my $action ( keys %{$node} ) {
451 my $action_obj = $node->{$action};
453 if ( ( $action =~ /^_.*/ )
454 && ( !$c->config->{show_internal_actions} ) );
455 $privates->addRow( "$prefix$action", $action_obj->class );
458 $walker->( $walker, $_, $prefix ) for $parent->getAllChildren;
461 $walker->( $walker, $self->tree, '' );
462 $c->log->debug( "Loaded Private actions:\n" . $privates->draw )
463 if ( @{ $privates->{tbl_rows} } );
465 # List all public actions
466 $_->list($c) for @{ $self->dispatch_types };
473 Sebastian Riedel, C<sri@cpan.org>
477 This program is free software, you can redistribute it and/or modify it under
478 the same terms as Perl itself.