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 less-than
147           sign ("<"). First character will be excluded as well. Path of this
148           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 environment 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
182               # http://host.domain/cgi-bin/errors.cgi?error=404
183               error_document => 'http://host.domain/cgi-bin/errors.cgi?error=%s'
184
185       auto_rest
186           This tells Dispatch that you are using REST by default and that you
187           care about which HTTP method is being used. Dispatch will append
188           the HTTP method name (upper case by default) to the run mode that
189           is determined after finding the appropriate dispatch rule. So a GET
190           request that translates into "MyApp::Module->foo" will become
191           "MyApp::Module->foo_GET".
192
193           This can be overridden on a per-rule basis in a custom dispatch
194           table.
195
196       auto_rest_lc
197           In combinaion with auto_rest this tells Dispatch that you prefer
198           lower cased HTTP method names.  So instead of "foo_POST" and
199           "foo_GET" you'll have "foo_post" and "foo_get".
200
201   dispatch_path()
202       This method returns the path that is to be processed.
203
204       By default it returns the value of $ENV{PATH_INFO} (or "$r->path_info"
205       under mod_perl) which should work for most cases.  It allows the
206       ability for subclasses to override the value if they need to do
207       something more specific.
208
209   handler()
210       This method is used so that this module can be run as a mod_perl
211       handler.  When it creates the application module it passes the $r
212       argument into the PARAMS hash of new()
213
214           <Location /app>
215               SetHandler perl-script
216               PerlHandler CGI::Application::Dispatch
217               PerlSetVar  CGIAPP_DISPATCH_PREFIX  MyApp
218               PerlSetVar  CGIAPP_DISPATCH_DEFAULT /module_name
219           </Location>
220
221       The above example would tell apache that any url beginning with /app
222       will be handled by CGI::Application::Dispatch. It also sets the prefix
223       used to create the application module to 'MyApp' and it tells
224       CGI::Application::Dispatch that it shouldn't set the run mode but that
225       it will be determined by the application module as usual (through the
226       query string). It also sets a default application module to be used if
227       there is no path.  So, a url of "/app/module_name" would create an
228       instance of "MyApp::Module::Name".
229
230       Using this method will add the "Apache-"request> object to your
231       application's "PARAMS" as 'r'.
232
233           # inside your app
234           my $request = $self->param('r');
235
236       If you need more customization than can be accomplished with just
237       prefix and default, then it would be best to just subclass
238       CGI::Application::Dispatch and override dispatch_args since "handler()"
239       uses dispatch to do the heavy lifting.
240
241           package MyApp::Dispatch;
242           use base 'CGI::Application::Dispatch';
243
244           sub dispatch_args {
245               return {
246                   prefix  => 'MyApp',
247                   table   => [
248                       ''                => { app => 'Welcome', rm => 'start' },
249                       ':app/:rm'        => { },
250                       'admin/:app/:rm'  => { prefix   => 'MyApp::Admin' },
251                   ],
252                   args_to_new => {
253                       PARAMS => {
254                           foo => 'bar',
255                           baz => 'bam',
256                       },
257                   }
258               };
259           }
260
261           1;
262
263       And then in your httpd.conf
264
265           <Location /app>
266               SetHandler perl-script
267               PerlHandler MyApp::Dispatch
268           </Location>
269
270   dispatch_args()
271       Returns a hashref of args that will be passed to dispatch(). It will
272       return the following structure by default.
273
274           {
275               prefix      => '',
276               args_to_new => {},
277               table       => [
278                   ':app'      => {},
279                   ':app/:rm'  => {},
280               ],
281           }
282
283       This is the perfect place to override when creating a subclass to
284       provide a richer dispatch table.
285
286       When called, it receives 1 argument, which is a reference to the hash
287       of args passed into dispatch.
288
289   translate_module_name($input)
290       This method is used to control how the module name is translated from
291       the matching section of the path (see "Path Parsing").  The main reason
292       that this method exists is so that it can be overridden if it doesn't
293       do exactly what you want.
294
295       The following transformations are performed on the input:
296
297       The text is split on '_'s (underscores) and each word has its first
298       letter capitalized. The words are then joined back together and each
299       instance of an underscore is replaced by '::'.
300       The text is split on '-'s (hyphens) and each word has its first letter
301       capitalized. The words are then joined back together and each instance
302       of a hyphen removed.
303
304       Here are some examples to make it even clearer:
305
306           module_name         => Module::Name
307           module-name         => ModuleName
308           admin_top-scores    => Admin::TopScores
309
310   require_module($module_name)
311       This class method is used internally by CGI::Application::Dispatch to
312       take a module name (supplied by get_module_name) and require it in a
313       secure fashion. It is provided as a public class method so that if you
314       override other functionality of this module, you can still safely
315       require user specified modules. If there are any problems requiring the
316       named module, then we will "croak".
317
318           CGI::Application::Dispatch->require_module('MyApp::Module::Name');
319

DISPATCH TABLE

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

Path Parsing

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

MISC NOTES

500       ·       CGI query strings
501
502               CGI query strings are unaffected by the use of "PATH_INFO" to
503               obtain the module name and run mode.  This means that any other
504               modules you use to get access to you query argument (ie, CGI,
505               Apache::Request) should not be affected. But, since the run
506               mode may be determined by CGI::Application::Dispatch having a
507               query argument named 'rm' will be ignored by your application
508               module.
509

CLEAN URLS WITH MOD_REWRITE

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

SUBCLASSING

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

AUTHOR

603       Michael Peters <mpeters@plusthree.com>
604
605       Thanks to Plus Three, LP (http://www.plusthree.com) for sponsoring my
606       work on this module
607

COMMUNITY

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

SOURCE CODE REPOSITORY

616       A public source code repository for this project is hosted here:
617
618       http://code.google.com/p/cgi-app-modules/source/checkout
619

CONTRIBUTORS

621       ·   Shawn Sorichetti
622
623       ·   Timothy Appnel
624
625       ·   dsteinbrunner
626
627       ·   ZACKSE
628
629       ·   Stew Heckenberg
630
631       ·   Drew Taylor <drew@drewtaylor.com>
632
633       ·   James Freeman <james.freeman@smartsurf.org>
634
635       ·   Michael Graham <magog@the-wire.com>
636
637       ·   Cees Hek <ceeshek@gmail.com>
638
639       ·   Mark Stosberg <mark@summersault.com>
640
641       ·   Viacheslav Sheveliov <slavash@aha.ru>
642

SECURITY

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

SEE ALSO

654       CGI::Application, Apache::Dispatch
655
657       Copyright Michael Peters and Mark Stosberg 2008, all rights reserved.
658
659       This library is free software; you can redistribute it and/or modify it
660       under the same terms as Perl itself.
661
662
663
664perl v5.30.1                      2020-01-29     CGI::Application::Dispatch(3)
Impressum