[Catalyst] RFC $c->uri_to

Michael Reece mreece at vinq.com
Wed Jan 3 19:45:33 GMT 2007


$c->uri_for() is great and all, but i usually am more interested in  
getting a uri for an action rather than a uri to a template (or  
public path).

(incidentally, i feel uri_for would be better named uri_to, and the  
sub below named uri_for, but i digress.)

the following code is what i have come up with.  i present it here  
for feedback, comments, etc.

## my $uri = $c->uri_to( $controller_path, @path_args );
## my $uri = $c->uri_to( $controller_path, @path_args, \%query_args );
## my $uri = $c->uri_to( $controller_path, @path_args,  
\@snippets );    # for :Regex() actions
#   $controller_path is '/controller/method' (preferred) or  
'method' (in current $c->controller)
sub uri_to {
     my $c         = shift;
     my $namespace = shift;
     my @args      = @_;

     my @path_args;
     my $snippets;
     my $query;
     foreach (@args) {
         if (ref eq 'ARRAY') {
             $snippets = $_;
         } elsif (ref eq 'HASH') {
             $query = $_;
         } else {
             push @path_args, $_;
         }
     }

     my $path = $namespace;
     unless ($path =~ m{^/}) {
         my $ns = $c->namespace;    # get current namespace
         if ($ns eq '') {
             $path = "/$path";      # Root controller has namespace=''
         } else {
             $path = "/$ns/$path";
         }
     }

     my $action = $c->dispatcher->get_action_by_path($path);
     unless ($action) {
         $c->log->error("uri_to cannot get_action_by_path($path)");
         return undef;
     }

     my @action_args = (defined $snippets) ? @$snippets : ();
     my $uri = $c->dispatcher->uri_for_action($action, @action_args);
     unless ($uri) {
         $c->log->error("uri_to cannot find uri_for_action $action");
         return undef;
     }

     my @uri_args = (defined $query) ? ($query) : ();
     $uri = $c->uri_for("$uri", @path_args, @uri_args);    #  
"stringify" important here
     return $uri;
}

there is a good chance i am re-inventing a wheel here!




More information about the Catalyst mailing list