1HTML::Mason::Request(3)User Contributed Perl DocumentatioHnTML::Mason::Request(3)
2
3
4

NAME

6       HTML::Mason::Request - Mason Request Class
7

SYNOPSIS

9           $m->abort (...)
10           $m->comp (...)
11           etc.
12

DESCRIPTION

14       The Request API is your gateway to all Mason features not provided by
15       syntactic tags. Mason creates a new Request object for every web
16       request. Inside a component you access the current request object via
17       the global $m.  Outside of a component, you can use the class method
18       "instance".
19

COMPONENT PATHS

21       The methods Request->comp, Request->comp_exists, and
22       Request->fetch_comp take a component path argument.  Component paths
23       are like URL paths, and always use a forward slash (/) as the
24       separator, regardless of what your operating system uses.
25
26       ·   If the path is absolute (starting with a '/'), then the component
27           is found relative to the component root.
28
29       ·   If the path is relative (no leading '/'), then the component is
30           found relative to the current component directory.
31
32       ·   If the path matches both a subcomponent and file-based component,
33           the subcomponent takes precedence.
34

PARAMETERS TO THE new() CONSTRUCTOR

36       autoflush
37           True or false, default is false. Indicates whether to flush the
38           output buffer ("$m->flush_buffer") after every string is output.
39           Turn on autoflush if you need to send partial output to the client,
40           for example in a progress meter.
41
42           As of Mason 1.3, autoflush will only work if enable_autoflush has
43           been set.  Components can be compiled more efficiently if they
44           don't have to check for autoflush. Before using autoflush you might
45           consider whether a few manual "$m->flush_buffer" calls would work
46           nearly as well.
47
48       data_cache_api
49           The "$m->cache" API to use:
50
51           ·   '1.1', the default, indicates a "Cache::Cache" based API.
52
53           ·   'chi' indicates a "CHI" based API.
54
55           ·   '1.0' indicates the custom cache API used in Mason 1.0x and
56               earlier. This compatibility layer is provided as a convenience
57               for users upgrading from older versions of Mason, but will not
58               be supported indefinitely.
59
60       data_cache_defaults
61           A hash reference of default options to use for the "$m->cache"
62           command.  For example, to use Cache::Cache's "MemoryCache"
63           implementation by default:
64
65               data_cache_defaults => {cache_class => 'MemoryCache'}
66
67           To use the CHI "FastMmap" driver by default:
68
69               data_cache_api      => 'CHI',
70               data_cache_defaults => {driver => 'FastMmap'},
71
72           These settings are overridden by options given to particular
73           "$m->cache" calls.
74
75       dhandler_name
76           File name used for dhandlers. Default is "dhandler".  If this is
77           set to an empty string ("") then dhandlers are turned off entirely.
78
79       error_format
80           Indicates how errors are formatted. The built-in choices are
81
82           ·   brief - just the error message with no trace information
83
84           ·   text - a multi-line text format
85
86           ·   line - a single-line text format, with different pieces of
87               information separated by tabs (useful for log files)
88
89           ·   html - a fancy html format
90
91           The default format under Apache and CGI is either line or html
92           depending on whether the error mode is fatal or output,
93           respectively. The default for standalone mode is text.
94
95           The formats correspond to "HTML::Mason::Exception" methods named
96           as_format. You can define your own format by creating an
97           appropriately named method; for example, to define an "xml" format,
98           create a method "HTML::Mason::Exception::as_xml" patterned after
99           one of the built-in methods.
100
101       error_mode
102           Indicates how errors are returned to the caller.  The choices are
103           fatal, meaning die with the error, and output, meaning output the
104           error just like regular output.
105
106           The default under Apache and CGI is output, causing the error to be
107           displayed in the browser.  The default for standalone mode is
108           fatal.
109
110       component_error_handler
111           A code reference used to handle errors thrown during component
112           compilation or runtime. By default, this is a subroutine that turns
113           non-exception object errors in components into exceptions. If this
114           parameter is set to a false value, these errors are simply rethrown
115           as-is.
116
117           Turning exceptions into objects can be expensive, since this will
118           cause the generation of a stack trace for each error. If you are
119           using strings or unblessed references as exceptions in your code,
120           you may want to turn this off as a performance boost.
121
122       max_recurse
123           The maximum recursion depth for the component stack, for the
124           request stack, and for the inheritance stack. An error is signalled
125           if the maximum is exceeded.  Default is 32.
126
127       out_method
128           Indicates where to send output. If out_method is a reference to a
129           scalar, output is appended to the scalar.  If out_method is a
130           reference to a subroutine, the subroutine is called with each
131           output string. For example, to send output to a file called
132           "mason.out":
133
134               my $fh = new IO::File ">mason.out";
135               ...
136               out_method => sub { $fh->print($_[0]) }
137
138           By default, out_method prints to standard output. Under Apache,
139           standard output is redirected to "$r->print".
140
141       plugins
142           An array of plugins that will be called at various stages of
143           request processing.  Please see HTML::Mason::Plugin for details.
144

ACCESSOR METHODS

146       All of the above properties have standard accessor methods of the same
147       name. In general, no arguments retrieves the value, and one argument
148       sets and returns the value.  For example:
149
150           my $max_recurse_level = $m->max_recurse;
151           $m->autoflush(1);
152

OTHER METHODS

154       abort ([return value])
155           Ends the current request, finishing the page without returning
156           through components. The optional argument specifies the return
157           value from "Interp::exec"; in a web environment, this ultimately
158           becomes the HTTP status code.
159
160           "abort" is implemented by throwing an HTML::Mason::Exception::Abort
161           object and can thus be caught by eval(). The "aborted" method is a
162           shortcut for determining whether a caught error was generated by
163           "abort".
164
165           If "abort" is called from a component that has a "<%filter>", than
166           any output generated up to that point is filtered, unless "abort"
167           is called from a "<%shared>" block.
168
169       clear_and_abort ([return value])
170           This method is syntactic sugar for calling "clear_buffer()" and
171           then "abort()".  If you are aborting the request because of an
172           error, you will often want to clear the buffer first so that any
173           output generated up to that point is not sent to the client.
174
175       aborted ([$err])
176           Returns true or undef indicating whether the specified $err was
177           generated by "abort". If no $err was passed, uses $@.
178
179           In this code, we catch and process fatal errors while letting
180           "abort" exceptions pass through:
181
182               eval { code_that_may_fail_or_abort() };
183               if ($@) {
184                   die $@ if $m->aborted;
185
186                   # handle fatal errors...
187
188           $@ can lose its value quickly, so if you are planning to call
189           $m->aborted more than a few lines after the eval, you should save
190           $@ to a temporary variable.
191
192       base_comp
193           Returns the current base component.
194
195           Here are the rules that determine base_comp as you move from
196           component to component.
197
198           ·   At the beginning of a request, the base component is
199               initialized to the requested component ("$m->request_comp()").
200
201           ·   When you call a regular component via a path, the base
202               component changes to the called component.
203
204           ·   When you call a component method via a path (/foo/bar:baz), the
205               base component changes to the method's owner.
206
207           ·   The base component does not change when:
208
209               ·   a component call is made to a component object
210
211               ·   a component call is made to SELF:x or PARENT:x or REQUEST:x
212
213               ·   a component call is made to a subcomponent (<%def>)
214
215           This may return nothing if the base component is not yet known, for
216           example inside a plugin's "start_request_hook()" method, where we
217           have created a request but it does not yet know anything about the
218           component being called.
219
220       cache
221           "$m->cache" returns a new cache object with a namespace specific to
222           this component. The parameters to and return value from "$m->cache"
223           differ depending on which data_cache_api you are using.
224
225           If data_cache_api = 1.1 (default)
226               cache_class specifies the class of cache object to create. It
227               defaults to "FileCache" in most cases, or "MemoryCache" if the
228               interpreter has no data directory, and must be a backend
229               subclass of "Cache::Cache". The prefix "Cache::" need not be
230               included.  See the "Cache::Cache" package for a full list of
231               backend subclasses.
232
233               Beyond that, cache_options may include any valid options to the
234               new() method of the cache class. e.g. for "FileCache", valid
235               options include "default_expires_in" and "cache_depth".
236
237               See HTML::Mason::Cache::BaseCache for information about the
238               object returned from "$m->cache".
239
240           If data_cache_api = CHI
241               chi_root_class specifies the factory class that will be called
242               to create cache objects. The default is 'CHI'.
243
244               driver specifies the driver to use, for example "Memory" or
245               "FastMmap".  The default is "File" in most cases, or "Memory"
246               if the interpreter has no data directory.
247
248               Beyond that, cache_options may include any valid options to the
249               new() method of the driver. e.g. for the "File" driver, valid
250               options include "expires_in" and "depth".
251
252       cache_self ([expires_in => '...'], [key => '...'], [get_options],
253       [cache_options])
254           "$m->cache_self" caches the entire output and return result of a
255           component.
256
257           "cache_self" either returns undef, or a list containing the return
258           value of the component followed by '1'. You should return
259           immediately upon getting the latter result, as this indicates that
260           you are inside the second invocation of the component.
261
262           "cache_self" takes any of parameters to "$m->cache" (e.g.
263           cache_depth), any of the optional parameters to "$cache->get"
264           (expire_if, busy_lock), and two additional options:
265
266           ·   expire_in or expires_in: Indicates when the cache expires - it
267               is passed as the third argument to "$cache->set". e.g. '10
268               sec', '5 min', '2 hours'.
269
270           ·   key: An identifier used to uniquely identify the cache results
271               - it is passed as the first argument to "$cache->get" and
272               "$cache->set".  The default key is '__mason_cache_self__'.
273
274           To cache the component's output:
275
276               <%init>
277               return if $m->cache_self(expire_in => '10 sec'[, key => 'fookey']);
278               ... <rest of init> ...
279               </%init>
280
281           To cache the component's scalar return value:
282
283               <%init>
284               my ($result, $cached) = $m->cache_self(expire_in => '5 min'[, key => 'fookey']);
285
286               return $result if $cached;
287               ... <rest of init> ...
288               </%init>
289
290           To cache the component's list return value:
291
292               <%init>
293               my (@retval) = $m->cache_self(expire_in => '3 hours'[, key => 'fookey']);
294
295               return @retval if pop @retval;
296               ... <rest of init> ...
297               </%init>
298
299           We call "pop" on @retval to remove the mandatory '1' at the end of
300           the list.
301
302           If a component has a "<%filter>" block, then the filtered output is
303           cached.
304
305           Note: users upgrading from 1.0x and earlier can continue to use the
306           old "$m->cache_self" API by setting data_cache_api to '1.0'.  This
307           support will be removed at a later date.
308
309           See the the DATA CACHING section of the developer's manual section
310           for more details on how to exercise finer control over caching.
311
312       caller_args
313           Returns the arguments passed by the component at the specified
314           stack level. Use a positive argument to count from the current
315           component and a negative argument to count from the component at
316           the bottom of the stack. e.g.
317
318               $m->caller_args(0)   # arguments passed to current component
319               $m->caller_args(1)   # arguments passed to component that called us
320               $m->caller_args(-1)  # arguments passed to first component executed
321
322           When called in scalar context, a hash reference is returned.  When
323           called in list context, a list of arguments (which may be assigned
324           to a hash) is returned.  Returns undef or an empty list, depending
325           on context, if the specified stack level does not exist.
326
327       callers
328           With no arguments, returns the current component stack as a list of
329           component objects, starting with the current component and ending
330           with the top-level component. With one numeric argument, returns
331           the component object at that index in the list. Use a positive
332           argument to count from the current component and a negative
333           argument to count from the component at the bottom of the stack.
334           e.g.
335
336               my @comps = $m->callers   # all components
337               $m->callers(0)            # current component
338               $m->callers(1)            # component that called us
339               $m->callers(-1)           # first component executed
340
341           Returns undef or an empty list, depending on context, if the
342           specified stack level does not exist.
343
344       caller
345           A synonym for "$m->callers(1)", i.e. the component that called the
346           currently executing component.
347
348       call_next ([args...])
349           Calls the next component in the content wrapping chain; usually
350           called from an autohandler. With no arguments, the original
351           arguments are passed to the component.  Any arguments specified
352           here serve to augment and override (in case of conflict) the
353           original arguments. Works like "$m->comp" in terms of return value
354           and scalar/list context.  See the autohandlers section of the
355           developer's manual for examples.
356
357       call_self (output, return, error, tag)
358           This method allows a component to call itself so that it can filter
359           both its output and return values.  It is fairly advanced; for most
360           purposes the "<%filter>" tag will be sufficient and simpler.
361
362           "$m->call_self" takes four arguments, all of them optional.
363
364           output - scalar reference that will be populated with the component
365           output.
366           return - scalar reference that will be populated with the component
367           return value.
368           error - scalar reference that will be populated with the error
369           thrown by the component, if any. If this parameter is not defined,
370           then call_self will not catch errors.
371           tag - a name for this call_self invocation; can almost always be
372           omitted.
373
374           "$m->call_self" acts like a "fork()" in the sense that it will
375           return twice with different values.  When it returns 0, you allow
376           control to pass through to the rest of your component.  When it
377           returns 1, that means the component has finished and you can
378           examine the output, return value and error. (Don't worry, it
379           doesn't really do a fork! See next section for explanation.)
380
381           The following examples would generally appear at the top of a
382           "<%init>" section.  Here is a no-op "$m->call_self" that leaves the
383           output and return value untouched:
384
385               <%init>
386               my ($output, $retval);
387               if ($m->call_self(\$output, \$retval)) {
388                   $m->print($output);
389                   return $retval;
390               }
391               ...
392
393           Here is a simple output filter that makes the output all uppercase.
394           Note that we ignore both the original and the final return value.
395
396               <%init>
397               my ($output, $error);
398               if ($m->call_self(\$output, undef)) {
399                   $m->print(uc $output);
400                   return;
401               }
402               ...
403
404           Here is a piece of code that traps all errors occurring anywhere in
405           a component or its children, e.g. for the purpose of handling
406           application-specific exceptions. This is difficult to do with a
407           manual "eval" because it would have to span multiple code sections
408           and the main component body.
409
410               <%init>
411               my ($output, undef, $error);
412               if ($m->call_self(\$output, undef, \$error)) {
413                   if ($error) {
414                       # check $error and do something with it
415                   }
416                   $m->print($output);
417                   return;
418               }
419               ...
420
421       clear_buffer
422           Clears the Mason output buffer. Any output sent before this line is
423           discarded. Useful for handling error conditions that can only be
424           detected in the middle of a request.
425
426           clear_buffer is, of course, thwarted by "flush_buffer".
427
428       comp (comp, args...)
429           Calls the component designated by comp with the specified
430           option/value pairs. comp may be a component path or a component
431           object.
432
433           Components work exactly like Perl subroutines in terms of return
434           values and context. A component can return any type of value, which
435           is then returned from the "$m->comp" call.
436
437           The <& &> tag provides a convenient shortcut for "$m->comp".
438
439           As of 1.10, component calls can accept an initial hash reference of
440           modifiers.  The only currently supported modifier is "store", which
441           stores the component's output in a scalar reference. For example:
442
443             my $buf;
444             my $return = $m->comp( { store => \$buf }, '/some/comp', type => 'big' );
445
446           This mostly duplicates the behavior of scomp, but can be useful in
447           rare cases where you need to capture both a component's output and
448           return value.
449
450           This modifier can be used with the <& &> tag as well, for example:
451
452             <& { store => \$buf }, '/some/comp', size => 'medium' &>
453
454       comp_exists (comp_path)
455           Returns 1 if comp_path is the path of an existing component, 0
456           otherwise.  comp_path may be any path accepted by comp or
457           fetch_comp, including method or subcomponent paths.
458
459           Depending on implementation, <comp_exists> may try to load the
460           component referred to by the path, and may throw an error if the
461           component contains a syntax error.
462
463       content
464           Evaluates the content (passed between <&| comp &> and </&> tags) of
465           the current component, and returns the resulting text.
466
467           Returns undef if there is no content.
468
469       has_content
470           Returns true if the component was called with content (i.e. with
471           <&| comp &> and </&> tags instead of a single <& comp &> tag). This
472           is generally better than checking the defined'ness of "$m->content"
473           because it will not try to evaluate the content.
474
475       count
476           Returns the number of this request, which is unique for a given
477           request and interpreter.
478
479       current_args
480           Returns the arguments passed to the current component. When called
481           in scalar context, a hash reference is returned.  When called in
482           list context, a list of arguments (which may be assigned to a hash)
483           is returned.
484
485       current_comp
486           Returns the current component object.
487
488       decline
489           Used from a top-level component or dhandler, this method clears the
490           output buffer, aborts the current request and restarts with the
491           next applicable dhandler up the tree. If no dhandler is available,
492           a not-found error occurs.
493
494           This method bears no relation to the Apache DECLINED status except
495           in name.
496
497       declined ([$err])
498           Returns true or undef indicating whether the specified $err was
499           generated by "decline". If no $err was passed, uses $@.
500
501       depth
502           Returns the current size of the component stack.  The lowest
503           possible value is 1, which indicates we are in the top-level
504           component.
505
506       dhandler_arg
507           If the request has been handled by a dhandler, this method returns
508           the remainder of the URI or "Interp::exec" path when the dhandler
509           directory is removed. Otherwise returns undef.
510
511           "dhandler_arg" may be called from any component in the request, not
512           just the dhandler.
513
514       exec (comp, args...)
515           Starts the request by executing the top-level component and
516           arguments. This is normally called for you on the main request, but
517           you can use it to execute subrequests.
518
519           A request can only be executed once; e.g. it is an error to call
520           this recursively on the same request.
521
522       fetch_comp (comp_path)
523           Given a comp_path, returns the corresponding component object or
524           undef if no such component exists.
525
526       fetch_next
527           Returns the next component in the content wrapping chain, or undef
528           if there is no next component. Usually called from an autohandler.
529           See the autohandlers section of the developer's manual for usage
530           and examples.
531
532       fetch_next_all
533           Returns a list of the remaining components in the content wrapping
534           chain. Usually called from an autohandler.  See the autohandlers
535           section of the developer's manual for usage and examples.
536
537       file (filename)
538           Returns the contents of filename as a string. If filename is a
539           relative path, Mason prepends the current component directory.
540
541       flush_buffer
542           Flushes the Mason output buffer. Under mod_perl, also sends HTTP
543           headers if they haven't been sent and calls "$r->rflush" to flush
544           the Apache buffer. Flushing the initial bytes of output can make
545           your servers appear more responsive.
546
547           Attempts to flush the buffers are ignored within the context of a
548           call to "$m->scomp" or when output is being stored in a scalar
549           reference, as with the " { store => \$out } " component call
550           modifier.
551
552           "<%filter>" blocks will process the output whenever the buffers are
553           flushed.  If "autoflush" is on, your data may be filtered in small
554           pieces.
555
556       instance
557           This class method returns the "HTML::Mason::Request" currently in
558           use.  If called when no Mason request is active it will return
559           "undef".
560
561           If called inside a subrequest, it returns the subrequest object.
562
563       interp
564           Returns the Interp object associated with this request.
565
566       make_subrequest (comp => path, args => arrayref, other parameters)
567           This method creates a new Request object which inherits its
568           parent's settable properties, such as autoflush and out_method.
569           These values may be overridden by passing parameters to this
570           method.
571
572           The "comp" parameter is required, while all other parameters are
573           optional.  It may be specified as an absolute path or as a path
574           relative to the current component.
575
576           See the subrequests section of the developer's manual for more
577           information about subrequests.
578
579       log Returns a "Log::Any" logger with a log category specific to the
580           current component.  The category for a component "/foo/bar" would
581           be "HTML::Mason::Component::foo::bar".
582
583       notes (key, value)
584           The "notes()" method provides a place to store application data,
585           giving developers a way to share data among multiple components.
586           Any data stored here persists for the duration of the request, i.e.
587           the same lifetime as the Request object.
588
589           Conceptually, "notes()" contains a hash of key-value pairs.
590           "notes($key, $value)" stores a new entry in this hash.
591           "notes($key)" returns a previously stored value.  "notes()" without
592           any arguments returns a reference to the entire hash of key-value
593           pairs.
594
595           "notes()" is similar to the mod_perl method "$r->pnotes()".  The
596           main differences are that this "notes()" can be used in a
597           non-mod_perl environment, and that its lifetime is tied to the
598           Mason request object, not the Apache request object.  In
599           particular, a Mason subrequest has its own "notes()" structure, but
600           would access the same "$r->pnotes()" structure.
601
602       out (string)
603           A synonym for "$m->print".
604
605       print (string)
606           Print the given string. Rarely needed, since normally all text is
607           just placed in the component body and output implicitly.
608           "$m->print" is useful if you need to output something in the middle
609           of a Perl block.
610
611           In 1.1 and on, "print" and "$r->print" are remapped to "$m->print",
612           so they may be used interchangeably. Before 1.1, one should only
613           use "$m->print".
614
615       request_args
616           Returns the arguments originally passed to the top level component
617           (see request_comp for definition).  When called in scalar context,
618           a hash reference is returned. When called in list context, a list
619           of arguments (which may be assigned to a hash) is returned.
620
621       request_comp
622           Returns the component originally called in the request. Without
623           autohandlers, this is the same as the first component executed.
624           With autohandlers, this is the component at the end of the
625           "$m->call_next" chain.
626
627       request_depth
628           Returns the current size of the request/subrequest stack.  The
629           lowest possible value is 1, which indicates we are in the top-level
630           request.  A value of 2 indicates we are inside a subrequest of the
631           top-level request, and so on.
632
633       scomp (comp, args...)
634           Like comp, but returns the component output as a string instead of
635           printing it. (Think sprintf versus printf.) The component's return
636           value is discarded.
637
638       subexec (comp, args...)
639           This method creates a new subrequest with the specified top-level
640           component and arguments, and executes it. This is most often used
641           to perform an "internal redirect" to a new component such that
642           autohandlers and dhandlers take effect.
643
644       time
645           Returns the interpreter's notion of the current time (deprecated).
646

APACHE-ONLY METHODS

648       These additional methods are available when running Mason with mod_perl
649       and the ApacheHandler.
650
651       ah  Returns the ApacheHandler object associated with this request.
652
653       apache_req
654           Returns the Apache request object.  This is also available in the
655           global $r.
656
657       auto_send_headers
658           True or false, default is true.  Indicates whether Mason should
659           automatically send HTTP headers before sending content back to the
660           client. If you set to false, you should call "$r->send_http_header"
661           manually.
662
663           See the sending HTTP headers section of the developer's manual for
664           more details about the automatic header feature.
665
666           NOTE: This parameter has no effect under mod_perl-2, since calling
667           "$r->send_http_header" is no longer needed.
668

CGI-ONLY METHODS

670       This additional method is available when running Mason with the
671       CGIHandler module.
672
673       cgi_request
674           Returns the Apache request emulation object, which is available as
675           $r inside components.
676
677           See the CGIHandler docs for more details.
678

APACHE- OR CGI-ONLY METHODS

680       This method is available when Mason is running under either the
681       ApacheHandler or CGIHandler modules.
682
683       cgi_object
684           Returns the CGI object used to parse any CGI parameters submitted
685           to the component, assuming that you have not changed the default
686           value of the ApacheHandler args_method parameter.  If you are using
687           the 'mod_perl' args method, then calling this method is a fatal
688           error.  See the ApacheHandler and CGIHandler documentation for more
689           details.
690
691       redirect ($url, [$status])
692           Given a url, this generates a proper HTTP redirect for that URL. It
693           uses "$m->clear_and_abort" to clear out any previous output, and
694           abort the request.  By default, the status code used is 302, but
695           this can be overridden by the user.
696
697           Since this is implemented using "$m->abort", it will be trapped by
698           an " eval {} " block.  If you are using an " eval {} " block in
699           your code to trap errors, you need to make sure to rethrow these
700           exceptions, like this:
701
702             eval {
703                 ...
704             };
705
706             die $@ if $m->aborted;
707
708             # handle other exceptions
709
710
711
712perl v5.32.0                      2020-07-28           HTML::Mason::Request(3)
Impressum