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, $name, $namespace ) = @_;
204 $namespace = '' if $namespace eq '/';
206 my @match = $self->get_containers($namespace);
208 return unless @match;
210 if ( my $action = $match[-1]->get_action( $c, $name ) )
212 return $action if $action->namespace eq $namespace;
216 =item $self->get_actions( $c, $action, $namespace )
221 my ( $self, $c, $action, $namespace ) = @_;
222 return [] unless $action;
224 $namespace = '' if $namespace eq '/';
226 my @match = $self->get_containers($namespace);
228 return map { $_->get_action($c, $action) } @match;
231 =item $self->get_containers( $namespace )
236 my ( $self, $namespace ) = @_;
238 # If the namespace is / just return the root ActionContainer
240 return ( $self->tree->getNodeValue )
241 if ( !$namespace || ( $namespace eq '/' ) );
243 # Use a visitor to recurse down the tree finding the ActionContainers
244 # for each namespace in the chain.
246 my $visitor = Tree::Simple::Visitor::FindByPath->new;
247 my @path = split( '/', $namespace );
248 $visitor->setSearchPath(@path);
249 $self->tree->accept($visitor);
251 my @match = $visitor->getResults;
252 @match = ( $self->tree ) unless @match;
254 if ( !defined $visitor->getResult ) {
256 # If we don't manage to match, the visitor doesn't return the last
257 # node is matched, so foo/bar/baz would only find the 'foo' node,
258 # not the foo and foo/bar nodes as it should. This does another
259 # single-level search to see if that's the case, and the 'last unless'
260 # should catch any failures - or short-circuit this if this *is* a
261 # bug in the visitor and gets fixed.
263 my $extra = $path[ ( scalar @match ) - 1 ];
265 $visitor->setSearchPath($extra);
266 $match[-1]->accept($visitor);
267 push( @match, $visitor->getResult ) if defined $visitor->getResult;
270 return map { $_->getNodeValue } @match;
273 =item $self->set_action( $c, $action, $code, $class, $attrs )
278 my ( $self, $c, $method, $code, $class, $attrs ) = @_;
281 Catalyst::Utils::class2prefix( $class, $c->config->{case_sensitive} )
285 for my $attr ( @{$attrs} ) {
287 # Parse out :Foo(bar) into Foo => bar etc (and arrayify)
290 $initialized{ ref $_ }++ for @{ $self->dispatch_types };
292 if ( my ( $key, $value ) = ( $attr =~ /^(.*?)(?:\(\s*(.+)\s*\))?$/ ) ) {
295 my $class = "Catalyst::DispatchType::$key";
296 unless ( $initialized{$class} ) {
297 eval "require $class";
298 push( @{ $self->dispatch_types }, $class->new ) unless $@;
299 $initialized{$class}++;
302 if ( defined $value ) {
303 ( $value =~ s/^'(.*)'$/$1/ ) || ( $value =~ s/^"(.*)"/$1/ );
305 push( @{ $attributes{$key} }, $value );
309 if ( $attributes{Private} && ( keys %attributes > 1 ) ) {
310 $c->log->debug( 'Bad action definition "'
311 . join( ' ', @{$attrs} )
312 . qq/" for "$class->$method"/ )
316 return unless keys %attributes;
318 my $reverse = $namespace ? "$namespace/$method" : $method;
320 my $action = Catalyst::Action->new(
325 namespace => $namespace,
327 attributes => \%attributes,
331 $self->register($c, $action);
335 my ( $self, $c, $action ) = @_;
337 my $namespace = $action->namespace;
338 my $parent = $self->tree;
339 my $visitor = Tree::Simple::Visitor::FindByPath->new;
342 for my $part ( split '/', $namespace ) {
343 $visitor->setSearchPath($part);
344 $parent->accept($visitor);
345 my $child = $visitor->getResult;
349 # Create a new tree node and an ActionContainer to form
353 Catalyst::ActionContainer->new(
354 { part => $part, actions => {} } );
355 $child = $parent->addChild( Tree::Simple->new($container) );
356 $visitor->setSearchPath($part);
357 $parent->accept($visitor);
358 $child = $visitor->getResult;
365 # Set the method value
366 $parent->getNodeValue->actions->{$action->name} = $action;
368 # Pass the action to our dispatch types so they can register it if reqd.
369 foreach my $type ( @{ $self->dispatch_types } ) {
370 $type->register( $c, $action );
374 =item $self->setup_actions( $class, $component )
379 my ( $self, $c ) = @_;
381 $self->dispatch_types( [] );
383 # Preload action types
384 for my $type (@PRELOAD) {
385 my $class = "Catalyst::DispatchType::$type";
386 eval "require $class";
387 Catalyst::Exception->throw( message => qq/Couldn't load "$class"/ )
389 push @{ $self->dispatch_types }, $class->new;
394 Catalyst::ActionContainer->new( { part => '/', actions => {} } );
395 $self->tree( Tree::Simple->new( $container, Tree::Simple->ROOT ) );
397 for my $comp ( keys %{ $c->components } ) {
399 # We only setup components that inherit from Catalyst::Base
400 next unless $comp->isa('Catalyst::Base');
402 for my $action ( @{ Catalyst::Utils::reflect_actions($comp) } ) {
403 my ( $code, $attrs ) = @{$action};
406 my @cache = ( $comp, @{"$comp\::ISA"} );
409 while ( my $class = shift @cache ) {
411 for my $isa ( @{"$class\::ISA"} ) {
412 next if $classes{$isa};
418 for my $class ( keys %classes ) {
419 for my $sym ( values %{ $class . '::' } ) {
420 if ( *{$sym}{CODE} && *{$sym}{CODE} == $code ) {
421 $name = *{$sym}{NAME};
422 $self->set_action( $c, $name, $code, $comp, $attrs );
430 # Postload action types
431 for my $type (@POSTLOAD) {
432 my $class = "Catalyst::DispatchType::$type";
433 eval "require $class";
434 Catalyst::Exception->throw( message => qq/Couldn't load "$class"/ )
436 push @{ $self->dispatch_types }, $class->new;
439 return unless $c->debug;
441 my $privates = Text::ASCIITable->new;
442 $privates->setCols( 'Private', 'Class' );
443 $privates->setColWidth( 'Private', 36, 1 );
444 $privates->setColWidth( 'Class', 37, 1 );
447 my ( $walker, $parent, $prefix ) = @_;
448 $prefix .= $parent->getNodeValue || '';
449 $prefix .= '/' unless $prefix =~ /\/$/;
450 my $node = $parent->getNodeValue->actions;
452 for my $action ( keys %{$node} ) {
453 my $action_obj = $node->{$action};
455 if ( ( $action =~ /^_.*/ )
456 && ( !$c->config->{show_internal_actions} ) );
457 $privates->addRow( "$prefix$action", $action_obj->class );
460 $walker->( $walker, $_, $prefix ) for $parent->getAllChildren;
463 $walker->( $walker, $self->tree, '' );
464 $c->log->debug( "Loaded Private actions:\n" . $privates->draw )
465 if ( @{ $privates->{tbl_rows} } );
467 # List all public actions
468 $_->list($c) for @{ $self->dispatch_types };
475 Sebastian Riedel, C<sri@cpan.org>
479 This program is free software, you can redistribute it and/or modify it under
480 the same terms as Perl itself.