|
NAMECGI::Application::Dispatch - Dispatch requests to CGI::Application based objectsSYNOPSISOut of BoxUnder 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(); With a dispatch tablepackage 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(); DESCRIPTIONThis module provides a way (as a mod_perl handler or running under vanilla CGI) 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 URI 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 METHODSdispatch(%args)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:
dispatch_path()This method returns the path that is to be processed.By default it returns the value of $ENV{PATH_INFO} (or "$r->path_info" 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. handler()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 PARAMS 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 "/app/module_name" would create an instance of "MyApp::Module::Name". Using this method will add the "Apache-"request> object to your application's "PARAMS" 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 "handler()" 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> dispatch_args()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. translate_module_name($input)This method is used to control how the module name is translated from the matching section of the path (see "Path Parsing"). 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 require_module($module_name)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 "croak".CGI::Application::Dispatch->require_module('MyApp::Module::Name'); DISPATCH TABLESometimes 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 "TMPL_PATH" into args_to_new. Next it sets the table. VOCABULARYJust 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 "rule". The second element in the pair is called the rule's "arg list". Inside a rule there are slashes "/". Anything set of characters between slashes is called a "token". URL MATCHINGWhen a URL 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:
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. ARG LISTEach 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 URL, or just have additional args passed available in "$self->param()"For instance, if you want to override prefix for a specific rule, then you can do so. 'admin/:app/:rm' => { prefix => 'MyApp::Admin' }, Path ParsingThis section will describe how the application module and run mode are determined from the path if no "DISPATCH TABLE" 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 "PATH_INFO" environment variable.Getting the module nameTo get the name of the application module the path is split on backslahes ("/"). 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 "prefix" (and there should always be a prefix) it is added to the beginning of this new module name with a double colon "::" 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 "DISPATCH TABLE" 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. Getting the run modeJust 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. MISC NOTES
CLEAN URLS WITH MOD_REWRITEWith a dispatch script, you can fairly clean URLS like this:/cgi-bin/dispatch.cgi/module_name/run_mode However, including "/cgi-bin/dispatch.cgi" in ever URL doesn't add any value to the URL, so it's nice to remove it. This is easily done if you are using the Apache web server with "mod_rewrite" available. Adding the following to a ".htaccess" 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 mod_rewrite related code in the dispatch script.This seemed necessary to put in the dispatch script to make mod_rewrite happy. Perhaps it's specific to using "RewriteBase".# 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}; Simple Apache ExampleRewriteEngine 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] More complex rewrite: dispatching "/" and multiple developersHere is a more complex example that dispatches "/", which would otherwise be treated as a directory, and also supports multiple developer directories, so "/~mark" has its own separate dispatching system beneath it.Note that order matters here! The Location block for "/" 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> SUBCLASSINGWhile 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.AUTHORMichael Peters <mpeters@plusthree.com>Thanks to Plus Three, LP (http://www.plusthree.com) for sponsoring my work on this module COMMUNITYThis 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 "cgiapp-subscribe@lists.erlbaum.net". There is also a community wiki located at <http://www.cgi-app.org/>SOURCE CODE REPOSITORYA public source code repository for this project is hosted here:http://code.google.com/p/cgi-app-modules/source/checkout CONTRIBUTORS
SECURITYSince 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.SEE ALSOCGI::Application, Apache::DispatchCOPYRIGHT & LICENSECopyright 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.
Visit the GSP FreeBSD Man Page Interface. |