1CGI::Application::DispaUtscehr(3C)ontributed Perl DocumeCnGtIa:t:iAopnplication::Dispatch(3)
2
3
4

NAME

6       CGI::Application::Dispatch - Dispatch requests to CGI::Application
7       based objects
8

SYNOPSIS

10   Out of Box
11       Under mod_perl:
12
13           <Location /app>
14               SetHandler perl-script
15               PerlHandler CGI::Application::Dispatch
16           </Location>
17
18       Under normal cgi:
19
20       This would be the instance script for your application, such as
21       /cgi-bin/dispatch.cgi:
22
23           #!/usr/bin/perl
24           use FindBin::Real 'Bin';
25           use lib Bin() . '/../../rel/path/to/my/perllib';
26           use CGI::Application::Dispatch;
27           CGI::Application::Dispatch->dispatch();
28
29   With a dispatch table
30           package MyApp::Dispatch;
31           use base 'CGI::Application::Dispatch';
32
33           sub dispatch_args {
34               return {
35                   prefix  => 'MyApp',
36                   table   => [
37                       ''                => { app => 'Welcome', rm => 'start' },
38                       ':app/:rm'        => { },
39                       'admin/:app/:rm'  => { prefix   => 'MyApp::Admin' },
40                   ],
41               };
42           }
43
44       Under mod_perl:
45
46           <Location /app>
47               SetHandler perl-script
48               PerlHandler MyApp::Dispatch
49           </Location>
50
51       Under normal cgi:
52
53       This would be the instance script for your application, such as
54       /cgi-bin/dispatch.cgi:
55
56           #!/usr/bin/perl
57           use FindBin::Real 'Bin';
58           use lib Bin() . '/../../rel/path/to/my/perllib';
59           use MyApp::Dispatch;
60           MyApp::Dispatch->dispatch();
61

DESCRIPTION

63       This module provides a way (as a mod_perl handler or running under
64       vanilla CGI) to look at the path (as returned by dispatch_path) of the
65       incoming request, parse off the desired module and its run mode, create
66       an instance of that module and run it.
67
68       It currently supports both generations of mod_perl (1.x and 2.x).
69       Although, for simplicity, all examples involving Apache configuration
70       and mod_perl code will be shown using mod_perl 1.x.  This may change as
71       mp2 usage increases.
72
73       It will translate a URI like this (under mod_perl):
74
75           /app/module_name/run_mode
76
77       or this (vanilla cgi)
78
79           /app/index.cgi/module_name/run_mode
80
81       into something that will be functionally similar to this
82
83           my $app = Module::Name->new(..);
84           $app->mode_param(sub {'run_mode'}); #this will set the run mode
85

METHODS

87   dispatch(%args)
88       This is the primary method used during dispatch. Even under mod_perl,
89       the handler method uses this under the hood.
90
91           #!/usr/bin/perl
92           use strict;
93           use CGI::Application::Dispatch;
94
95           CGI::Application::Dispatch->dispatch(
96               prefix  => 'MyApp',
97               default => 'module_name',
98           );
99
100       This method accepts the following name value pairs:
101
102       default
103           Specify a value to use for the path if one is not available.  This
104           could be the case if the default page is selected (eg: "/" ).
105
106       prefix
107           This option will set the string that will be prepended to the name
108           of the application module before it is loaded and created. So to
109           use our previous example request of
110
111               /app/index.cgi/module_name/run_mode
112
113           This would by default load and create a module named
114           'Module::Name'. But let's say that you have all of your application
115           specific modules under the 'My' namespace. If you set this option
116           to 'My' then it would instead load the 'My::Module::Name'
117           application module instead.
118
119       args_to_new
120           This is a hash of arguments that are passed into the "new()"
121           constructor of the application.
122
123       table
124           In most cases, simply using Dispatch with the "default" and
125           "prefix" is enough to simplify your application and your URLs, but
126           there are many cases where you want more power. Enter the dispatch
127           table. Since this table can be slightly complicated, a whole
128           section exists on its use. Please see the "DISPATCH TABLE" section.
129
130       debug
131           Set to a true value to send debugging output for this module to
132           STDERR. Off by default.
133
134       error_document
135           This string is similar to Apache ErrorDocument directive. If this
136           value is not present, then Dispatch will return a NOT FOUND error
137           either to the browser with simple hardcoded message (under CGI) or
138           to Apache (under mod_perl).
139
140           This value can be one of the following:
141
142           A string with error message - if it starts with a single double-
143           quote character ("""). This double-quote character will be trimmed
144           from final output.
145
146           A file with content of error document - if it starts with greater-
147           than sign ("<"). First character will be excluded as well. Path of
148           this file should be relative to server DOCUMENT_ROOT.
149
150           A URI to which the application will be redirected - if no leading
151           """ or "<" will be found.
152
153           Custom messages will be displayed in non mod_perl enviroment only.
154           (Under mod_perl, please use ErrorDocument directive in Apache
155           configuration files.)  This value can contain %s placeholder for
156           sprintf Perl function. This placeholder will be replaced with
157           numeric HTTP error code. Currently CGI::Application::Dispatch uses
158           three HTTP errors:
159
160           400 Bad Request - If there are invalid characters in module name
161           (parameter :app) or runmode name (parameter :rm).
162
163           404 Not Found - When the path does not match anything in the
164           "DISPATCH TABLE", or module could not be found in @INC, or run mode
165           did not exist.
166
167           500 Internal Server Error - If application error occurs.
168
169           Examples of using error_document (assume error 404 have been
170           returned):
171
172               # return in browser 'Opss... HTTP Error #404'
173               error_document => '"Opss... HTTP Error #%s'
174
175               # return contents of file $ENV{DOCUMENT_ROOT}/errors/error404.html
176               error_document => '</errors/error%s.html'
177
178               # internal redirect to /errors/error404.html
179               error_document => '/errors/error%s.html'
180
181               # external redirect to http://host.domain/cgi-bin/errors.cgi?error=404
182               error_document => 'http://host.domain/cgi-bin/errors.cgi?error=%s'
183
184       auto_rest
185           This tells Dispatch that you are using REST by default and that you
186           care about which HTTP method is being used. Dispatch will append
187           the HTTP method name (upper case by default) to the run mode that
188           is determined after finding the appropriate dispatch rule. So a GET
189           request that translates into "MyApp::Module-"foo> will become
190           "MyApp::Module-"foo_GET>.
191
192           This can be overridden on a per-rule basis in a custom dispatch
193           table.
194
195       auto_rest_lc
196           In combinaion with auto_rest this tells Dispatch that you prefer
197           lower cased HTTP method names.  So instead of "foo_POST" and
198           "foo_GET" you'll have "foo_post" and "foo_get".
199
200   dispatch_path()
201       This method returns the path that is to be processed.
202
203       By default it returns the value of $ENV{PATH_INFO} (or "$r->path_info"
204       under mod_perl) which should work for most cases.  It allows the
205       ability for subclasses to override the value if they need to do
206       something more specific.
207
208   handler()
209       This method is used so that this module can be run as a mod_perl
210       handler.  When it creates the application module it passes the $r
211       argument into the PARAMS hash of new()
212
213           <Location /app>
214               SetHandler perl-script
215               PerlHandler CGI::Application::Dispatch
216               PerlSetVar  CGIAPP_DISPATCH_PREFIX  MyApp
217               PerlSetVar  CGIAPP_DISPATCH_DEFAULT /module_name
218           </Location>
219
220       The above example would tell apache that any url beginning with /app
221       will be handled by CGI::Application::Dispatch. It also sets the prefix
222       used to create the application module to 'MyApp' and it tells
223       CGI::Application::Dispatch that it shouldn't set the run mode but that
224       it will be determined by the application module as usual (through the
225       query string). It also sets a default application module to be used if
226       there is no path.  So, a url of "/app/module_name" would create an
227       instance of "MyApp::Module::Name".
228
229       Using this method will add the "Apache-"request> object to your
230       application's "PARAMS" as 'r'.
231
232           # inside your app
233           my $request = $self->param('r');
234
235       If you need more customization than can be accomplished with just
236       prefix and default, then it would be best to just subclass
237       CGI::Application::Dispatch and override dispatch_args since "handler()"
238       uses dispatch to do the heavy lifting.
239
240           package MyApp::Dispatch;
241           use base 'CGI::Application::Dispatch';
242
243           sub dispatch_args {
244               return {
245                   prefix  => 'MyApp',
246                   table   => [
247                       ''                => { app => 'Welcome', rm => 'start' },
248                       ':app/:rm'        => { },
249                       'admin/:app/:rm'  => { prefix   => 'MyApp::Admin' },
250                   ],
251                   args_to_new => {
252                       PARAMS => {
253                           foo => 'bar',
254                           baz => 'bam',
255                       },
256                   }
257               };
258           }
259
260           1;
261
262       And then in your httpd.conf
263
264           <Location /app>
265               SetHandler perl-script
266               PerlHandler MyApp::Dispatch
267           </Location>
268
269   dispatch_args()
270       Returns a hashref of args that will be passed to dispatch(). It will
271       return the following structure by default.
272
273           {
274               prefix      => '',
275               args_to_new => {},
276               table       => [
277                   ':app'      => {},
278                   ':app/:rm'  => {},
279               ],
280           }
281
282       This is the perfect place to override when creating a subclass to
283       provide a richer dispatch table.
284
285       When called, it receives 1 argument, which is a reference to the hash
286       of args passed into dispatch.
287
288   translate_module_name($input)
289       This method is used to control how the module name is translated from
290       the matching section of the path (see "Path Parsing".  The main reason
291       that this method exists is so that it can be overridden if it doesn't
292       do exactly what you want.
293
294       The following transformations are performed on the input:
295
296       The text is split on '_'s (underscores) and each word has its first
297       letter capitalized. The words are then joined back together and each
298       instance of an underscore is replaced by '::'.
299       The text is split on '-'s (hyphens) and each word has its first letter
300       capitalized. The words are then joined back together and each instance
301       of a hyphen removed.
302
303       Here are some examples to make it even clearer:
304
305           module_name         => Module::Name
306           module-name         => ModuleName
307           admin_top-scores    => Admin::TopScores
308
309   require_module($module_name)
310       This class method is used internally by CGI::Application::Dispatch to
311       take a module name (supplied by get_module_name) and require it in a
312       secure fashion. It is provided as a public class method so that if you
313       override other functionality of this module, you can still safely
314       require user specified modules. If there are any problems requiring the
315       named module, then we will "croak".
316
317           CGI::Application::Dispatch->require_module('MyApp::Module::Name');
318

DISPATCH TABLE

320       Sometimes it's easiest to explain with an example, so here you go:
321
322         CGI::Application::Dispatch->dispatch(
323           prefix      => 'MyApp',
324           args_to_new => {
325               TMPL_PATH => 'myapp/templates'
326           },
327           table       => [
328               ''                         => { app => 'Blog', rm => 'recent'},
329               'posts/:category'          => { app => 'Blog', rm => 'posts' },
330               ':app/:rm/:id'             => { app => 'Blog' },
331               'date/:year/:month?/:day?' => {
332                   app         => 'Blog',
333                   rm          => 'by_date',
334                   args_to_new => { TMPL_PATH => "events/" },
335               },
336           ]
337         );
338
339       So first, this call to dispatch sets the prefix and passes a
340       "TMPL_PATH" into args_to_new. Next it sets the table.
341
342   VOCABULARY
343       Just so we all understand what we're talking about....
344
345       A table is an array where the elements are gouped as pairs (similar to
346       a hash's key-value pairs, but as an array to preserve order). The first
347       element of each pair is called a "rule". The second element in the pair
348       is called the rule's "arg list".  Inside a rule there are slashes "/".
349       Anything set of characters between slashes is called a "token".
350
351   URL MATCHING
352       When a URL comes in, Dispatch tries to match it against each rule in
353       the table in the order in which the rules are given. The first one to
354       match wins.
355
356       A rule consists of slashes and tokens. A token can one of the following
357       types:
358
359       literal
360           Any token which does not start with a colon (":") is taken to be a
361           literal string and must appear exactly as-is in the URL in order to
362           match. In the rule
363
364               'posts/:category'
365
366           "posts" is a literal token.
367
368       variable
369           Any token which begins with a colon (":") is a variable token.
370           These are simply wild-card place holders in the rule that will
371           match anything in the URL that isn't a slash. These variables can
372           later be referred to by using the "$self->param" mechanism. In the
373           rule
374
375               'posts/:category'
376
377           ":category" is a variable token. If the URL matched this rule, then
378           you could retrieve the value of that token from whithin your
379           application like so:
380
381               my $category = $self->param('category');
382
383           There are some variable tokens which are special. These can be used
384           to further customize the dispatching.
385
386           :app
387               This is the module name of the application. The value of this
388               token will be sent to the translate_module_name method and then
389               prefixed with the prefix if there is one.
390
391           :rm This is the run mode of the application. The value of this
392               token will be the actual name of the run mode used.
393
394       optional-variable
395           Any token which begins with a colon (":") and ends with a question
396           mark (<?>) is considered optional. If the rest of the URL matches
397           the rest of the rule, then it doesn't matter whether it contains
398           this token or not. It's best to only include optional-variable
399           tokens at the end of your rule. In the rule
400
401               'date/:year/:month?/:day?'
402
403           ":month?" and ":day?" are optional-variable tokens.
404
405           Just like with variable tokens, optional-variable tokens' values
406           can also be retrieved by the application, if they existed in the
407           URL.
408
409               if( defined $self->param('month') ) {
410                   ...
411               }
412
413       wildcard
414           The wildcard token "*" allows for partial matches. The token MUST
415           appear at the end of the rule.
416
417             'posts/list/*'
418
419           By default, the "dispatch_url_remainder" param is set to the
420           remainder of the URL matched by the *. The name of the param can be
421           changed by setting "*" argument in the "ARG LIST".
422
423             'posts/list/*' => { '*' => 'post_list_filter' }
424
425       method
426           You can also dispatch based on HTTP method. This is similar to
427           using auto_rest but offers more fine grained control. You include
428           the method (case insensitive) at the end of the rule and enclose it
429           in square brackets.
430
431             ':app/news[post]'   => { rm => 'add_news'    },
432             ':app/news[get]'    => { rm => 'news'        },
433             ':app/news[delete]' => { rm => 'delete_news' },
434
435       The main reason that we don't use regular expressions for dispatch
436       rules is that regular expressions provide no mechanism for named back
437       references, like variable tokens do.
438
439   ARG LIST
440       Each rule can have an accompanying arg-list. This arg list can contain
441       special arguments that override something set higher up in dispatch for
442       this particular URL, or just have additional args passed available in
443       "$self->param()"
444
445       For instance, if you want to override prefix for a specific rule, then
446       you can do so.
447
448           'admin/:app/:rm' => { prefix => 'MyApp::Admin' },
449

Path Parsing

451       This section will describe how the application module and run mode are
452       determined from the path if no "DISPATCH TABLE" is present, and what
453       options you have to customize the process.  The value for the path to
454       be parsed is retrieved from the dispatch_path method, which by default
455       uses the "PATH_INFO" environment variable.
456
457   Getting the module name
458       To get the name of the application module the path is split on
459       backslahes ("/").  The second element of the returned list (the first
460       is empty) is used to create the application module. So if we have a
461       path of
462
463           /module_name/mode1
464
465       then the string 'module_name' is used. This is passed through the
466       translate_module_name method. Then if there is a "prefix" (and there
467       should always be a prefix) it is added to the beginning of this new
468       module name with a double colon "::" separating the two.
469
470       If you don't like the exact way that this is done, don't fret you do
471       have a couple of options.  First, you can specify a "DISPATCH TABLE"
472       which is much more powerful and flexible (in fact this default behavior
473       is actually implemented internally with a dispatch table).  Or if you
474       want something a little simpler, you can simply subclass and extend the
475       translate_module_name method.
476
477   Getting the run mode
478       Just like the module name is retrieved from splitting the path on
479       slashes, so is the run mode. Only instead of using the second element
480       of the resulting list, we use the third as the run mode. So, using the
481       same example, if we have a path of
482
483           /module_name/mode2
484
485       Then the string 'mode2' is used as the run mode.
486

MISC NOTES

488       ·       CGI query strings
489
490               CGI query strings are unaffected by the use of "PATH_INFO" to
491               obtain the module name and run mode.  This means that any other
492               modules you use to get access to you query argument (ie, CGI,
493               Apache::Request) should not be affected. But, since the run
494               mode may be determined by CGI::Application::Dispatch having a
495               query argument named 'rm' will be ignored by your application
496               module.
497

CLEAN URLS WITH MOD_REWRITE

499       With a dispatch script, you can fairly clean URLS like this:
500
501        /cgi-bin/dispatch.cgi/module_name/run_mode
502
503       However, including "/cgi-bin/dispatch.cgi" in ever URL doesn't add any
504       value to the URL, so it's nice to remove it. This is easily done if you
505       are using the Apache web server with "mod_rewrite" available. Adding
506       the following to a ".htaccess" file would allow you to simply use:
507
508        /module_name/run_mode
509
510       If you have problems with mod_rewrite, turn on debugging to see exactly
511       what's happening:
512
513        RewriteLog /home/project/logs/alpha-rewrite.log
514        RewriteLogLevel 9
515
516   mod_rewrite related code in the dispatch script.
517       This seemed necessary to put in the dispatch script to make mod_rewrite
518       happy.  Perhaps it's specific to using "RewriteBase".
519
520         # mod_rewrite alters the PATH_INFO by turning it into a file system path,
521         # so we repair it.
522         $ENV{PATH_INFO} =~ s/^$ENV{DOCUMENT_ROOT}// if defined $ENV{PATH_INFO};
523
524   Simple Apache Example
525         RewriteEngine On
526
527         # You may want to change the base if you are using the dispatcher within a
528         # specific directory.
529         RewriteBase /
530
531         # If an actual file or directory is requested, serve directly
532         RewriteCond %{REQUEST_FILENAME} !-f
533         RewriteCond %{REQUEST_FILENAME} !-d
534
535         # Otherwise, pass everything through to the dispatcher
536         RewriteRule ^(.*)$ /cgi-bin/dispatch.cgi/$1 [L,QSA]
537
538   More complex rewrite: dispatching "/" and multiple developers
539       Here is a more complex example that dispatches "/", which would
540       otherwise be treated as a directory, and also supports multiple
541       developer directories, so "/~mark" has its own seperate dispatching
542       system beneath it.
543
544       Note that order matters here! The Location block for "/" needs to come
545       before the user blocks.
546
547         <Location />
548           RewriteEngine On
549           RewriteBase /
550
551           # Run "/" through the dispatcher
552           RewriteRule ^home/project/www/$ /cgi-bin/dispatch.cgi [L,QSA]
553
554           # Don't apply this rule to the users sub directories.
555           RewriteCond %{REQUEST_URI} !^/~.*$
556           # If an actual file or directory is requested, serve directly
557           RewriteCond %{REQUEST_FILENAME} !-f
558           RewriteCond %{REQUEST_FILENAME} !-d
559           # Otherwise, pass everything through to the dispatcher
560           RewriteRule ^(.*)$ /cgi-bin/dispatch.cgi/$1 [L,QSA]
561         </Location>
562
563         <Location /~mark>
564           RewriteEngine On
565           RewriteBase /~mark
566
567           # Run "/" through the dispatcher
568           RewriteRule ^/home/mark/www/$ /~mark/cgi-bin/dispatch.cgi [L,QSA]
569
570            # Otherwise, if an actual file or directory is requested, serve directly
571           RewriteCond %{REQUEST_FILENAME} !-f
572           RewriteCond %{REQUEST_FILENAME} !-d
573
574            # Otherwise, pass everything through to the dispatcher
575           RewriteRule ^(.*)$ /~mark/cgi-bin/dispatch.cgi/$1 [L,QSA]
576
577           # These examples may also be helpful, but are unrelated to dispatching.
578           SetEnv DEVMODE mark
579           SetEnv PERL5LIB /home/mark/perllib:/home/mark/config
580           ErrorDocument 404 /~mark/errdocs/404.html
581           ErrorDocument 500 /~mark/errdocs/500.html
582         </Location>
583

SUBCLASSING

585       While Dispatch tries to be flexible, it won't be able to do everything
586       that people want. Hopefully we've made it flexible enough so that if it
587       doesn't do The Right Thing you can easily subclass it.
588

AUTHOR

590       Michael Peters <mpeters@plusthree.com>
591
592       Thanks to Plus Three, LP (http://www.plusthree.com) for sponsoring my
593       work on this module
594

COMMUNITY

596       This module is a part of the larger CGI::Application community. If you
597       have questions or comments about this module then please join us on the
598       cgiapp mailing list by sending a blank message to
599       "cgiapp-subscribe@lists.erlbaum.net". There is also a community wiki
600       located at http://www.cgi-app.org/ <http://www.cgi-app.org/>
601

SOURCE CODE REPOSITORY

603       A public source code repository for this project is hosted here:
604
605       http://code.google.com/p/cgi-app-modules/source/checkout
606

CONTRIBUTORS

608       ·   Shawn Sorichetti
609
610       ·   Timothy Appnel
611
612       ·   dsteinbrunner
613
614       ·   ZACKSE
615
616       ·   Stew Heckenberg
617
618       ·   Drew Taylor <drew@drewtaylor.com>
619
620       ·   James Freeman <james.freeman@smartsurf.org>
621
622       ·   Michael Graham <magog@the-wire.com>
623
624       ·   Cees Hek <ceeshek@gmail.com>
625
626       ·   Mark Stosberg <mark@summersault.com>
627
628       ·   Viacheslav Sheveliov <slavash@aha.ru>
629

SECURITY

631       Since C::A::Dispatch will dynamically choose which modules to use as
632       the content generators, it may give someone the ability to execute
633       random modules on your system if those modules can be found in you
634       path. Of course those modules would have to behave like
635       CGI::Application based modules, but that still opens up the door more
636       than most want. This should only be a problem if you don't use a
637       prefix. By using this option you are only allowing Dispatch to pick
638       from a namespace of modules to run.
639

SEE ALSO

641       CGI::Application, Apache::Dispatch
642
644       Copyright Michael Peters and Mark Stosberg 2008, all rights reserved.
645
646       This library is free software; you can redistribute it and/or modify it
647       under the same terms as Perl itself.
648
649
650
651perl v5.12.0                      2010-04-30     CGI::Application::Dispatch(3)
Impressum