NAME
HTML::Mason::Request - Mason Request Class
SYNOPSIS
$m->abort (...)
$m->comp (...)
etc.
DESCRIPTION
The Request API is your gateway to all Mason features not provided by syntactic tags. Mason creates a new Request object for every web request. Inside a component you access the current request object via the global $m
. Outside of a component, you can use the class method instance
.
COMPONENT PATHS
The methods Request->comp, Request->comp_exists, and Request->fetch_comp take a component path argument. Component paths are like URL paths, and always use a forward slash (/) as the separator, regardless of what your operating system uses.
If the path is absolute (starting with a '/'), then the component is found relative to the component root.
If the path is relative (no leading '/'), then the component is found relative to the current component directory.
If the path matches both a subcomponent and file-based component, the subcomponent takes precedence.
CONSTRUCTOR PARAMETERS
- autoflush
-
Indicates whether or not to delay sending output until all output has been generated.
- data_cache_defaults
-
The default parameters used when $m->cache is called.
- dhandler_name
-
File name used for dhandlers. Default is "dhandler".
- error_format
-
The format used to display errors. The options are 'brief', 'text', 'line', and 'html'. The default is 'text' except when running under ApacheHandler, in which case the default is 'html'.
- error_mode
-
This can be either 'fatal' or 'output'. If the mode is 'fatal', errors generate an exception. With 'output' mode, the error is sent to the same output as normal component output. The default is 'fatal', except when running under ApacheHandler or CGIHandler, in which case the output is 'default'.
- max_recurse
-
The maximum recursion depth for the component stack, for the request stack, and for the inheritance stack. An error is signalled if the maximum is exceeded. Default is 32.
- out_method
-
Indicates where to send output. If out_method is a reference to a scalar, output is appended to the scalar. If out_method is a reference to a subroutine, the subroutine is called with each output string. For example, to send output to a file called "mason.out":
my $fh = new IO::File ">mason.out"; ... out_method => sub { $fh->print($_[0]) }
By default, out_method prints to standard output. When the HTML::Mason::ApacheHandler module is used, the out method uses the
$r->print
method to send output.
METHODS
expires_in: Indicates when the cache expires - it is passed as the third argument to $cache->set. See the Cache::Cache documentation for details on what formats it accepts.
key: An identifier used to uniquely identify the cache results - it is passed as the first argument to $cache->get and $cache->set. A default key will be provided if none is passed.
brief - just the error message with no trace information
text - a multi-line text format
line - a single-line text format, with different pieces of information separated by tabs (useful for log files)
html - a fancy html format
abort ([return value])
Ends the current request, finishing the page without returning through components. The optional argument specifies the return value from Interp::exec
; in a web environment, this ultimately becomes the HTTP status code.
abort
is implemented by throwing an HTML::Mason::Exception::Abort object and can thus be caught by eval(). The aborted
method is a shortcut for determining whether a caught error was generated by abort
.
aborted ([$err])
Returns true or undef indicating whether the specified $err
was generated by abort
. If no $err
was passed, use $@
.
In this code, we catch and process fatal errors while letting abort
exceptions pass through:
eval { code_that_may_fail_or_abort() };
if ($@) {
die $@ if $m->aborted;
# handle fatal errors...
$@
can lose its value quickly, so if you are planning to call $m->aborted more than a few lines after the eval, you should save $@ to a temporary variable.
base_comp
Returns the current base component for method and attributes. Generally set to the original page component; however, if you invoke call_method on a component, base_comp
is dynamically set to that component until call_method exits. See Object-Oriented Techniques in the Component Developer's Guide for examples of usage.
cache (cache_class=>'...', [cache_options])
$m->cache
returns a new cache object with a namespace specific to this component.
cache_class specifies the class of cache object to create. It defaults to Cache::FileCache in most cases, or Cache::MemoryCache if the interpreter has no data directory, and must be a subclass of Cache::Cache. If cache_class does not contain a "::", the prefix "Cache::" is automatically prepended.
cache_options may include any valid options to the new() method of the cache class. e.g. for Cache::FileCache, valid options include default_expires_in and cache_depth.
See the data caching in the Component Developer's Guide for examples and caching strategies. See the Cache::Cache documentation for a complete list of options and methods.
cache_self (expires_in => '...', key => '...', [cache_options])
$m->cache_self
caches the entire output and return result of a component.
It takes all of the options which can be passed to the cache method, plus two additional options:
cache_self
either returns undef, or a list containing the return value of the component followed by '1'. You should return immediately upon getting the latter result, as this indicates that you are inside the second invocation of the component.
To cache the component's output:
<%init>
return if $m->cache_self(expires_in => '3 hours'[, key => 'fookey']);
... <rest of init> ...
</%init>
To cache the component's scalar return value:
<%init>
my ($result, $cached) = $m->cache_self(expires_in => '3 hours'[, key => 'fookey']);
return $result if $cached;
... <rest of init> ...
</%init>
To cache the component's list return value:
<%init>
my (@retval) = $m->cache_self(expires_in => '3 hours'[, key => 'fookey']);
return @retval if pop @retval;
... <rest of init> ...
</%init>
We call pop
on @retval
to remove the mandatory '1' at the end of the list.
caller_args
Returns the arguments passed by the component at the specified stack level. Use a positive argument to count from the current component and a negative argument to count from the component at the bottom of the stack. e.g.
$m->caller_args(0) # arguments passed to current component
$m->caller_args(1) # arguments passed to component that called us
$m->caller_args(-1) # arguments passed to first component executed
When called in scalar context, a hash reference is returned. When called in list context, a list of arguments (which may be assigned to a hash) is returned.
callers
With no arguments, returns the current component stack as a list of component objects, starting with the current component and ending with the top-level component. With one numeric argument, returns the component object at that index in the list. Use a positive argument to count from the current component and a negative argument to count from the component at the bottom of the stack. e.g.
my @comps = $m->callers # all components
$m->callers(0) # current component
$m->callers(1) # component that called us
$m->callers(-1) # first component executed
call_next ([args...])
Calls the next component in the content wrapping chain; usually called from an autohandler. With no arguments, the original arguments are passed to the component. Any arguments specified here serve to augment and override (in case of conflict) the original arguments. Works like $m->comp
in terms of return value and scalar/list context. See the autohandlers section in the Component Developer's Guide for examples.
clear_buffer
Clears the Mason output buffer. Any output sent before this line is discarded. Useful for handling error conditions that can only be detected in the middle of a request.
clear_buffer is, of course, thwarted by flush_buffer
.
comp (comp, args...)
Calls the component designated by comp with the specified option/value pairs. comp may be a component path or a component object.
Components work exactly like Perl subroutines in terms of return values and context. A component can return any type of value, which is then returned from the $m->comp
call.
The <& &> tag provides a convenient shortcut for $m->comp
.
As of 1.10, component calls can accept an initial hash reference of modifiers. The only currently supported modifier is store
, which stores the component's output in a scalar reference. For example:
my $buf;
my $return = $m->comp( { store => \$buf }, '/some/comp', type => 'big' );
This mostly duplicates the behavior of scomp, but can be useful in rare cases where you need to capture both a component's output and return value.
This modifier can be used with the <& &> tag as well, for example:
<& { store => \$buf }, '/some/comp', size => 'medium' &>
comp_exists (comp_path)
Returns 1 if comp_path is the path of an existing component, 0 otherwise. That path given may be relative, in which case the current component's directory path will be prepended.
content
Evaluates the content (passed between <&| comp &> and </&> tags) of the current component, and returns the resulting text.
Returns undef if there is no content.
count
Returns the number of this request, which is unique for a given request and interpreter.
current_comp
Returns the current component object.
decline
Used from a top-level component or dhandler, this method clears the output buffer, aborts the current request and restarts with the next applicable dhandler up the tree. If no dhandler is available, an error occurs. This method bears no relation to the Apache DECLINED status except in name.
depth
Returns the current size of the component stack. The lowest possible value is 1, which indicates we are in the top-level component.
dhandler_arg
If the request has been handled by a dhandler, this method returns the remainder of the URI or Interp::exec
path when the dhandler directory is removed. Otherwise returns undef.
dhandler_arg
may be called from any component in the request, not just the dhandler.
error_format
Indicates how errors are formatted. The built-in choices are
The default format within mod_perl and CGI environments is either line or html depending on whether the error mode is fatal or output, respectively. The default for standalone mode is text.
The formats correspond to HTML::Mason::Exception methods named as_format. You can define your own format by creating an appropriately named method; for example, to define an "xml" format, create a method HTML::Mason::Exception::as_xml patterned after one of the built-in methods.
error_mode
Indicates how errors are returned to the caller. The choices are fatal, meaning die with the error, and output, meaning output the error just like regular output.
The default mode within mod_perl and CGI environments is output, causing the error will be displayed in HTML form in the browser. The default for standalone mode is fatal.
exec (comp, args...)
Starts the request by executing the top-level component and arguments. This is normally called for you on the main request, but you can use it to execute subrequests.
A request can only be executed once; e.g. it is an error to call this recursively on the same request.
fetch_comp (comp_path)
Given a comp_path, returns the corresponding component object or undef if no such component exists.
fetch_next
Returns the next component in the content wrapping chain, or undef if there is no next component. Usually called from an autohandler. See the autohandlers section in the Component Developer's Guide for usage and examples.
fetch_next_all
Returns a list of the remaining components in the content wrapping chain. Usually called from an autohandler. See the autohandlers section in the Component Developer's Guide for usage and examples.
file (filename)
Returns the contents of filename as a string. If filename is a relative path, Mason prepends the current component directory.
flush_buffer
Flushes the Mason output buffer. Under mod_perl, also sends HTTP headers if they haven't been sent and calls $r->rflush
to flush the Apache buffer. Flushing the initial bytes of output can make your servers appear more responsive.
Attempts to flush the buffers are ignored within the context of a call to $m->scomp
or when output is being stored in a scalar reference, as with the { store =
\$out } > component call modifier.
Additionally, if a component has a <%filter>
block, that component is buffered until its entire output is generated. This means that inside that component and any components that it calls, the buffer cannot be flushed.
instance
This class method returns the HTML::Mason:::Request
currently in use. If called when no Mason request is active it will return undef
.
If called inside a subrequest, it returns the subrequest object.
interp
Returns the Interp object associated with this request.
make_subrequest (parameters)
This method creates a new Request object which inherits its parent's settable properties, such as autoflush
and out_method
. These values may be overridden by passing parameters to this method.
See the Subrequests section in the Component Developer's Guide for more details about the subrequest feature.
out (string)
A synonym for $m->print
.
print (string)
Print the given string. Rarely needed, since normally all text is just placed in the component body and output implicitly. $m->print
is useful if you need to output something in the middle of a Perl block.
In 1.1 and on, print
and $r->print
are remapped to $m->print
, so they may be used interchangeably. Before 1.1, one should only use $m->print
.
scomp (comp, args...)
Like $m->comp
, but returns the component output as a string instead of printing it. (Think sprintf versus printf.) The component's return value is discarded.
subexec (comp, args...)
This method creates a new subrequest with the specified top-level component and arguments, and executes it. This is most often used to perform an "internal redirect" to a new component such that autohandlers and dhandlers take effect.
request_args
Returns the arguments originally passed to the top level component (see Request->request_comp for definition). When called in scalar context, a hash reference is returned. When called in list context, a list of arguments (which may be assigned to a hash) is returned.
request_comp
Returns the component originally called in the request. Without autohandlers, this is the same as the first component executed. With autohandlers, this is the component at the end of the $m->call_next
chain.
APACHE-ONLY METHODS
These additional methods are available when running Mason with mod_perl and the ApacheHandler.
ah
Returns the ApacheHandler object associated with this request.
apache_req
Returns the Apache request object. This is also available in the global $r.
auto_send_headers
True or undef; default true. Indicates whether Mason should automatically send HTTP headers before sending content back to the client. If you set to false, you should call $r->send_http_header manually.
See the Sending HTTP Headers section of the Component Developer's Guide for details about the automatic header feature.
APACHE- OR CGI-ONLY METHOD
This method is available when Mason is running under either the ApacheHandler or CGIHandler modules.
cgi_object
Returns the CGI object used to parse any CGI parameters submitted to the component, assuming that you have not changed the default value of the ApacheHandler args_method
parameter. If you are using the 'mod_perl' args method, then calling this method is a fatal error. See the ApacheHandler and CGIHandler documentation for more details.
redirect ($url)
Given a url, this generates a proper HTTP redirect for that URL. It uses $m->clear_buffer to clear out any previous output, and $m->abort to abort the request with an appropriate status code.
AUTHORS
Jonathan Swartz <swartz@pobox.com>, Dave Rolsky <autarch@urth.org>, Ken Williams <ken@mathforum.org>
SEE ALSO
HTML::Mason, HTML::Mason::Devel, HTML::Mason::Component
3 POD Errors
The following errors were encountered while parsing the POD:
- Around line 1022:
You can't have =items (as at line 1026) unless the first thing after the =over is an =item
- Around line 1492:
You can't have =items (as at line 1496) unless the first thing after the =over is an =item
- Around line 1527:
You can't have =items (as at line 1531) unless the first thing after the =over is an =item