Dispatch requests to cgi::application based objects
Under mod_perl:
<Location /app> SetHandler perl-script PerlHandler CGI::Application::Dispatch </Location>
Under normal cgi:
This would be the instance script for your application, such as /cgi-bin/dispatch.cgi:
#!/usr/bin/perl use FindBin::Real 'Bin'; use lib Bin() . '/../../rel/path/to/my/perllib'; use CGI::Application::Dispatch; CGI::Application::Dispatch->dispatch();
package MyApp::Dispatch; use base 'CGI::Application::Dispatch';
sub dispatch_args { return { prefix => 'MyApp', table => [ '' => { app => 'Welcome', rm => 'start' }, ':app/:rm' => { }, 'admin/:app/:rm' => { prefix => 'MyApp::Admin' }, ], }; }
Under mod_perl:
<Location /app> SetHandler perl-script PerlHandler MyApp::Dispatch </Location>
Under normal cgi:
This would be the instance script for your application, such as /cgi-bin/dispatch.cgi:
#!/usr/bin/perl use FindBin::Real 'Bin'; use lib Bin() . '/../../rel/path/to/my/perllib'; use MyApp::Dispatch; MyApp::Dispatch->dispatch();
This module provides a way (as a mod_perl handler or running under vanilla \s-1CGI\s0) to look at the path (as returned by dispatch_path) of the incoming request, parse off the desired module and its run mode, create an instance of that module and run it.
It currently supports both generations of mod_perl (1.x and 2.x). Although, for simplicity, all examples involving Apache configuration and mod_perl code will be shown using mod_perl 1.x. This may change as mp2 usage increases.
It will translate a \s-1URI\s0 like this (under mod_perl):
/app/module_name/run_mode
or this (vanilla cgi)
/app/index.cgi/module_name/run_mode
into something that will be functionally similar to this
my $app = Module::Name->new(..); $app->mode_param(sub {'run_mode'}); #this will set the run mode
This is the primary method used during dispatch. Even under mod_perl, the handler method uses this under the hood.
#!/usr/bin/perl use strict; use CGI::Application::Dispatch;
CGI::Application::Dispatch->dispatch( prefix => 'MyApp', default => 'module_name', );
This method accepts the following name value pairs:
Specify a value to use for the path if one is not available. This could be the case if the default page is selected (eg: \*(L"/\*(R" ).
This option will set the string that will be prepended to the name of the application module before it is loaded and created. So to use our previous example request of /app/index.cgi/module_name/run_mode This would by default load and create a module named 'Module::Name'. But let's say that you have all of your application specific modules under the 'My' namespace. If you set this option to 'My' then it would instead load the 'My::Module::Name' application module instead.
This is a hash of arguments that are passed into the \*(C`new()\*(C' constructor of the application.
In most cases, simply using Dispatch with the \*(C`default\*(C' and \*(C`prefix\*(C' is enough to simplify your application and your URLs, but there are many cases where you want more power. Enter the dispatch table. Since this table can be slightly complicated, a whole section exists on its use. Please see the \*(L"\s-1DISPATCH\s0 \s-1TABLE\s0\*(R" section.
Set to a true value to send debugging output for this module to \s-1STDERR\s0. Off by default.
This string is similar to Apache ErrorDocument directive. If this value is not present, then Dispatch will return a \s-1NOT\s0 \s-1FOUND\s0 error either to the browser with simple hardcoded message (under \s-1CGI\s0) or to Apache (under mod_perl). This value can be one of the following: A string with error message - if it starts with a single double-quote character (\*(C`"\*(C'). This double-quote character will be trimmed from final output. A file with content of error document - if it starts with less-than sign (\*(C`<\*(C'). First character will be excluded as well. Path of this file should be relative to server \s-1DOCUMENT_ROOT\s0. A \s-1URI\s0 to which the application will be redirected - if no leading \*(C`"\*(C' or \*(C`<\*(C' will be found. Custom messages will be displayed in non mod_perl environment only. (Under mod_perl, please use ErrorDocument directive in Apache configuration files.) This value can contain %s placeholder for sprintf Perl function. This placeholder will be replaced with numeric \s-1HTTP\s0 error code. Currently CGI::Application::Dispatch uses three \s-1HTTP\s0 errors: 400 Bad Request - If there are invalid characters in module name (parameter :app) or runmode name (parameter :rm). 404 Not Found - When the path does not match anything in the \*(L"\s-1DISPATCH\s0 \s-1TABLE\s0\*(R", or module could not be found in @INC, or run mode did not exist. 500 Internal Server Error - If application error occurs. Examples of using error_document (assume error 404 have been returned): # return in browser 'Opss... HTTP Error #404' error_document => '"Opss... HTTP Error #%s'
# return contents of file $ENV{DOCUMENT_ROOT}/errors/error404.html error_document => '</errors/error%s.html'
# internal redirect to /errors/error404.html error_document => '/errors/error%s.html'
# external redirect to # http://host.domain/cgi-bin/errors.cgi?error=404 error_document => 'http://host.domain/cgi-bin/errors.cgi?error=%s'
This tells Dispatch that you are using \s-1REST\s0 by default and that you care about which \s-1HTTP\s0 method is being used. Dispatch will append the \s-1HTTP\s0 method name (upper case by default) to the run mode that is determined after finding the appropriate dispatch rule. So a \s-1GET\s0 request that translates into \*(C`MyApp::Module->foo\*(C' will become \*(C`MyApp::Module->foo_GET\*(C'. This can be overridden on a per-rule basis in a custom dispatch table.
In combinaion with auto_rest this tells Dispatch that you prefer lower cased \s-1HTTP\s0 method names. So instead of \*(C`foo_POST\*(C' and \*(C`foo_GET\*(C' you'll have \*(C`foo_post\*(C' and \*(C`foo_get\*(C'.
This method returns the path that is to be processed.
By default it returns the value of $ENV{PATH_INFO} (or \*(C`$r->path_info\*(C' under mod_perl) which should work for most cases. It allows the ability for subclasses to override the value if they need to do something more specific.
This method is used so that this module can be run as a mod_perl handler. When it creates the application module it passes the $r argument into the \s-1PARAMS\s0 hash of new()
<Location /app> SetHandler perl-script PerlHandler CGI::Application::Dispatch PerlSetVar CGIAPP_DISPATCH_PREFIX MyApp PerlSetVar CGIAPP_DISPATCH_DEFAULT /module_name </Location>
The above example would tell apache that any url beginning with /app will be handled by CGI::Application::Dispatch. It also sets the prefix used to create the application module to 'MyApp' and it tells CGI::Application::Dispatch that it shouldn't set the run mode but that it will be determined by the application module as usual (through the query string). It also sets a default application module to be used if there is no path. So, a url of \*(C`/app/module_name\*(C' would create an instance of \*(C`MyApp::Module::Name\*(C'.
Using this method will add the \*(C`Apache-\*(C'request> object to your application's \*(C`PARAMS\*(C' as 'r'.
# inside your app my $request = $self->param('r');
If you need more customization than can be accomplished with just prefix and default, then it would be best to just subclass CGI::Application::Dispatch and override dispatch_args since \*(C`handler()\*(C' uses dispatch to do the heavy lifting.
package MyApp::Dispatch; use base 'CGI::Application::Dispatch';
sub dispatch_args { return { prefix => 'MyApp', table => [ '' => { app => 'Welcome', rm => 'start' }, ':app/:rm' => { }, 'admin/:app/:rm' => { prefix => 'MyApp::Admin' }, ], args_to_new => { PARAMS => { foo => 'bar', baz => 'bam', }, } }; }
1;
And then in your httpd.conf
<Location /app> SetHandler perl-script PerlHandler MyApp::Dispatch </Location>
Returns a hashref of args that will be passed to dispatch(). It will return the following structure by default.
{ prefix => '', args_to_new => {}, table => [ ':app' => {}, ':app/:rm' => {}, ], }
This is the perfect place to override when creating a subclass to provide a richer dispatch table.
When called, it receives 1 argument, which is a reference to the hash of args passed into dispatch.
This method is used to control how the module name is translated from the matching section of the path (see \*(L"Path Parsing\*(R"). The main reason that this method exists is so that it can be overridden if it doesn't do exactly what you want.
The following transformations are performed on the input:
Here are some examples to make it even clearer:
module_name => Module::Name module-name => ModuleName admin_top-scores => Admin::TopScores
This class method is used internally by CGI::Application::Dispatch to take a module name (supplied by get_module_name) and require it in a secure fashion. It is provided as a public class method so that if you override other functionality of this module, you can still safely require user specified modules. If there are any problems requiring the named module, then we will \*(C`croak\*(C'.
CGI::Application::Dispatch->require_module('MyApp::Module::Name');
Sometimes it's easiest to explain with an example, so here you go:
CGI::Application::Dispatch->dispatch( prefix => 'MyApp', args_to_new => { TMPL_PATH => 'myapp/templates' }, table => [ '' => { app => 'Blog', rm => 'recent'}, 'posts/:category' => { app => 'Blog', rm => 'posts' }, ':app/:rm/:id' => { app => 'Blog' }, 'date/:year/:month?/:day?' => { app => 'Blog', rm => 'by_date', args_to_new => { TMPL_PATH => "events/" }, }, ] );
So first, this call to dispatch sets the prefix and passes a \*(C`TMPL_PATH\*(C' into args_to_new. Next it sets the table.
Just so we all understand what we're talking about....
A table is an array where the elements are gouped as pairs (similar to a hash's key-value pairs, but as an array to preserve order). The first element of each pair is called a \*(C`rule\*(C'. The second element in the pair is called the rule's \*(C`arg list\*(C'. Inside a rule there are slashes \*(C`/\*(C'. Anything set of characters between slashes is called a \*(C`token\*(C'.
When a \s-1URL\s0 comes in, Dispatch tries to match it against each rule in the table in the order in which the rules are given. The first one to match wins.
A rule consists of slashes and tokens. A token can one of the following types:
Any token which does not start with a colon (\*(C`:\*(C') is taken to be a literal string and must appear exactly as-is in the \s-1URL\s0 in order to match. In the rule 'posts/:category' \*(C`posts\*(C' is a literal token.
Any token which begins with a colon (\*(C`:\*(C') is a variable token. These are simply wild-card place holders in the rule that will match anything in the \s-1URL\s0 that isn't a slash. These variables can later be referred to by using the \*(C`$self->param\*(C' mechanism. In the rule 'posts/:category' \*(C`:category\*(C' is a variable token. If the \s-1URL\s0 matched this rule, then you could retrieve the value of that token from whithin your application like so: my $category = $self->param('category'); There are some variable tokens which are special. These can be used to further customize the dispatching.
This is the module name of the application. The value of this token will be sent to the translate_module_name method and then prefixed with the prefix if there is one.
This is the run mode of the application. The value of this token will be the actual name of the run mode used. The run mode can be optional, as noted below. Example: /foo/:rm? If no run mode is found, it will default to using the \*(C`start_mode()\*(C', just like invoking CGI::Application directly. Both of these URLs would end up dispatching to the start mode associated with /foo: /foo/ /foo
Any token which begins with a colon (\*(C`:\*(C') and ends with a question mark (<?>) is considered optional. If the rest of the \s-1URL\s0 matches the rest of the rule, then it doesn't matter whether it contains this token or not. It's best to only include optional-variable tokens at the end of your rule. In the rule 'date/:year/:month?/:day?' \*(C`:month?\*(C' and \*(C`:day?\*(C' are optional-variable tokens. Just like with variable tokens, optional-variable tokens' values can also be retrieved by the application, if they existed in the \s-1URL\s0. if( defined $self->param('month') ) { ... }
The wildcard token \*(L"*\*(R" allows for partial matches. The token \s-1MUST\s0 appear at the end of the rule. 'posts/list/*' By default, the \*(C`dispatch_url_remainder\*(C' param is set to the remainder of the \s-1URL\s0 matched by the *. The name of the param can be changed by setting \*(L"*\*(R" argument in the \*(L"\s-1ARG\s0 \s-1LIST\s0\*(R". 'posts/list/*' => { '*' => 'post_list_filter' }
You can also dispatch based on \s-1HTTP\s0 method. This is similar to using auto_rest but offers more fine grained control. You include the method (case insensitive) at the end of the rule and enclose it in square brackets. ':app/news[post]' => { rm => 'add_news' }, ':app/news[get]' => { rm => 'news' }, ':app/news[delete]' => { rm => 'delete_news' },
The main reason that we don't use regular expressions for dispatch rules is that regular expressions provide no mechanism for named back references, like variable tokens do.
Each rule can have an accompanying arg-list. This arg list can contain special arguments that override something set higher up in dispatch for this particular \s-1URL\s0, or just have additional args passed available in \*(C`$self->param()\*(C'
For instance, if you want to override prefix for a specific rule, then you can do so.
'admin/:app/:rm' => { prefix => 'MyApp::Admin' },
This section will describe how the application module and run mode are determined from the path if no \*(L"\s-1DISPATCH\s0 \s-1TABLE\s0\*(R" is present, and what options you have to customize the process. The value for the path to be parsed is retrieved from the dispatch_path method, which by default uses the \*(C`PATH_INFO\*(C' environment variable.
To get the name of the application module the path is split on backslahes (\*(C`/\*(C'). The second element of the returned list (the first is empty) is used to create the application module. So if we have a path of
/module_name/mode1
then the string 'module_name' is used. This is passed through the translate_module_name method. Then if there is a \*(C`prefix\*(C' (and there should always be a prefix) it is added to the beginning of this new module name with a double colon \*(C`::\*(C' separating the two.
If you don't like the exact way that this is done, don't fret you do have a couple of options. First, you can specify a \*(L"\s-1DISPATCH\s0 \s-1TABLE\s0\*(R" which is much more powerful and flexible (in fact this default behavior is actually implemented internally with a dispatch table). Or if you want something a little simpler, you can simply subclass and extend the translate_module_name method.
Just like the module name is retrieved from splitting the path on slashes, so is the run mode. Only instead of using the second element of the resulting list, we use the third as the run mode. So, using the same example, if we have a path of
/module_name/mode2
Then the string 'mode2' is used as the run mode.
\s-1CGI\s0 query strings \s-1CGI\s0 query strings are unaffected by the use of \*(C`PATH_INFO\*(C' to obtain the module name and run mode. This means that any other modules you use to get access to you query argument (ie, \s-1CGI\s0, Apache::Request) should not be affected. But, since the run mode may be determined by CGI::Application::Dispatch having a query argument named 'rm' will be ignored by your application module.
With a dispatch script, you can fairly clean \s-1URLS\s0 like this:
/cgi-bin/dispatch.cgi/module_name/run_mode
However, including \*(L"/cgi-bin/dispatch.cgi\*(R" in ever \s-1URL\s0 doesn't add any value to the \s-1URL\s0, so it's nice to remove it. This is easily done if you are using the Apache web server with \*(C`mod_rewrite\*(C' available. Adding the following to a \*(C`.htaccess\*(C' file would allow you to simply use:
/module_name/run_mode
If you have problems with mod_rewrite, turn on debugging to see exactly what's happening:
RewriteLog /home/project/logs/alpha-rewrite.log RewriteLogLevel 9
This seemed necessary to put in the dispatch script to make mod_rewrite happy. Perhaps it's specific to using \*(C`RewriteBase\*(C'.
# mod_rewrite alters the PATH_INFO by turning it into a file system path, # so we repair it. $ENV{PATH_INFO} =~ s/^$ENV{DOCUMENT_ROOT}// if defined $ENV{PATH_INFO};
RewriteEngine On
# You may want to change the base if you are using the dispatcher within a # specific directory. RewriteBase /
# If an actual file or directory is requested, serve directly RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d
# Otherwise, pass everything through to the dispatcher RewriteRule ^(.*)$ /cgi-bin/dispatch.cgi/$1 [L,QSA] Here is a more complex example that dispatches \*(L"/\*(R", which would otherwise be treated as a directory, and also supports multiple developer directories, so \*(C`/~mark\*(C' has its own separate dispatching system beneath it.
Note that order matters here! The Location block for \*(L"/\*(R" needs to come before the user blocks.
<Location /> RewriteEngine On RewriteBase /
# Run "/" through the dispatcher RewriteRule ^home/project/www/$ /cgi-bin/dispatch.cgi [L,QSA]
# Don't apply this rule to the users sub directories. RewriteCond %{REQUEST_URI} !^/~.*$ # If an actual file or directory is requested, serve directly RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d # Otherwise, pass everything through to the dispatcher RewriteRule ^(.*)$ /cgi-bin/dispatch.cgi/$1 [L,QSA] </Location>
<Location /~mark> RewriteEngine On RewriteBase /~mark
# Run "/" through the dispatcher RewriteRule ^/home/mark/www/$ /~mark/cgi-bin/dispatch.cgi [L,QSA]
# Otherwise, if an actual file or directory is requested, # serve directly RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d
# Otherwise, pass everything through to the dispatcher RewriteRule ^(.*)$ /~mark/cgi-bin/dispatch.cgi/$1 [L,QSA]
# These examples may also be helpful, but are unrelated to dispatching. SetEnv DEVMODE mark SetEnv PERL5LIB /home/mark/perllib:/home/mark/config ErrorDocument 404 /~mark/errdocs/404.html ErrorDocument 500 /~mark/errdocs/500.html </Location>
While Dispatch tries to be flexible, it won't be able to do everything that people want. Hopefully we've made it flexible enough so that if it doesn't do The Right Thing you can easily subclass it.
Michael Peters <[email protected]>
Thanks to Plus Three, \s-1LP\s0 (http://www.plusthree.com) for sponsoring my work on this module
This module is a part of the larger CGI::Application community. If you have questions or comments about this module then please join us on the cgiapp mailing list by sending a blank message to \*(L"[email protected]\*(R". There is also a community wiki located at http://www.cgi-app.org/ <http://www.cgi-app.org/>
A public source code repository for this project is hosted here:
http://code.google.com/p/cgi-app-modules/source/checkout
Shawn Sorichetti
Timothy Appnel
dsteinbrunner
\s-1ZACKSE\s0
Stew Heckenberg
Drew Taylor <[email protected]>
James Freeman <[email protected]>
Michael Graham <[email protected]>
Cees Hek <[email protected]>
Mark Stosberg <[email protected]>
Viacheslav Sheveliov <[email protected]>
Since C::A::Dispatch will dynamically choose which modules to use as the content generators, it may give someone the ability to execute random modules on your system if those modules can be found in you path. Of course those modules would have to behave like CGI::Application based modules, but that still opens up the door more than most want. This should only be a problem if you don't use a prefix. By using this option you are only allowing Dispatch to pick from a namespace of modules to run.
CGI::Application, Apache::Dispatch
Copyright Michael Peters and Mark Stosberg 2008, all rights reserved.
This library is free software; you can redistribute it and/or modify it under the same terms as Perl itself.