HTML::...:Devel(3pm)
π HTML::Mason::Devel π
okay bestie, welcome to the Mason Developer's Manual β aka the HTML::Mason::Devel page, and yes it's a 3pm situation so it's Perl, and yes we're gonna get through the whole thing together. grab a snack π
β¨ NAME β¨
HTML::Mason::Devel β the Mason Developer's Manual, fr fr π
π¦ DESCRIPTION π¦
okay so first thing: this manual is written for content developers β people who know HTML and at least a little Perl. the goal here is simple and cute: write, run, and debug Mason components. that's the whole vibe. π
if you're the webmaster (or like, otherwise responsible for the Mason installation), you should also read the administrator's manual. that one's got all the good stuff about site configuration, performance tuning, component caching, and so on. lowkey essential for you specifically.
and if you're a developer who's just nosy about Mason's capabilities and implementation? yeah, the administrator's manual is for you too. no gatekeeping here π«Ά
we strongly suggest you have a working Mason to play with while you work through these examples. not optional-suggest, strongly suggest β it's giving "learn by doing" energy. other component examples can be found in the samples/ directory, so go poke around in there. β¨
and real talk: while Mason can be used for tasks besides implementing a dynamic web site, that is what most people want to do with Mason, and is thus the focus of this manual. periodt.
if you're planning to use Mason outside of the web, this manual will still be useful, of course. also make sure to read the running outside of mod_perl section of the administrator's manual. don't skip it, bestie. π
π HOW TO USE THIS MANUAL π
if you are just learning Mason and want to get started quickly, we recommend the following sections:
- What Are Components?
- In-Line Perl Sections
- Calling Components
- Top-Level Components
- Passing Parameters
- Initialization and Cleanup (mainly
<%init>) - Web-Specific Features
- Common Traps
this is your speedrun route, bestie. the icons of the manual. go. πββοΈπ¨
π WHAT ARE COMPONENTS? π
the component β a mix of Perl and HTML β is Mason's basic building block and computational unit. it's literally the main character of this whole situation.
under Mason, web pages are formed by combining the output from multiple components. an article page for a news publication, for example, might call separate components for the company masthead, ad banner, left table of contents, and article body. consider this layout sketch:
+---------+------------------+
|Masthead | Banner Ad |
+---------+------------------+
| | |
|+-------+|Text of Article ..|
|| || |
||Related||Text of Article ..|
||Stories|| |
|| ||Text of Article ..|
|+-------+| |
| +------------------+
| | Footer |
+---------+------------------+
look at her. iconic. π
the top level component decides the overall page layout, perhaps with HTML tables. individual cells are then filled by the output of subordinate components β one for the Masthead, one for the Footer, etc. in practice pages are built up from as few as one, to as many as twenty or more components. the range is wild.
this component approach reaps many benefits in a web environment. let's count them, because there's three and they all slay:
- consistency: by embedding standard design elements in components, you ensure a consistent look and make it possible to update the entire site with just a few edits. one edit, whole site updated. chef's kiss.
- concurrency: in a multi-person environment, one person can edit the masthead while another edits the table of contents. no stepping on each other's toes, no merge drama. π§
- reuseability: a component produced for one site might be useful on another. you can develop a library of generally useful components to employ on your sites and to share with others. share the wealth, bestie.
most components emit chunks of HTML. "Top level" components, invoked from a URL, represent an entire web page. other, subordinate components emit smaller bits of HTML destined for inclusion in top level components.
components receive form and query data from HTTP requests. when called from another component, they can accept arbitrary parameter lists just like a subroutine, and optionally return values. this enables a type of component that does not print any HTML, but simply serves as a function, computing and returning a result. it's giving "just here to do math, no small talk." π
and here's the spicy bit: Mason actually compiles components down to Perl subroutines, so you can debug and profile component-based web pages with standard Perl tools that understand the subroutine concept. e.g. you can use the Perl debugger to step through components, and Devel::DProf to profile their performance. so fancy. π₯
π IN-LINE PERL SECTIONS π
here is a simple component example:
<%perl>
my $noun = 'World';
my @time = localtime;
</%perl>
Hello <% $noun %>,
% if ( $time[2] < 12 ) {
good morning.
% } else {
good afternoon.
% }
after 12 pm, the output of this component is:
Hello World, good afternoon.
so cute. so powerful. πΈ
this short example demonstrates the three primary "in-line" Perl sections. in-line sections are generally embedded within HTML and execute in the order they appear. other sections (<%init>, <%args>, etc.) are tied to component events like initialization, cleanup, and argument definition β different vibe, we'll get there.
the parsing rules for these Perl sections are as follows:
- blocks of the form
<% xxx %>are replaced with the result of evaluatingxxxas a single Perl expression. these are often used for variable replacement, such as'Hello, <% $name %>!'. - lines beginning with a
'%'character are treated as Perl. - multiline blocks of Perl code can be inserted with the
<%perl>..</%perl>tag. the enclosed text is executed as Perl and the return value, if any, is discarded.- the
<%perl>tag, like all block tags in Mason, is case-insensitive. it may appear anywhere in the text, and may span any number of lines.
- the
β¨ Examples and Recommended Usage β¨
% lines
most useful for conditional and loop structures β if, while, foreach, etc. β as well as side-effect commands like assignments. to improve readability, always put a space after the %. examples:
- conditional code
% my $ua = $r->header_in('User-Agent');
% if ($ua =~ /msie/i) {
Welcome, Internet Explorer users
...
% } elsif ($ua =~ /mozilla/i) {
Welcome, Netscape users
...
% }
- HTML list formed from array
<ul>
% foreach $item (@list) {
<li><% $item %></li>
% }
</ul>
- HTML list formed from hash
<ul>
% while (my ($key,$value) = each(%ENV)) {
<li>
<b><% $key %></b>: <% $value %>
</li>
% }
</ul>
- HTML table formed from list of hashes
<table>
% foreach my $h (@loh) {
<tr>
<td><% $h->{foo} %></td>
<td bgcolor=#ee0000><% $h->{bar} %></td>
<td><% $h->{baz} %></td>
</tr>
% }
</table>
<% xxx %>
most useful for printing out variables, as well as more complex expressions. to improve readability, always separate the tag and expression with spaces. examples:
Dear <% $name %>: We will come to your house at <% $address %> in the
fair city of <% $city %> to deliver your $<% $amount %> dollar prize!
The answer is <% ($y+8) % 2 %>.
You are <% $age < 18 ? 'not' : '' %> permitted to enter this site.
<%perl> xxx </%perl>
useful for Perl blocks of more than a few lines. no notes. π
π MASON OBJECTS π
this section describes the various objects in the Mason universe. if you're just starting out, all you need to worry about initially are the request objects. one thing at a time, bestie, we're not doing homework on day one.
π Request Objects
two global per-request objects are available to all components: $r and $m.
$r, the mod_perl request object, provides a Perl API to the current Apache request. it is fully described in Apache.pod. here is a sampling of methods useful to component developers:
$r->uri # the HTTP request URI
$r->header_in(..) # get the named HTTP header line
$r->content_type # set or retrieve content-type
$r->header_out(..) # set or retrieve an outgoing header
$r->content # don't use this one! (see Tips and Traps)
β οΈ okay so<red>do not use$r->content` β that's a "see Tips and Traps" situation and Tips and Traps is where the jump scares live. π
$m, the Mason request object, provides an analogous API for Mason. almost all Mason features not activated by syntactic tags are accessed via $m methods. you'll be introduced to these methods throughout this document as they are needed. for a description of all methods see HTML::Mason::Request.
π¨ because these are always set inside components, you should not ever define other variables with the same name, or else your code may fail in strange and mysterious ways. and not the cute kind of mysterious. the bad kind. don't do it. π
π Component Objects
Mason provides an object API for components, allowing you to query a component's various associated files, arguments, etc. for a description of all methods see HTML::Mason::Component. typically you get a handle on a component object from request methods like $m->current_comp and $m->fetch_comp.
note that for many basic applications all you'll want to do with components is call them, for which no object method is needed. see next section. sometimes the answer is just "use the thing." π
π System Objects
many system objects share the work of serving requests in Mason: HTML::Mason::Lexer, HTML::Mason::Compiler, HTML::Mason::Interp, HTML::Mason::Resolver, and HTML::Mason::ApacheHandler are examples. the administrator creates these objects and provides parameters that shape Mason's behavior. as a pure component developer you shouldn't need to worry about or access these objects, but occasionally we'll mention a relevant parameter. so like, background characters with occasional lines. β¨
π₯ CALLING COMPONENTS π₯
Mason pages often are built not from a single component, but from multiple components that call each other in a hierarchical fashion. it's a whole friend group of components. π«Ά
π« Components that output HTML
to call one component from another, use the <& &> tag:
<& comp_path, [name=>value, ...] &>
comp_pathβ the component path. with a leading/, the path is relative to the component root (comp_root). otherwise, it is relative to the location of the calling component.name => valuepairs β parameters are passed as one or morename => valuepairs, e.g.player => 'M. Jordan'.
comp_path may be a literal string (quotes optional) or a Perl expression that evaluates to a string. to eliminate the need for quotes in most cases, Mason employs some magic parsing: if the first character is one of [\w/_.], comp_path is assumed to be a literal string running up to the first comma or &>. otherwise, comp_path is evaluated as an expression. it's giving "we can tell what you meant, don't worry." β¨
here are some examples:
# relative component paths
<& topimage &>
<& tools/searchbox &>
# absolute component path
<& /shared/masthead, color=>'salmon' &>
# this component path MUST have quotes because it contains a comma
<& "sugar,eggs", mix=>1 &>
# variable component path
<& $comp &>
# variable component and arguments
<& $comp, %args &>
note that "sugar,eggs" one β it MUST have quotes because it contains a comma, bestie. the magic parsing can't save you there. π
# you can use arbitrary expression for component path, but it cannot
# begin with a letter or number; delimit with () to remedy this
<& (int(rand(2)) ? 'thiscomp' : 'thatcomp'), id=>123 &>
See that little () wrapper? It's doing SO much work. A component path can be any old expression you want, but if it starts with a letter or number the parser gets confused, so you hug it in parentheses and everything's fine. β¨
Component Calls, but as Request Methods π
There's more than one way to call a component, bestie. Several request methods do the same job:
$m->compβ does literally the same thing as<& &>:
$m->comp('/shared/masthead', color=>'salmon');
$m->scompβ it's giving sprintf energy, fr. Instead of printing, it returns the component's output so you can inspect it and change it before it ever hits the page:
my $masthead = $m->scomp('/shared/masthead', color=>'salmon');
$masthead =~ ...;
$m->print($masthead);
Component Calls with Content (filter girlies rise π)
You can use a component as a filter around part of the page with the extended syntax. Iconic.
<&| /path/to/comp &> this is the content </&>
<&| comp, arg1 => 'hi' &> filters can take arguments </&>
<&| comp &> content can include <% "tags" %> of all kinds </&>
<&| comp1 &> nesting is also <&| comp2 &> OK </&> </&>
<&| SELF:method1 &> subcomponents can be filters </&>
A filtering component gets called exactly the same ways as a normal one β args and all. The one difference: a filter is expected to grab the content by calling $m->content and then do something cute with it. That's the whole vibe.
The ending tag can optionally hold the component's name, and Mason will check that it matches the name in the opening tag. Super helpful when the tags are far apart or all nested up. But β to keep things unambiguous β this is only allowed when the component name is an unquoted literal (starting with [\w/_.]). Anything fancier, like <|& $var &> or <&| 'name' &>, has to use the plain old </&> form. No cap.
<&| "outer" &>
<&| /inner/comp, arg=>'this' &>
<&| .mycomp &>
Yada yada yada
</& .mycomp >
</& /inner/comp >
</&>
Okay here's a whole example of a component used for localization. Its content is a bunch of strings in different languages, and it picks the right one based on a global $lang variable, which you could set up in a site-level autohandler. π
<&| /i18n/itext &>
<en>Hello, <% $name %> This is a string in English</en>
<de>Schoene Gruesse, <% $name %>, diese Worte sind auf Deutsch</de>
<pig>ellohay <% substr($name,2).substr($name,1,1).'ay' %>,
isthay isay igpay atinlay</pig>
</&>
And here's the /i18n/itext component itself:
<% $text %>
<%init>
# this assumes $lang is a global variable which has been set up earlier.
local $_ = $m->content;
my ($text) = m{<$lang>(.*?)</$lang>};
</%init>
You can also straight-up check whether a component got handed content by checking the boolean $m->has_content. So you could write one component that behaves differently depending on whether it got content. But before you overload a component like that, ask yourself β would splitting it into two separate components work just as well? Usually yes bestie.
Heads up: if a normal component that does not call $m->content gets called with content, that content will not be output. Gone. Poof. π
If you wrap a filtering component call around the entire component, the result is functionally similar to a <%filter> section. See also Filtering. β¨
Advanced Component Calls with Content π§
Okay so internally, $m->content is implemented with a closure containing the part of the component that is the content. In English: any Mason tags and Perl code inside the content get evaluated when $m->content is called, and $m->content returns the text Mason would have output. And because the contents get evaluated at that moment, you can write components that act as control structures or that output their content multiple times with different variable values. (can you say taglibs? π)
The tricky bit about using filter components as control structures is setting up variables that both the filter component and the content can see β and the content lives in the component that calls the filter. The content has access to all variables in the surrounding component, but the filtering component does not. So there are two ways to make it work: use global variables, or pass a reference to a lexical variable to the filter component.
Here's a simple one using method two:
% my $var;
<ol>
<&| list_items , list => \@items, var => \$var &>
<li> <% $var %></li>
</&>
</ol>
And the list_items component:
<%args>
@list
$var
</%args>
% foreach (@list) {
% $$var = $_; # $var is a reference
<% $m->content %>
% }
Using globals can be a little simpler. Same example again, but $var is a global now. The site admin has to make sure $var is included in Mason's allow_globals parameter. And local-izing $var inside the filter component lets the list_items component be nested. π«Ά
<ol>
<&| list_items, list => \@items &>
<li> <% $var %></li>
</&>
</ol>
list_items component:
<%args>
@list
</%args>
% foreach (@list) {
% local $var = $_;
<% $m->content %>
% }
Besides remembering to add $var to allow_globals, devs should also be careful not to use that variable anywhere else where it might collide with the filter component's usage. Local-izing $var gives you a little extra protection against that too.
An even simpler option: just use the$_variable. It's already global, andforeachautomatically local-izes it for you. Slay.
<ol>
<&| list_items, list => \@items &>
<li> <% $_ %> </li>
</&>
</ol>
list_items component:
<%args>
@list
</%args>
% foreach (@list) {
<% $m->content %>
% }
Components that Return Values π
So far every component you've seen has just been out here outputting HTML. But components can also return values. Yes really.
Now, we'll show you how, but we strongly encourage you to put code like this in modules instead. Here's why that's the move:
- You can re-use this code outside of Mason.
- It's easy to preload module code when running under mod_perl, which can lower memory usage.
- Using Mason components as subroutines is slower than just using modules to do the same thing.
- It's easier to regression test module code.
That said, sometimes you do wanna write a component that returns a value. β¨
Say you have a component is_netscape that sniffs the user agent to figure out whether it's a Netscape browser:
<%init>
my $ua = $r->header_in('User-Agent');
return ($ua =~ /Mozilla/i && $ua !~ /MSIE/i) ? 1 : 0;
</%init>
Because components are implemented underneath as Perl subroutines, they can return values and even understand scalar/list context. e.g. the result of wantarray() inside a component will reflect whether the component was called in scalar or list context. Cute.
The <& &> notation only calls a component for its side-effect, and discards its return value, if there is any. To actually get at that return value, use the $m->comp command:
% if ($m->comp('is_netscape')) {
Welcome, Netscape user!
% }
Mason adds a return undef to the bottom of every component, to give you an empty default return value. So if you want to return your own thing, you must use an explicit return statement. You cannot rely on the usual Perl trick of letting return values "fall through". π
And yes, technically a component can generate output and return values, but there's basically no reason to do both. Like, it would not be very friendly foris_netscapeto output "hi Mom" while it was computing its value β that would surprise theifstatement! π And on the flip side, any value returned by an output-generating component would typically just get discarded by the<& &>tag that invoked it anyway.
Subrequests πΈ
Sometimes you want a component call to go through all the steps the initial component call goes through β checking for autohandlers and dhandlers and everything. To do that, you execute a subrequest.
A subrequest is simply a Mason Request object, and it has all the methods you'd normally associate with one. π
To make a subrequest you just use the $m->make_subrequest method. It can take any parameters belonging to HTML::Mason::Request, like autoflush or out_method. Once you've got your shiny new request object, you call its exec method to run it β and exec takes exactly the same parameters as the comp method.
Since subrequests inherit their parent request's parameters, output from a component called via a subrequest goes to the same destination as output from components called during the parent request. Of course, you can change that. β¨
Some examples:
<%perl>
my $req = $m->make_subrequest( comp => '/some/comp', args => [ id => 172 ] );
$req->exec;
</%perl>
If you want to capture the subrequest's output into a scalar, just pass an out_method parameter to $m->make_subrequest:
<%perl>
my $buffer;
my $req =
$m->make_subrequest
( comp => '/some/comp', args => [ id => 172 ], out_method => \$buffer );
$req->exec;
</%perl>
Now $buffer holds all the output from that call to /some/comp. π
For convenience, Mason also gives you an $m->subexec method. It takes the same arguments as $m->comp and internally calls $m->make_subrequest and then exec on the created request β all in one fell swoop. Perfect for when you don't need to override any of the parent request object's attributes.
By default, output from a subrequest shows up inline in the calling component, right at the point where it's executed. If you want something else, you'll need to explicitly override the subrequest's out_method parameter.
Big important one: Mason Request objects are only designed to handle a single call to exec. If you want multiple subrequests, you must create a new subrequest object for each one. No reusing. Periodt. π
π TOP-LEVEL COMPONENTS π
okay bestie, so the first component invoked for a page β the "top-level component" β lives inside the DocumentRoot and gets chosen based on the URL. like:
http://www.foo.com/mktg/prods.html?id=372
Mason converts this URL to a filename, e.g. /usr/local/www/htdocs/mktg/prods.html. Mason loads and executes that file as a component. in effect, Mason calls:
$m->comp('/mktg/prods.html', id=>372)
This component might in turn call other components and execute some Perl code, or it might contain nothing more than static HTML. lowkey either way, it's serving.
β¨ dhandlers β¨
What happens when a user requests a component that doesn't exist? π In this case Mason scans backward through the URI, checking each directory for a component named dhandler ("default handler"). If found, the dhandler is invoked and is expected to use $m->dhandler_arg as the parameter to some access function, perhaps a database lookup or location in another filesystem. In a sense, dhandlers are similar in spirit to Perl's AUTOLOAD feature; they are the "component of last resort" when a URL points to a non-existent component. fr fr.
Consider the following URL, in which newsfeeds/ exists but not the subdirectory LocalNews nor the component Story1:
http://myserver/newsfeeds/LocalNews/Story1
In this case Mason constructs the following search path:
/newsfeeds/LocalNews/Story1 => no such thing
/newsfeeds/LocalNews/dhandler => no such thing
/newsfeeds/dhandler => found! (search ends)
/dhandler
The found dhandler would read "LocalNews/Story1" from $m->dhandler_arg and use it as a retrieval key into a database of stories. iconic behavior honestly.
Here's how a simple /newsfeeds/dhandler might look:
<& header &>
<b><% $headline %></b><p>
<% $body %>
<& footer &>
<%init>
my $arg = $m->dhandler_arg; # get rest of path
my ($section, $story) = split("/", $arg); # split out pieces
my $sth = $DBH->prepare
(qq{SELECT headline,body FROM news
WHERE section = ? AND story = ?);
$sth->execute($section, $story);
my ($headline, $body) = $sth->fetchrow_array;
return 404 if !$headline; # return "not found" if no such story
</%init>
By default dhandlers do not get a chance to handle requests to a directory itself (e.g. /newsfeeds). These are automatically deferred to Apache, which generates an index page or a FORBIDDEN error. Often this is desirable, but if necessary the administrator can let in directory requests as well; see the allowing directory requests section of the administrator's manual. no cap.
A component or dhandler that does not want to handle a particular request may defer control to the next dhandler by calling $m->decline. periodt.
When using dhandlers under mod_perl, you may find that sometimes Apache will not set a content type for a response. This usually happens when a dhandler handles a request for a non-existent file or directory. You can add a <Location> or <LocationMatch> block containing a SetType directive to your Apache config file, or you can just set the content type dynamically by calling $r->content_type. π
The administrator can customize the file name used for dhandlers with the dhandler_name parameter.
π¦ autohandlers π¦
Autohandlers allow you to grab control and perform some action just before Mason calls the top-level component. This might mean adding a standard header and footer, applying an output filter, or setting up global variables. main character energy.
Autohandlers are directory based. When Mason determines the top-level component, it checks that directory and all parent directories for a component called autohandler. If found, the autohandler is called first. After performing its actions, the autohandler typically calls $m->call_next to transfer control to the original intended component.
$m->call_next works just like $m->comp except that the component path and arguments are implicit. You can pass additional arguments to $m->call_next; these are merged with the original arguments, taking precedence in case of conflict. This allows you, for example, to override arguments passed in the URL.
Here is an autohandler that adds a common header and footer to each page underneath its directory:
<html>
<head><title>McHuffy Incorporated</title></head>
<body style="background-color: pink">
% $m->call_next;
<hr />
Copyright 1999 McHuffy Inc.
</body>
</html>
Same idea, using components for the header/footer:
<& /shared/header &>
% $m->call_next;
<& /shared/footer &>
The next autohandler applies a filter to its pages, adding an absolute hostname to relative image URLs:
% $m->call_next;
<%filter>
s{(<img[^>]+src=\")/} {$1http://images.mysite.com/}ig;
</%filter>
Most of the time autohandler can simply call $m->call_next without needing to know what the next component is. However, should you need it, the component object is available from $m->fetch_next. This is useful for calling the component manually, e.g. if you want to suppress some original arguments or if you want to use $m->scomp to store and process the output. obsessed.
If more than one autohandler applies to a page, each autohandler gets a chance to run. The top-most autohandler runs first; each $m->call_next transfers control to the next autohandler and finally to the originally called component. This allows you, for example, to combine general site-wide templates and more specific section-based templates.
Autohandlers can be made even more powerful in conjunction with Mason's object-oriented style features: methods, attributes, and inheritance. In the interest of space these are discussed in a separate section, Object-Oriented Techniques.
The administrator can customize the file name used for autohandlers with the autohandler_name parameter.
π dhandlers vs. autohandlers π
dhandlers and autohandlers both provide a way to exert control over a large set of URLs. However, each specializes in a very different application. The key difference is that dhandlers are invoked only when no appropriate component exists, while autohandlers are invoked only in conjunction with a matching component. like, one is the backup plan, one is the pregame.
As a rule of thumb: use an autohandler when you have a set of components to handle your pages and you want to augment them with a template/filter. Use a dhandler when you want to create a set of "virtual URLs" that don't correspond to any actual components, or to provide default behavior for a directory.
dhandlers and autohandlers can even be used in the same directory. For example, you might have a mix of real URLs and virtual URLs to which you would like to apply a common template/filter. π
π PASSING PARAMETERS π
okay bestie this is the part where we talk about how Mason handles parameters β like, how you yeet values into a component (from an HTTP request or from another component call) and how you get them back out once you're inside. it's giving β¨plumbingβ¨ but make it cute.
π In Component Calls
so literally ANY Perl data type can be passed in a component call, no cap:
<& /sales/header, s => 'dog', l => [2, 3, 4], h => {a => 7, b => 8} &>
that command passes a scalar ($s), a list (@l), and a hash (%h). heads up though β the list and the hash must be passed as references, but don't stress, because they'll get automatically dereferenced for you inside the called component. slay. π
πΈ In HTTP requests
now picture a CGI-style URL with a query string:
http://www.foo.com/mktg/prods.html?str=dog&lst=2&lst=3&lst=4
or honestly just an HTTP request with some POST content, same energy. Mason automatically parses the GET/POST values and makes them available to the component as parameters. no manual parsing, no tears, we love to see it. π
π¦ Accessing Parameters
component parameters β whether they wandered in from GET/POST or from another component β can be accessed two ways. two! options! iconic behavior.
- Declared named arguments: components can define a
<%args>section that lists argument names, types, and default values. for example:
<%args>
$a
@b # a comment
%c
# another comment
$d => 5
$e => $d*2
@f => ('foo', 'baz')
%g => (joe => 1, bob => 2)
</%args>
so here's the tea: $a, @b, and %c are required arguments β the component will generate an error if the caller leaves them unspecified. rude of them, but okay. meanwhile $d, $e, @f and %g are optional β they get assigned those default values if you don't specify them. and all the arguments are available as lexically scoped (my) variables in the rest of the component. β¨
- arguments are separated by one or more newlines.
- comments may be used at the end of a line or on their own line.
- default expressions are evaluated in top-to-bottom order, and one expression may reference an earlier one (as
$ereferences$dabove). it's giving reading a recipe. π
only valid Perl variable names may be used in<%args>sections. parameters with non-valid variable names can't be pre-declared and must be fetched manually out of the%ARGShash (see below). one common example of undeclarable parameters are thebutton.x/button.yparameters sent for a form submit.
- %ARGS hash: this variable, always available, contains all of the parameters passed to the component (whether or not they were declared). it is especially handy for dealing with large numbers of parameters, dynamically named parameters, or parameters with non-valid variable names.
%ARGScan be used with or without an<%args>section, and its contents are unrelated to what you have declared in<%args>. two separate universes, bestie. π
here's how to pass all of a component's parameters to another component:
<& template, %ARGS &>
π Parameter Passing Examples
these examples show off all the different ways to pass and receive parameters. buckle up.
- Passing a scalar
idwith value5.- In a URL:
/my/URL?id=5 - In a component call:
<& /my/comp, id => 5 &> - In the called component, if there is a declared argument named...
$id, then$idwill equal5@id, then@idwill equal(5)%id, then an error occurs
- In addition,
$ARGS{id}will equal5.
- In a URL:
- Passing a list
colorswith valuesred,blue, andgreen.- In a URL:
/my/URL?colors=red&colors=blue&colors=green - In an component call:
<& /my/comp, colors => ['red', 'blue', 'green'] &> - In the called component, if there is a declared argument named...
$colors, then$colorswill equal['red', 'blue', 'green']@colors, then@colorswill equal('red', 'blue', 'green')%colors, then an error occurs
- In addition,
$ARGS{colors}will equal['red', 'blue', 'green'].
- In a URL:
- Passing a hash
gradeswith pairsAlice => 92andBob => 87.- In a URL:
/my/URL?grades=Alice&grades=92&grades=Bob&grades=87 - In an component call:
<& /my/comp, grades => {Alice => 92, Bob => 87} &> - In the called component, if there is a declared argument named...
@grades, then@gradeswill equal('Alice', 92, 'Bob', 87)%grades, then%gradeswill equal(Alice => 92, Bob => 87)
- In addition,
$gradeand$ARGS{grades}will equal['Alice',92,'Bob',87]in the URL case, or{Alice => 92, Bob => 87}in the component call case. (The discrepancy exists because, in a query string, there is no detectable difference between a list or hash.)
- In a URL:
not me side-eyeing example 3 likeβ¦ the URL truly cannot tell a list from a hash and that's just the lore. π
π Using @_ instead
if you don't like named parameters (valid honestly), you can pass a traditional list of ordered parameters:
<& /mktg/prods.html', 'dog', [2, 3, 4], {a => 7, b => 8} &>
and access them as usual through Perl's @_ array:
my ($scalar, $listref, $hashref) = @_;
in this case no <%args> section is necessary. freedom!! π¦
we generally recommend named parameters for the benefits of readability, syntax checking, and default value automation. however using @_ may be convenient for very small components, especially subcomponents created with <%def>.
okay important history lesson β before Mason 1.21,@_contained copies of the caller's arguments. in Mason 1.21 and beyond, this unnecessary copying was eliminated and@_now contains aliases to the caller's arguments, just as with regular Perl subroutines. for example, if a component updates$_[0], the corresponding argument is updated (or an error occurs if it is not updateable). β οΈ
most users won't notice this change because <%args> variables and the %ARGS hash always contain copies of arguments. so like, chill, it's probably fine. π
see perlsub for more information on @_ aliasing.
next up, more manual, keep scrolling bestie, we are SO not done β¨
π INITIALIZATION AND CLEANUP π
okay bestie, these next sections are all about when your Perl code runs. Different vibes, different moments, no cap. β¨
πΈ <%init> πΈ
This is the code that runs the second your component gets called. Like, immediately. Fr fr. What kinda stuff goes here? Think: checking that a user is logged in, pulling rows out of a database into a list, parsing a file's contents into a data structure. The classics. π
Technically, an <%init> block is literally the same thing as a <%perl> block sitting at the very beginning of the component. But β and this is the tea β it's just aesthetically nicer to park that block at the end of the component instead of the top. π
Here's why that slaps: the most readable components (especially for the non-programmers in the group chat) keep all the HTML in one continuous block up top, with cute little substitutions for the dynamic bits and zero distracting Perl in the way. Then down at the bottom, an <%init> block sets up all those substitution variables. This organization lets non-programmers hang out in the HTML without getting distracted or discouraged by Perl code. Iconic. π
Example time:
<html>
<head><title><% $headline %></title></head>
<body>
<h2><% $headline %></h2>
<p>By <% $author %>, <% $date %></p>
<% $body %>
</body>
</html>
<%init>
# Fetch article from database
my $dbh = DBI::connect ...;
my $sth = $dbh->prepare("select * from articles where id = ?");
$sth->execute($article_id);
my ($headline, $date, $author, $body) = $sth->fetchrow_array;
# Massage the fields
$headline = uc($headline);
my ($year, $month, $day) = split('-', $date);
$date = "$month/$day";
</%init>
<%args>
$article_id
</%args>
π§Ή <%cleanup> π§Ή
Cleanup code that runs just before the component exits. Closing a database connection, closing a file handle β that kinda thing. π
A <%cleanup> block is equivalent to a <%perl> block at the end of the component. Which means... it will NOT execute if the component explicitly returns, or if an abort or error happens in that component or one of its children. π
And because of that limitation, plus the fact that Perl is usually soooo good about cleaning up at the end of a lexical scope (like, a component), <%cleanup> sections are rarely needed. Not me telling you to skip them, just saying. π
If you genuinely need code that is guaranteed to run when the component or request exits, consider using a mod_perl cleanup handler, or creating a custom class with a DESTROY method. Those are the real ones. π«Ά
π¦ <%once> π¦
This code executes once when the component is loaded. Variables declared in here can be seen in all of a component's code and they persist for the entire lifetime of the component. Main character longevity, honestly. β¨
Super useful for:
- declaring persistent component-scoped lexical variables (especially objects that are expensive to create, ouch πΈ)
- declaring subroutines (both named and anonymous)
- initializing state
Now the important bits, listen up:
- This code does not run inside a request context.
- You cannot call components or access
$mor$rfrom this section. - Also, do not attempt to
return()from a<%once>section; the current compiler cannot properly handle it. π«
Normally this code will execute individually from every HTTP child that uses the component. But if the component is preloaded, this code will only execute once in the parent. So unless you have total control over what components will be preloaded, it is safest to avoid initializing variables that can't survive a fork(), e.g. DBI handles. π
Use code like this to initialize such variables in the <%init> section instead:
<%once>
my $dbh; # declare but don't assign
...
</%once>
<%init>
$dbh ||= DBI::connect ...
...
</%init>
In addition, using $m or $r in this section will not work in a preloaded component, because neither of those variables exist when a component is preloaded. Sorry bestie, them's the rules. π
π <%shared> π
Just like <%once>, lexical (my) variables declared in this section can be seen in all the rest of a component's code: the main body, subcomponents, and methods. π
BUT β and this is the plot twist β unlike <%once>, the code runs once per request (whenever the component is used), and its variables last only until the end of the request. Different vibe entirely.
A <%shared> section is useful for initializing variables needed in, say, the main body and one or more subcomponents or methods. See Object-Oriented Techniques for an example of usage. π
Real talk though, you need to realize this: you do not have access to the %ARGS hash or variables created via an <%args> block inside a shared section. However, you can access arguments via $m->request_args. Got it? π
Additionally, you cannot call a component's own methods or subcomponents from inside a <%shared>, though you can call other components.
Avoid using <%shared> for side-effect code that needs to run at a predictable time during page generation. You may assume only that <%shared> runs just before the first code that needs it, and runs at most once per request. That's the whole promise, don't push it. π
In the current implementation, the scope sharing is done with closures, so variables will only be shared if they are visible at compile-time in the other parts of the component. In addition, you can't rely on the specific destruction time of the shared variables, because they may not be destroyed until the first time the <%shared> section executes in a future request. <%init> offers a more predictable execution and destruction time. Predictability girlies, rise. π₯
Currently, any component with a <%shared> section incurs an extra performance penalty, because Mason must recreate its anonymous subroutines the first time each new request uses the component. The exact penalty varies between systems and for most applications will be unnoticeable. However, one should avoid using <%shared> when patently unnecessary, e.g. when an <%init> would work just as well. Don't do extra work for no reason, it's giving wasteful. π
Do not attempt to return() from a <%shared> section; the current compiler cannot properly handle it.
π EMBEDDED COMPONENTS π
π§ <%def name> π§
Each instance of this section creates a subcomponent embedded right inside the current component. Inside you may place anything a regular component contains β with the exception of <%def>, <%method>, <%once>, and <%shared> tags. So no nesting shenanigans, bestie. π«
The name is made of characters in the set [\w._-]. To call a subcomponent, simply use its name in <& &> or $m->comp. A subcomponent can only be seen from the surrounding component. It's a private little baby, very exclusive. π
If you define a subcomponent with the same name as a file-based component in the current directory, the subcomponent takes precedence. You'd need to use an absolute path to call the file-based component. To avoid this situation, and for general clarity, we recommend that you pick a unique way to name all of your subcomponents that is unlikely to interfere with file-based components. A commonly accepted practice is to start subcomponent names with .. π
While inside a subcomponent, you may use absolute or relative paths to call file-based components, and also call any of your "sibling" subcomponents. Group chat, but for components. π«Ά
The lexical scope of a subcomponent is separate from the main component. However, a subcomponent can declare its own <%args> section and have relevant values passed in. You can also use a <%shared> section to declare variables visible from both scopes. πΈ
In the following example, we create a .link subcomponent to produce a standardized hyperlink:
<%def .link>
<a href="http://www.<% $site %>.com"><% $label %></a>
<%args>
$site
$label=>ucfirst($site)
</%args>
</%def>
Visit these sites:
<ul>
<li><& .link, site=>'yahoo' &></li>
<li><& .link, site=>'cmp', label=>'CMP Media' &></li>
<li><& .link, site=>'excite' &></li>
</ul>
π
<%method name> π
Each instance of this section creates a method embedded inside the current component. Methods resemble subcomponents in terms of naming, contents, and scope. HOWEVER β while subcomponents can only be seen from the parent component, methods are meant to be called from other components. They're social like that. β¨
There are two ways to call a method. First, via a path of the form comp:method:
<& /foo/bar:method1 &>
$m->comp('/foo/bar:method1');
Second, via the call_method component method:
my $comp = $m->fetch_comp('/foo/bar');
...
$comp->call_method('method1');
Methods are commonly used in conjunction with autohandlers to make templates more flexible. See Object-Oriented Techniques for more information. π₯
You cannot create a subcomponent and a method with the same name. This is mostly to prevent obfuscation and accidental errors. Pick a lane, bestie. π
β FLAGS AND ATTRIBUTES β
The <%flags> and <%attr> sections consist of key/value pairs, one per line, joined by =>. In each pair, the key must be any valid Perl "bareword identifier" (made of letters, numbers, and the underscore character), and the value may be any scalar value, including references. An optional comment may follow each line. Cute, clean, done. π
π <%flags> π
Use this section to set official Mason flags that affect the current component's behavior.
Currently there is only one flag, inherit, which specifies the component's parent in the form of a relative or absolute component path. A component inherits methods and attributes from its parent; see Object-Oriented Techniques for examples. Passing down the family traits, iconic behavior. π
<%flags>
inherit=>'/site_handler'
</%flags>
π <%attr> π
Use this section to assign static key/value attributes that can be queried from other components. Static girlies, no drama. β¨
<%attr>
color => 'blue'
fonts => [qw(arial geneva helvetica)]
</%attr>
To query an attribute of a component, use the attr method:
my $color = $comp->attr('color')
where $comp is a component object.
Mason evaluates attribute values once when loading the component. This makes them faster but less flexible than methods. Speed vs. flexibility, the eternal tradeoff. π
π FILTERING π
okay bestie, this section is all about the different ways you can slap filtering functions over the results of the current component. the whole point? by pulling out and hiding a filter that, say, changes HTML in a super complicated way, we let non-programmers work in a cleaner HTML environment. iconic behavior, honestly. β¨
π <%filter> section π
The <%filter> section lets you arbitrarily filter the output of the current component. When you enter this code, $_ contains the component output, and you are expected to modify it in place. The code has access to component arguments and can invoke subroutines, call other components, etc. slay.
This simple filter converts the component output to UPPERCASE:
<%filter>
tr/a-z/A-Z/
</%filter>
The following navigation bar uses a filter to "unlink" and highlight the item corresponding to the current page:
<a href="/">Home</a> | <a href="/products/">Products</a> |
<a href="/bg.html">Background</a> | <a href="/finance/">Financials</a> |
<a href="/support/">Tech Support</a> | <a href="/contact.html">Contact Us</a>
<%filter>
my $uri = $r->uri;
s{<a href="$uri/?">(.*?)</a>} {<b>$1</b>}i;
</%filter>
This allows a designer to code such a navigation bar intuitively without "if" statements surrounding each link! Note that the regular expression need not be very robust as long as you have control over what will appear in the body. lowkey genius.
A filter block does not have access to variables declared in a component's <%init> section, though variables declared in the <%args>, <%once> or <%shared> blocks are usable in a filter. no cap.
It should be noted that a filter cannot rely on receiving all of a component's output at once, and so may be called multiple times with different chunks of output. This can happen if autoflush is on, or if a filter-containing component, or the components it calls, call the $m->flush_buffer() method. fr fr.
β οΈ You should never call Perl's return() function inside a filter section, or you will not see any output at all. do not do it, bestie.
You can use Component Calls with Content if you want to filter specific parts of a component rather than the entire component. obsessed.
π¬ COMMENT MARKERS π¬
There are several ways to place comments in components, i.e. arbitrary text that is ignored by the parser. iykyk.
π <%doc> π
Text in this section is treated as a comment and ignored. Most useful for a component's main documentation. One can easily write a program to sift through a set of components and pull out their <%doc> blocks to form a reference page. main character documentation energy.
π¨οΈ <% # comment... %> π¨οΈ
A <% %> tag is considered a comment if all of its lines are either whitespace, or begin with a '#' optionally preceded by whitespace. For example,
<% # This is a single-line comment %>
<%
# This is a
# multi-line comment
%>
π
%# comment π
Because a line beginning with % is treated as Perl, %# automatically works as a comment. However we prefer the <% # comment %> form over %#, because it stands out a little more as a comment and because it is more flexible with regards to preceding whitespace. the way that works.
π % if (0) { } π
Anything between these two lines
% if (0) {
...
% }
will be skipped by Mason, including component calls. While we don't recommend this for comments per se, it is a useful notation for "commenting out" code that you don't want to run. sneaky but valid.
π HTML/XML/... comments π
HTML and other markup languages will have their own comment markers, for example <!-- -->. Note two important differences with these comments versus the above comments:
- They will be sent to the client and appear in the source of the page.
- They do not block component calls and other code from running, so don't try to use them to comment out code!
<!-- Oops, the code below will still run
<& /shared/expensive.mhtml &>
-->
do not use these to comment out code, bestie, it will still run! π
π OTHER SYNTAX π
π§ <%text> π§
Text in this section is printed as-is with all Mason syntax ignored. This is useful, for example, when documenting Mason itself from a component:
<%text>
% This is an example of a Perl line.
<% This is an example of an expression block. %>
</%text>
This works for almost everything, but doesn't let you output </%text> itself! When all else fails, use $m->print:
% $m->print('The tags are <%text> and </%text>.');
β¨ Escaping expressions β¨
Mason has facilities for escaping the output from <% %> tags, on either a site-wide or a per-expression basis. glow up for your output.
Any <% %> expression may be terminated by a '|' and one or more escape flags (plus arbitrary whitespace), separated by commas:
<% $file_data |h %>
The current valid flags are:
hβ Escape HTML ('<' => '<', etc.) usingHTML::Entities::encode(). Before Perl 5.8.0 this module assumes that text is in the ISO-8859-1 character set; see the next section for how to override this escaping. After 5.8.0, the encoding assumes that text is in Unicode. era-dependent behavior, periodt.uβ Escape a URL query string (':' => '%3A', etc.) - all but[a-zA-Z0-9_.-]nβ This is a special flag indicating that the default escape flags should not be used for this substitution.
The administrator may specify a set of default escape flags via the default_escape_flags parameter. For example, if the administrator sets default_escape_flags to ['h'], then all <% %> expressions will automatically be HTML-escaped. In this case you would use the n flag to turn off HTML-escaping for a specific expression:
<% $html_block |n %>
Multiple escapes can be specified as a comma-separated list:
<% $uri | u, n %>
The old pre-defined escapes, 'h', 'u', and 'n', can be used without commas, so that this is legal:
<% $uri | un %>
However, this only works for these three escapes, and no others. If you are using user-defined escapes as well, you must use a comma:
<% $uri | u, add_session %>
π User-defined Escapes π
Besides the default escapes mentioned above, it is possible for the user to define their own escapes or to override the built-in 'h' and 'u' escapes. customize your vibe.
This is done via the Interp object's escape_flags parameter or set_escape() method. Escape names may be any number of characters as long as it matches the regex /^[\w-]+$/. The one exception is that you cannot override the 'n' flag.
Each escape flag is associated with a subroutine reference. The subroutine should expect to receive a scalar reference, which should be manipulated in place. Any return value from this subroutine is ignored. return value? ignored. we move.
Escapes can be defined at any time but using an escape that is not defined will cause an error when executing that component. error alert!
A common use for this feature is to override the built-in HTML escaping, which will not work with non-ISO-8559-1 encodings. If you are using such an encoding and want to switch the 'h' flag to do escape just the minimal set of characters ("<", ">", "&", """), put this in your Apache configuration:
PerlSetVar MasonEscapeFlags "h => \&HTML::Mason::Escapes::basic_html_escape"
Or, in a top-level autohandler:
$m->interp->set_escape( h => \&HTML::Mason::Escapes::basic_html_escape );
Or you could write your own escape function for a particular encoding:
$ah->interp->set_escape( h => \&my_html_escape );
And of course this can be used for all sorts of other things, like a naughty words filter for the easily offended:
$interp->set_escape( 'no-naughty' => \&remove_naughty_words );
π«Ά Manually applying escapes π«Ά
You can manually apply one or more escapes to text using the Interp object's apply_escapes() method. e.g.
$m->interp->apply_escapes( 'some html content', 'h' );
π« Backslash at end of line π«
A backslash (\) at the end of a line suppresses the newline. In HTML components, this is mostly useful for fixed width areas like <pre> tags, since browsers ignore white space for the most part. An example:
<pre>
foo
% if (1) {
bar
% }
baz
</pre>
outputs
foo
bar
baz
because of the newlines on lines 2 and 4. (Lines 3 and 5 do not generate a newline because the entire line is taken by Perl.) To suppress the newlines:
<pre>
foo\
% if (1) {
bar\
% }
baz
</pre>
which prints
foobarbaz
β¨ DATA CACHING β¨
okay bestie, this is the glow-up section π Mason's data caching interface lets components cache the results of computation so everything gets faster. And when we say anything can be cached, we mean anything β from a lil block of HTML to a whole complex data structure. no cap.
Every component gets its own private, persistent data cache. Except under special circumstances, one component does not access another component's cache. (boundaries, queen π«Ά) And each cached value can be set to expire at a certain time.
Data caching is built on top of one of two external caching APIs:
Cache::Cacheβ stable, but lowkey has not changed in years πCHIβ picked up right whereCache::Cacheleft off and is actively maintained β¨
You control which one Mason uses with the data_cache_api parameter. Cache::Cache is the default for backward compatibility reasons, but we recommend CHI for anyone doing serious caching. The APIs are super similar for Mason users, so most of the info below applies to both β any differences are noted.
πΈ Basic Usage
The $m->cache method returns a cache object representing the cache for this component. Here's the typical usage of $m->cache:
my $result = $m->cache->get('key');
if (!defined($result)) {
... compute $result ...
$m->cache->set('key', $result);
}
$m->cache->get tries to retrieve this component's cache value. If the value is available it gets placed in $result. If it's not available, $result is computed and stored in the cache by $m->cache->set. slay. π
π¦ Multiple Keys/Values
A cache can store multiple key/value pairs. A value can be anything serializable by Storable, from a simple scalar to an arbitrary complex list or hash reference:
$m->cache->set(name => $string);
$m->cache->set(friends => \@list);
$m->cache->set(map => \%hash);
You can fetch all the keys in a cache with
my @idents = $m->cache->get_keys;
It should be noted that Mason reserves all keys beginning with __mason for its own use. π« that's Mason's territory, bestie, don't touch.
β Expiration
You can pass an optional third argument to $m->cache->set indicating when the item should expire:
$m->cache->set('name1', $string1, '5 min'); # Expire in 5 minutes
$m->cache->set('name2', $string2, '3h'); # Expire in 3 hours
To change the expiration time for a piece of data, just call set again with the new expiration. To expire an item immediately, use $m->cache->remove.
You can also specify an expiration condition when you fetch the item, using the expire_if option:
my $result = $m->cache->get('key',
expire_if=>sub { $_[0]->get_created_at < (stat($file))[9] });
expire_if takes an anonymous subroutine, which is called with the cache object as its only parameter. If the subroutine returns a true value, the item is expired. In the example above, we expire the item whenever a certain file changes. iconic behaviour tbh π₯
Finally, you can expire a cache item from an external script; see Accessing a Cache Externally below. π
π Avoiding Concurrent Recomputation
The code shown in "Basic Usage" above,
my $result = $m->cache->get('key');
if (!defined($result)) {
... compute $result ...
$m->cache->set('key', $result);
}
can suffer from a kind of race condition for caches that are accessed frequently and take a long time to recompute. π
Suppose that a particular cache value is accessed five times a second and takes three seconds to recompute. When the cache expires, the first process comes in, sees that it is expired, and starts to recompute the value. The second process comes in and does the same thing. This sequence continues until the first process finishes and stores the new value. On average, the value will be recomputed and written to the cache 15 times! π not the 15x recompute...
One solution is the busy_lock flag:
my $result = $m->cache->get('key', busy_lock=>'30 sec');
In this case, when the value cannot be retrieved, get() sets the expiration time of the value 30 seconds in the future before returning undef. This tells the first process to compute the new value while causing subsequent processes to use the old value for 30 seconds.
Should the 30 seconds expire before the first process is done, a second process will start computing the new value while setting the expiration time yet another 30 seconds in the future, and so on. π
The disadvantage of this solution is that multiple writes to the cache will be performed for each set().
Another solution, available only if you are using CHI, is expires_variance which will create a variable time window during which expiration may occur. See the CHI documentation for details.
π Caching All Output
Occasionally you will need to cache the complete output of a component. For this purpose, Mason offers the $m->cache_self method. This method causes Mason to check to see if this component has already been run and its output cached. If this is the case, this output is simply sent as output. Otherwise, the component run normally and its output and return value cached.
It is typically used right at the top of an <%init> section:
<%init>
return if $m->cache_self(key => 'fookey', expires_in => '3 hours',
... <other cache options> ...);
... <rest of init> ...
</%init>
A full list of parameters and examples are available in the cache_self section of the Request manual. π
π Cache Object
$m->cache->get_object returns a Cache::Object or CHI::CacheObject associated with a particular key. You can use this to retrieve useful meta-data:
my $co = $m->cache->get_object('name1');
$co->get_created_at(); # when was object stored in cache
$co->get_expires_at(); # when does object expire
π§ Choosing a Cache Subclass - with Cache::Cache
The Cache::Cache API is implemented by a variety of backend subclasses. For example, FileCache implements the interface with a set of directories and files, MemoryCache implements the interface in process memory, and SharedMemoryCache implements the interface in shared memory.
By default $m->cache uses FileCache, but you can override this with the cache_class keyword. The value must be the name of a Cache::Cache subclass; the prefix Cache:: need not be included. For example:
my $result = $m->cache(cache_class => 'MemoryCache')->get('key');
$m->cache(cache_class => 'MemoryCache')->set(key => $result);
You can even specify different subclasses for different keys in the same component. Just make sure the correct value is passed to all calls to $m->cache; Mason does not remember which subclass you have used for a given component or key. π
The administrator can set the default cache subclass used by all components with the data_cache_defaults parameter.
πΈ Choosing a Cache Subclass - with CHI
The CHI API is implemented by a variety of drivers, for example CHI::Driver::File, CHI::Driver::FastMmap, and CHI::Driver::Memcached.
CHI::Driver::File is the default, but you can override this with the driver keyword. The value must be the name of a CHI::Driver subclass; the prefix CHI::Driver:: need not be included. For example:
my $cache = $m->cache(driver => 'Memcached', servers => [ ... ]);
my $result = $cache->get('key');
$cache->set(key => $result);
You can even specify different subclasses for different keys in the same component. Just make sure the correct value is passed to all calls to $m->cache; Mason does not remember which subclass you have used for a given component or key. (yes this is the same warning as above, it's that important bestie π
)
The administrator can set the default cache subclass used by all components with the data_cache_defaults parameter.
π Accessing a Cache Externally
To access a component's cache from outside the component (e.g. in an external Perl script), you'll need have the following information:
- the namespace associated with the component. For
Cache::Cache, the functionHTML::Mason::Utils::data_cache_namespace, given a component id (usually just the component path), returns the namespace. ForCHI, the component id/path itself is the namespace. - the cache_root, for file-based caches only. Defaults to the
cachesubdirectory under the Mason data directory.
Given this information you can get a handle on the component's cache. For example, the following code removes a cache item for component /foo/bar, assuming the data directory is /usr/local/www/mason and you are using the default file backend:
use HTML::Mason::Utils qw(data_cache_namespace);
# With Cache::Cache
my $cache = new Cache::FileCache
( { namespace => data_cache_namespace("/foo/bar"),
cache_root => "/usr/local/www/mason/cache" } );
# With CHI
my $cache = CHI->new
( driver => 'File',
namespace => "/foo/bar",
cache_root => "/usr/local/www/mason/cache" );
# Remove one key
$cache->remove('key1');
# Remove all keys
$cache->clear;
π Mason 1.0x Cache API
For users upgrading from 1.0x and earlier, any existing $m->cache code will be incompatible with the new API. However, if you wish to continue using the 1.0x cache API for a while, you (or your administrator) can set data_cache_api to '1.0'. All of the $m->cache options with the exception of tie_class should be supported.
The access_data_cache function is no longer available; this will need to be converted to use Cache::Cache directly, as described in the previous section. π«‘
β¨ WEB-SPECIFIC FEATURES β¨
Like, this is the part where Mason gets all webby on you. π
π Sending HTTP Headers π
So here's the tea: Mason is gonna send your HTTP headers for you, automatically, via $r->send_http_header. But β and this is the important bit, bestie β it will not send headers if they've already been sent manually. It knows. It's polite like that. π«Ά
Now, to figure out the exact header behavior on your system, you gotta know whether your server's default is autoflush on or off. Your administrator should have this info. And if your administrator doesn't know? Then it's probably off, which is the default. π
With autoflush off, the header sitch is extremely simple: Mason just waits until the very end of the request to send headers. Any component can modify or augment the headers. Everyone gets a say. It's giving democracy. π
With autoflush on, things get more complex. Mason will send headers just before sending the first output. Which means if you wanna affect the headers with autoflush on, you gotta do it before any component sends any output. Generally this happens in an <%init> section. Lock it in early or lose your chance, fr fr. π
For example, this top-level component below calls another component to check whether the user has a cookie; if they don't, it inserts a new cookie into the header:
<%init>
my $cookie = $m->comp('/shared/get_user_cookie');
if (!$cookie) {
$cookie = new CGI::Cookie (...);
$r->header_out('Set-cookie' => $cookie);
}
...
</%init>
With autoflush off, this code will always work. Iconic. β¨ But turn autoflush on and this code will only work as long as /shared/get_user_cookie doesn't output anything (and given its functional nature, it shouldn't). Periodt.
Your administrator can turn off automatic header sending via the auto_send_headers parameter. And you can also turn it off on individual pages with:
$m->auto_send_headers(0);
π¦ Returning HTTP Status π¦
The value returned from the top-most component becomes the status code of the request. If no value is explicitly returned, it defaults to OK (0). Simple enough. π
But here's where it gets messy β simply returning an error status (such as 404) from the top-most component has two problems in practice:
- The decision to return an error status often resides further down in the component stack.
- You may have already generated some content by the time this decision is made.
(Both of these are more likely to be true when you're using autohandlers, jsyk.)
So the safer way to generate an error status is:
$m->clear_buffer;
$m->abort($status);
$m->abort bypasses the component stack and ensures that $status is returned from the top-most component. It works by throwing an exception. π And if you wrapped this code (directly or indirectly) in an eval, you must take care to rethrow the exception, or the status will not make it out:
eval { $m->comp('...') };
if (my $err = $@) {
if ($m->aborted) {
die $err;
} else {
# deal with non-abort exceptions
}
}
Rethrow it or lose it, bestie. No cap. π
π Filters and $m->abort π
A filter section will still be called after a component aborts with $m->abort. You can always check $m->aborted in your <%filter> block if you don't want to run the filter after an abort.
<%filter>
unless ( $m->aborted ) {
$_ .= ' filter stuff';
}
</%filter>
π External Redirects π
Because it is so commonly needed, Mason 1.1x and on provides an external redirect method:
$m->redirect($url); # Redirects with 302 status
This method uses the clear_buffer/abort technique mentioned above, so the same warnings apply regarding evals. β οΈ
Also β and this is a sneaky one β if you generate any output after calling $m->redirect, then this output will be sent, and will break the redirect. Like, it just ruins the whole vibe. For example:
% eval { $m->comp('redirect', ...) };
% die $@ if $@;
The blank line between the two Perl lines is new output generated after the redirect. π Either remove it or call $m->clear_buffer immediately before calling die().
π Internal Redirects π
There are two ways to perform redirects that are invisible to the client. Sneaky. I love it. π
- First, you can use a Mason subrequest (see "Subrequests"). This only works if you are redirecting to another Mason page.
- Second, you can use Apache's
internal_redirectmethod, which works whether or not the new URL will be handled by Mason. Use it this way:
$r->internal_redirect($url);
$m->auto_send_headers(0);
$m->clear_buffer;
$m->abort;
The last three lines prevent the original request from accidentally generating extra headers or content. Chef's kiss. π
π USING THE PERL DEBUGGER π
You can use the perl debugger in conjunction with a live mod_perl/Mason server with the help of Apache::DB, available from CPAN. Refer to the Apache::DB documentation for details. π
The only tricky thing about debugging Mason pages is that components are implemented by anonymous subroutines, which are not easily breakpoint'able. Which is, honestly, so annoying. π To remedy this, Mason calls the dummy subroutine debug_hook at the beginning of each component. You can breakpoint this subroutine like so:
b HTML::Mason::Request::debug_hook
debug_hook is called with two parameters: the current Request object and the full component path. Thus you can breakpoint specific components using a conditional on $_[1]:
b HTML::Mason::Request::debug_hook $_[1] =~ /component name/
And you can avoid all that typing by adding the following to your ~/.perldb file:
# Perl debugger aliases for Mason
$DB::alias{mb} = 's/^mb\b/b HTML::Mason::Request::debug_hook/';
which reduces the previous examples to just:
mb
mb $_[1] =~ /component name/
Look at that. Short king behavior. β¨
Mason normally inserts #line directives into compiled components so that line numbers are reported relative to the source file. Depending on your task, this can be a help or a hindrance when using the debugger. Your administrator can turn off #line directives with the use_source_line_numbers parameter.
π LOGGING π
Mason uses Log::Any to log various events, such as the start and end of each request and each component call. You can also log to Log::Any from a component with the $m->log method. e.g.
$m->log->error("Something bad happened!");
$m->log->debugf("Arguments for '%s' were '%s'", $func, \%args)
if $m->log->is_debug;
See Log::Any::Adapter for how to direct these logs to an output of your choice. Slay. π
β¨ OBJECT-ORIENTED TECHNIQUES β¨
okay bestie, earlier you learned how to assign a common template to an entire hierarchy of pages using autohandlers. The basic template looks like:
header HTML
% $m->call_next;
footer HTML
But sometimes you'll want a more flexible template that adjusts to the requested page. You might want to allow each page or subsection to specify a title, background color, or logo image while leaving the rest of the template intact. You might want some pages or subsections to use a different template, or to ignore templates entirely.
These issues can be addressed with the object-oriented style primitives introduced in Mason 0.85.
Note: we use the term object-oriented loosely. Mason borrows concepts like inheritance, methods, and attributes from object methodology but implements them in a shallow way to solve a particular set of problems. Future redesigns may incorporate a deeper object architecture if the current prototype proves successful.
π Determining inheritance π
Every component may have a single parent. The default parent is a component named "autohandler" in the closest parent directory. This rule applies to autohandlers too: an autohandler may not have itself as a parent but may have an autohandler further up the tree as its parent.
You can use the "inherit" flag to override a component's parent:
<%flags>
inherit => '/foo/bar'
</%flags>
If you specify undef as the parent, then the component inherits from no one. This is how to suppress templates.
Currently there is no way to specify a parent dynamically at run-time, or to specify multiple parents.
π Content wrapping π
At page execution time, Mason builds a chain of components from the called component, its parent, its parent's parent, and so on. Execution begins with the top-most component; calling "$m->call_next" passes control to the next component in the chain. This is the familiar autohandler "wrapping" behavior, generalized for any number of arbitrarily named templates.
π¦ Accessing methods and attributes π¦
A template can access methods and/or attributes of the requested page. First, use "$m->request_comp" to get a handle on the appropriate component:
my $self = $m->request_comp;
$self now refers to the component corresponding to the requested page (the component at the end of the chain).
To access a method for the page, use "call_method":
$self->call_method('header');
This looks for a method named 'header' in the page component. If no such method exists, the chain of parents is searched upwards, until ultimately a "method not found" error occurs. Use 'method_exists' to avoid this error for questionable method calls:
if ($self->method_exists('header')) { ...
The component returned by the "$m->request_comp" method never changes during request execution. In contrast, the component returned by "$m->base_comp" may change several times during request execution.
When execution starts, the base component is the same as the requested component. Whenever a component call is executed, the base component may become the component that was called. The base component will change for all component calls except in the following cases:
- A component is called via its component object rather than its path, for example:
<& $m->fetch_comp('/some/comp'), foo => 1 &>
- A subcomponent (defined with
"<%def>") is called. - A method is called via the use of
"SELF:","PARENT:", or"REQUEST:". These are covered in more detail below.
In all other cases, the base component is the called component or the called component's owner component if that called component is a method.
As hinted at above, Mason provides a shortcut syntax for method calls.
If a component call path starts with "SELF:", then Mason will start looking for the method (the portion of the call after "SELF:"), in the base component.
<& SELF:header &>
$m->comp('SELF:header')
If the call path starts with "PARENT:", then Mason will start looking in the current component's parent for the named method.
<& PARENT:header &>
$m->comp('PARENT:header')
In the context of a component path, PARENT is shorthand for "$m->current_comp->parent".
If the call path begins with "REQUEST:", then Mason looks for the method in the requested component. REQUEST is shorthand for "$m->request_comp".
The rules for attributes are similar. To access an attribute for the page, use "attr":
my $color = $self->attr('color')
This looks for an attribute named 'color' in the $self component. If no such attribute exists, the chain of parents is searched upwards, until ultimately an "attribute not found" error occurs. Use "attr_exists" or "attr_if_exist" to avoid this error for questionable attributes:
if ($self->attr_exists('color')) { ...
my $color = $self->attr_if_exists('color'); # if it doesn't exist $color is undef
πΈ Sharing data πΈ
A component's main body and its methods occupy separate lexical scopes. Variables declared, say, in the "<%init>" section of the main component cannot be seen from methods.
To share variables, declare them either in the "<%once>" or "<%shared>" section. Both sections have an all-inclusive scope. The "<%once>" section runs once when the component loads; its variables are persistent for the lifetime of the component. The "<%shared>" section runs once per request (when needed), just before any code in the component runs; its variables last only til the end of the request.
In the following example, various sections of code require information about the logged-in user. We use a "<%shared>" section to fetch these in a single request.
<%attr>
title=>sub { "Account for $full_name" }
</%attr>
<%method lefttoc>
<i><% $full_name %></i>
(<a href="logout.html">Log out</a>)<br />
...
</%method>
Welcome, <% $fname %>. Here are your options:
<%shared>
my $dbh = DBI::connect ...;
my $user = $r->connection->user;
my $sth = $dbh->prepare("select lname,fname, from users where user_id = ?");
$sth->execute($user);
my ($lname, $fname) = $sth->fetchrow_array;
my $full_name = "$first $last";
</%shared>
"<%shared>" presents a good alternative to "<%init>" when data is needed across multiple scopes. Outside these situations, "<%init>" is preferred for its slightly greater speed and predictable execution model.
π Example π
Let's say we have three components:
/autohandler
/products/autohandler
/products/index.html
and that a request comes in for /products/index.html.
/autohandler contains a general template for the site, referring to a number of standard methods and attributes for each page:
<head>
<title><& SELF:title &></title>
</head>
<body style="<% $self->attr('body_style') %>">
<& SELF:header &>
<div id="main">
% $m->call_next;
</div>
<& SELF:footer &>
</body>
<%init>
my $self = $m->base_comp;
...
</%init>
<%attr>
body_style => 'standard'
</%attr>
<%method title>
McGuffey Inc.
</%method>
<%method header>
<h2><& SELF:title &></h2>
</%method>
<%method footer>
</%method>
Notice how we provide defaults for each method and attribute, even if blank.
/products/autohandler overrides some attributes and methods for the /products section of the site.
<%attr>
body_style => 'plain'
</%attr>
<%method title>
McGuffey Inc.: Products
</%method>
% $m->call_next;
Note that this component, though it only defines attributes and methods, must call "$m->call_next" if it wants the rest of the chain to run.
/products/index.html might override a few attributes, but mainly provides a primary section for the body.
π COMMON TRAPS π
π« Do not call $r->content or "new CGI" π«
Mason calls "$r->content" itself to read request input, emptying the input buffer and leaving a trap for the unwary: subsequent calls to "$r->content" hang the server. This is a mod_perl "feature" that may be fixed in an upcoming release.
For the same reason you should not create a CGI object like
my $query = new CGI;
when handling a POST; the CGI module will try to reread request input and hang. Instead, create an empty object:
my $query = new CGI ("");
such an object can still be used for all of CGI's useful HTML output functions. Or, if you really want to use CGI's input functions, initialize the object from %ARGS:
my $query = new CGI (\%ARGS);
π MASON AND SOURCE FILTERS π
Modules which work as source filters, such as "Switch.pm", will only work when you are using object files. This is because of how source filters are implemented, and cannot be changed by the Mason authors.
and that's the entire page, bestie! brought to you by perl v5.38.2, dated 2024-03-05, from HTML::...:Devel(3pm) πβ¨
π¦ where this page comes from
- debian trixie: libhtml-mason-perl 1:1.60-2 Β· Artistic-1.0-Perl OR GPL-1.0-or-later
- ubuntu noble: libhtml-mason-perl 1:1.60-2 Β· Artistic-1.0-Perl OR GPL-1.0-or-later
- ubuntu resolute: libhtml-mason-perl 1:1.60-2 Β· Artistic-1.0-Perl OR GPL-1.0-or-later
- π girlified by deepseek-ai/DeepSeek-V4.1-Flash on : a language model's rewrite of the original, under its terms