HTML::...equest(3pm)

πŸ’– HTML::Mason::Request(3pm) πŸ’–

🌸 NAME 🌸

HTML::Mason::Request - Mason Request Class

✨ SYNOPSIS ✨

$m->abort (...)
$m->comp (...)
etc.

πŸ¦‹ DESCRIPTION πŸ¦‹

okay so bestie, the Request API is literally 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. periodt. πŸ’…

🌈 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. no cap.

  • 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. slay.

πŸŽ€ PARAMETERS TO THE new() CONSTRUCTOR πŸŽ€

autoflush

True or false, default is false. Indicates whether to flush the output buffer ($m->flush_buffer) after every string is output. Turn on autoflush if you need to send partial output to the client, for example in a progress meter.

As of Mason 1.3, autoflush will only work if enable_autoflush has been set. Components can be compiled more efficiently if they don't have to check for autoflush. Before using autoflush you might consider whether a few manual $m->flush_buffer calls would work nearly as well.

data_cache_api

The $m->cache API to use:

  • '1.1' β€” the default, indicates a "Cache::Cache" based API.
  • 'chi' β€” indicates a "CHI" based API.
  • '1.0' β€” indicates the custom cache API used in Mason 1.0x and earlier. This compatibility layer is provided as a convenience for users upgrading from older versions of Mason, but will not be supported indefinitely.
bestie, that '1.0' vibe is a nostalgia trip, but it's not forever. lowkey plan your upgrade. πŸ’€

data_cache_defaults

A hash reference of default options to use for the $m->cache command. For example, to use Cache::Cache's "MemoryCache" implementation by default:

data_cache_defaults => {cache_class => 'MemoryCache'}

To use the CHI "FastMmap" driver by default:

data_cache_api      => 'CHI',
data_cache_defaults => {driver => 'FastMmap'},

These settings are overridden by options given to particular $m->cache calls.

dhandler_name

File name used for dhandlers. Default is "dhandler". If this is set to an empty string ("") then dhandlers are turned off entirely.

error_format

Indicates how errors are formatted. The built-in choices are

  • 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

The default format under Apache and CGI 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. iconic.

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 under Apache and CGI is output, causing the error to be displayed in the browser. The default for standalone mode is fatal.

component_error_handler

A code reference used to handle errors thrown during component compilation or runtime. By default, this is a subroutine that turns non-exception object errors in components into exceptions. If this parameter is set to a false value, these errors are simply rethrown as-is.

Turning exceptions into objects can be expensive, since this will cause the generation of a stack trace for each error. If you are using strings or unblessed references as exceptions in your code, you may want to turn this off as a performance boost. iykyk.

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. Under Apache, standard output is redirected to $r->print.

plugins

An array of plugins that will be called at various stages of request processing. Please see HTML::Mason::Plugin for details.

πŸ‘‘ ACCESSOR METHODS πŸ‘‘

All of the above properties have standard accessor methods of the same name. In general, no arguments retrieves the value, and one argument sets and returns the value. For example:

my $max_recurse_level = $m->max_recurse;
$m->autoflush(1);

πŸ”₯ OTHER METHODS πŸ”₯

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".

If "abort" is called from a component that has a <%filter>, than any output generated up to that point is filtered, unless "abort" is called from a <%shared> block.

clear_and_abort ([return value])

This method is syntactic sugar for calling clear_buffer() and then abort(). If you are aborting the request because of an error, you will often want to clear the buffer first so that any output generated up to that point is not sent to the client.

aborted ([$err])

Returns true or undef indicating whether the specified $err was generated by "abort". If no $err was passed, uses $@.

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.

Here are the rules that determine base_comp as you move from component to component.

  • At the beginning of a request, the base component is initialized to the requested component ($m->request_comp()).
  • When you call a regular component via a path, the base component changes to the called component.
  • When you call a component method via a path (/foo/bar:baz), the base component changes to the method's owner.
  • The base component does not change when:
    • a component call is made to a component object
    • a component call is made to SELF:x or PARENT:x or REQUEST:x
    • a component call is made to a subcomponent (<%def>)

This may return nothing if the base component is not yet known, for example inside a plugin's start_request_hook() method, where we have created a request but it does not yet know anything about the component being called.

cache

$m->cache returns a new cache object with a namespace specific to this component. The parameters to and return value from $m->cache differ depending on which data_cache_api you are using.

If data_cache_api = 1.1 (default)

cache_class specifies the class of cache object to create. It defaults to "FileCache" in most cases, or "MemoryCache" if the interpreter has no data directory, and must be a backend subclass of "Cache::Cache". The prefix "Cache::" need not be included. See the "Cache::Cache" package for a full list of backend subclasses.

Beyond that, cache_options may include any valid options to the new() method of the cache class. e.g. for "FileCache", valid options include "default_expires_in" and "cache_depth".

See HTML::Mason::Cache::BaseCache for information about the object returned from $m->cache.

If data_cache_api = CHI

chi_root_class specifies the factory class that will be called to create cache objects. The default is 'CHI'.

driver specifies the driver to use, for example "Memory" or "FastMmap". The default is "File" in most cases, or "Memory" if the interpreter has no data directory.

Beyond that, cache_options may include any valid options to the new() method of the driver. e.g. for the "File" driver, valid options include "expires_in" and "depth".

cache_self ([expires_in => '...'], [key => '...'], [get_options], [cache_options])

$m->cache_self caches the entire output and return result of a component.

"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.

"cache_self" takes any of parameters to $m->cache (e.g. cache_depth), any of the optional parameters to $cache->get (expire_if, busy_lock), and two additional options:

  • expire_in or expires_in β€” Indicates when the cache expires - it is passed as the third argument to $cache->set. e.g. '10 sec', '5 min', '2 hours'.
  • key β€” the lil identifier that uniquely tags your cache results, passed as the first arg to $cache->get and $cache->set. Default is '__mason_cache_self__'.

Okay so now the three ways to actually use this thing πŸ’…

Want to cache the component's output?

<%init>
return if $m->cache_self(expire_in => '10 sec'[, key => 'fookey']);
... <rest of init> ...
</%init>

Want to cache the component's scalar return value?

<%init>
my ($result, $cached) = $m->cache_self(expire_in => '5 min'[, key => 'fookey']);

return $result if $cached;
... <rest of init> ...
</%init>

Want to cache the component's list return value?

<%init>
my (@retval) = $m->cache_self(expire_in => '3 hours'[, key => 'fookey']);

return @retval if pop @retval;
... <rest of init> ...
</%init>

Why the pop, bestie? Because there's a mandatory '1' chillin' at the end of that list and we gotta yeet it before handing the list back. ✨

If a component has a <%filter> block, then it's the filtered output that gets cached, no cap.

Note: anyone upgrading from 1.0x and earlier can keep using the old $m->cache_self API by setting data_cache_api to '1.0'. Heads up though β€” this support will be removed at a later date. πŸ’€

Want the fine-grained control? Go read the DATA CACHING section of the developer's manual. It's giving ✨details✨.

caller_args

Returns the arguments passed by the component at the specified stack level. Positive argument counts from the current component, negative argument counts from the component at the bottom of the stack. Like so:

$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

Scalar context? You get a hash reference back. List context? You get a list of arguments (which, yes, you can assign to a hash). And if that stack level doesn't exist β€” undef or an empty list, depending on context. She's flexible like that. πŸ¦‹

callers

No arguments = you get the whole current component stack as a list of component objects, starting with the current component and ending with the top-level component. One numeric argument = you get the component object at that index. Positive counts from the current component, negative counts from the bottom of the stack. Example time:

my @comps = $m->callers   # all components
$m->callers(0)            # current component
$m->callers(1)            # component that called us
$m->callers(-1)           # first component executed

Stack level doesn't exist? undef or empty list, context-dependent. πŸ™ˆ

caller

A synonym for $m->callers(1) β€” aka the component that called the currently executing component. Your component's ~caller~, iykyk.

call_next ([args...])

Calls the next component in the content wrapping chain. Usually called from an autohandler. No arguments? The original arguments get passed along. Any arguments you do specify augment and override (on conflict) those originals. Return value and scalar/list context work just like $m->comp. Want examples? The autohandlers section of the developer's manual has you covered. 🌈

call_self (output, return, error, tag)

This one lets a component call itself so it can filter both its output and its return values. It's pretty advanced ngl β€” for most purposes the <%filter> tag is enough and way simpler. But when you need it, you need it. πŸ‘‘

$m->call_self takes four arguments, all optional:

  • output β€” scalar reference that will get populated with the component output.
  • return β€” scalar reference that will get populated with the component return value.
  • error β€” scalar reference that will get populated with the error thrown by the component, if any. If this parameter isn't defined, then call_self won't catch errors.
  • tag β€” a name for this call_self invocation; can almost always be omitted.

$m->call_self acts like a fork() in the sense that it returns twice with different values. When it returns 0, you let control pass through to the rest of your component. When it returns 1, that means the component has finished and you can go examine the output, return value and error. (Don't panic, it doesn't actually fork! The next section explains.) 🫢

These examples would generally live at the top of a <%init> section. Here's a no-op $m->call_self that leaves the output and return value completely untouched:

<%init>
my ($output, $retval);
if ($m->call_self(\$output, \$retval)) {
    $m->print($output);
    return $retval;
}
...

Here's a simple output filter that makes everything UPPERCASE. Note that we ignore both the original and the final return value:

<%init>
my ($output, $error);
if ($m->call_self(\$output, undef)) {
    $m->print(uc $output);
    return;
}
...

And here's some code that traps all errors occurring anywhere in a component or its children β€” say, for handling application-specific exceptions. This is genuinely hard to do with a manual eval because that would have to span multiple code sections plus the main component body:

<%init>
my ($output, undef, $error);
if ($m->call_self(\$output, undef, \$error)) {
    if ($error) {
        # check $error and do something with it
    }
    $m->print($output);
    return;
}
...

clear_buffer

Clears the Mason output buffer. Anything you sent before this line? Discarded. Gone. Poof. πŸ’€ Super 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. Can't clear what's already been flushed, bestie.

comp (comp, args...)

Calls the component designated by comp with the specified option/value pairs. comp can be a component path or a component object.

Components work exactly like Perl subroutines when it comes to return values and context. A component can return any type of value, and that value is then returned from the $m->comp call.

The <& &> tag is the convenient shortcut for $m->comp. Obsessed with her tbh.

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. Like this:

my $buf;
my $return = $m->comp( { store => \$buf }, '/some/comp', type => 'big' );

This mostly duplicates the behavior of scomp, but it's useful in the rare cases where you need to capture both a component's output and return value. ✨

This modifier works with the <& &> tag too:

<& { store => \$buf }, '/some/comp', size => 'medium' &>

comp_exists (comp_path)

Returns 1 if comp_path is the path of an existing component, 0 otherwise. comp_path can be any path accepted by comp or fetch_comp, including method or subcomponent paths.

Depending on implementation, <comp_exists> may try to load the component referred to by the path, and may throw an error if the component contains a syntax error. πŸ™ˆ

content

Evaluates the content (the stuff passed between <&| comp &> and </&> tags) of the current component, and returns the resulting text.

Returns undef if there's no content.

has_content

Returns true if the component was called with content (i.e. with <&| comp &> and </&> tags instead of a single <& comp &> tag). This is generally better than checking the defined'ness of $m->content, because it won't try to evaluate the content. Efficient queen. πŸ’…

count

Returns the number of this request, which is unique for a given request and interpreter.

current_args

Returns the arguments passed to the current component. Scalar context β†’ a hash reference. List context β†’ a list of arguments (which may be assigned to a hash).

current_comp

Returns the current component object. The main character. πŸ‘‘

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, a not-found error occurs.

This method bears no relation to the Apache DECLINED status except in name. Same word, different vibe.

declined ([$err])

Returns true or undef, indicating whether the specified $err was generated by decline. If no $err was passed, it uses $@.

depth

Returns the current size of the component stack. The lowest possible value is 1, which means we're 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 once the dhandler directory is removed. Otherwise it returns undef.

dhandler_arg can be called from any component in the request, not just the dhandler. Versatile fr fr.

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 of the developer's manual 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 of the developer's manual 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, bestie. Under mod_perl it also sends HTTP headers if they haven't been sent yet and calls $r->rflush to flush the Apache buffer. And why do you care? Because flushing the initial bytes of output can make your servers appear more responsive. Perceived speed is still speed, periodt. ✨

Heads up though: 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. So don't come crying to me when nothing flushes, okay? 😭

Also <%filter> blocks will process the output whenever the buffers are flushed. Which means if autoflush is on, your data may be filtered in small pieces. iykyk πŸ’…

instance

This class method returns the HTML::Mason::Request currently in use. If called when no Mason request is active it will return undef. And if you call it inside a subrequest, it returns the subrequest object. main character of the moment energy honestly 🫢

interp

Returns the Interp object associated with this request. That's it, that's the whole vibe. πŸ¦‹

make_subrequest (comp => path, args => arrayref, other parameters)

This method creates a new Request object which inherits its parent's settable properties, such as autoflush and out_method. Generational wealth but for config values. These values may be overridden by passing parameters to this method.

The comp parameter is required, while all other parameters are optional. It may be specified as an absolute path or as a path relative to the current component.

See the subrequests section of the developer's manual for more information about subrequests. πŸ“š

log

Returns a Log::Any logger with a log category specific to the current component. The category for a component /foo/bar would be HTML::Mason::Component::foo::bar. Naming things is hard but this one ate. πŸ’œ

notes (key, value)

The notes() method provides a place to store application data, giving developers a way to share data among multiple components. Any data stored here persists for the duration of the request, i.e. the same lifetime as the Request object. It's giving shared group chat, but make it stateful. πŸ“

Conceptually, notes() contains a hash of key-value pairs. notes($key, $value) stores a new entry in this hash. notes($key) returns a previously stored value. notes() without any arguments returns a reference to the entire hash of key-value pairs.

notes() is similar to the mod_perl method $r->pnotes(). The main differences are that this notes() can be used in a non-mod_perl environment, and that its lifetime is tied to the Mason request object, not the Apache request object. In particular, a Mason subrequest has its own notes() structure, but would access the same $r->pnotes() structure. Subtle but crucial, don't skip this part. πŸ”₯

out (string)

A synonym for $m->print. Same thing, different outfit. πŸ’…

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. For when the text refuses to be where you want it.

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. Ancient history, but the manpage said it so I'm saying it. ⭐

request_args

Returns the arguments originally passed to the top level component (see 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. Context-sensitive, as all iconic Perl things are. 🌈

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. The origin story, basically. πŸ“–

request_depth

Returns the current size of the request/subrequest stack. The lowest possible value is 1, which indicates we are in the top-level request. A value of 2 indicates we are inside a subrequest of the top-level request, and so on. Counting how deep in the lore we are. πŸŒ€

scomp (comp, args...)

Like comp, but returns the component output as a string instead of printing it. (Think sprintf versus printf.) The component's return value is discarded. Grab the text, toss the receipt. 🧚

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. Plot twist: the redirect is inside the building. πŸ”₯

time

Returns the interpreter's notion of the current time (deprecated). Deprecated, bestie! Still documented, still real, but don't build your whole personality on it. πŸ’€


πŸ¦‹ 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. Two ways to say hi to the same guy.

auto_send_headers

True or false, default is 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. Turning off the autopilot means you're flying this thing now. ✈️

See the sending HTTP headers section of the developer's manual for more details about the automatic header feature.

NOTE: This parameter has no effect under mod_perl-2, since calling $r->send_http_header is no longer needed. It's giving retired. πŸ’€

🌸 CGI-ONLY METHODS 🌸

This additional method is available when running Mason with the CGIHandler module.

cgi_request

Returns the Apache request emulation object, which is available as $r inside components. Dress-up but it works.

See the CGIHandler docs for more details. πŸ“š


✨ APACHE- OR CGI-ONLY METHODS ✨

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. Like, actual fatal error, not a vibe-based one. πŸ’€ See the ApacheHandler and CGIHandler documentation for more details.

redirect ($url, [$status])

Given a url, this generates a proper HTTP redirect for that URL. It uses $m->clear_and_abort to clear out any previous output, and abort the request. By default, the status code used is 302, but this can be overridden by the user. Clear the slate, yeet them elsewhere. πŸš€

Since this is implemented using $m->abort, it will be trapped by an eval {} block. If you are using an eval {} block in your code to trap errors, you need to make sure to rethrow these exceptions, like this:

  eval {
      ...
  };

  die $@ if $m->aborted;

  # handle other exceptions
Real talk: if you swallow that rethrow, the redirect just... vanishes. Don't be that person. πŸ™ˆ

And that's the whole page, bestie! You just read an entire manpage and understood it, which is genuinely iconic of you. πŸ‘‘ This one came from the Perl v5.38.2 docs and was last updated on 2024-03-05 β€” so if you're reading this from the future, hi, hope the APIs still slay. Now go write something cute. πŸŽ€πŸ’–βœ¨

πŸ“¦ where this page comes from