The London Perl and Raku Workshop takes place on 26th Oct 2024. If your company depends on Perl, please consider sponsoring and/or attending.
    <HTML> 
	<HEAD> 
	    <TITLE>Devel.pod - Mason Developer's Manual

</TITLE> 
	</HEAD>

	<BODY>

<!-- INDEX BEGIN -->

<UL>

	<LI><A HREF="#name">NAME</A>
	<LI><A HREF="#description">DESCRIPTION</A>
	<LI><A HREF="#how_to_use_this_manual">HOW TO USE THIS MANUAL</A>
	<LI><A HREF="#what_are_components_">WHAT ARE COMPONENTS?</A>
	<LI><A HREF="#in_line_perl_sections">IN-LINE PERL SECTIONS </A>
	<UL>

		<LI><A HREF="#examples_and_recommended_usage">Examples and Recommended Usage</A>
	</UL>

	<LI><A HREF="#mason_objects">MASON OBJECTS</A>
	<UL>

		<LI><A HREF="#request_objects">Request Objects</A>
		<LI><A HREF="#system_objects">System Objects</A>
		<LI><A HREF="#component_objects">Component Objects</A>
	</UL>

	<LI><A HREF="#calling_components">CALLING COMPONENTS</A>
	<UL>

		<LI><A HREF="#components_that_output_html">Components that output HTML</A>
		<LI><A HREF="#components_that_compute_values">Components that compute values</A>
	</UL>

	<LI><A HREF="#top_level_components">TOP-LEVEL COMPONENTS</A>
	<UL>

		<LI><A HREF="#dhandlers">dhandlers</A>
		<LI><A HREF="#autohandlers">autohandlers</A>
		<LI><A HREF="#dhandlers_vs_autohandlers">dhandlers vs. autohandlers</A>
	</UL>

	<LI><A HREF="#passing_parameters">PASSING PARAMETERS</A>
	<UL>

		<LI><A HREF="#in_component_calls">In Component Calls</A>
		<LI><A HREF="#in_http_requests">In HTTP requests</A>
		<LI><A HREF="#accessing_parameters">Accessing Parameters</A>
		<LI><A HREF="#parameter_passing_examples">Parameter Passing Examples</A>
		<LI><A HREF="#using_instead">Using @_ instead</A>
	</UL>

	<LI><A HREF="#initialization_and_cleanup">INITIALIZATION AND CLEANUP</A>
	<UL>

		<LI><A HREF="#e_lt_inite_gt_">&lt;%init&gt;</A>
		<LI><A HREF="#e_lt_cleanupe_gt_">&lt;%cleanup&gt;</A>
		<LI><A HREF="#e_lt_oncee_gt_">&lt;%once&gt;</A>
		<LI><A HREF="#e_lt_sharede_gt_">&lt;%shared&gt;</A>
	</UL>

	<LI><A HREF="#embedded_components">EMBEDDED COMPONENTS</A>
	<UL>

		<LI><A HREF="#e_lt_def_i_name_e_gt_">&lt;%def <EM>name</EM>&gt;</A>
		<LI><A HREF="#e_lt_method_i_name_e_gt_">&lt;%method <EM>name</EM>&gt;</A>
	</UL>

	<LI><A HREF="#flags_and_attributes">FLAGS AND ATTRIBUTES</A>
	<UL>

		<LI><A HREF="#e_lt_flagse_gt_">&lt;%flags&gt;</A>
		<LI><A HREF="#e_lt_attre_gt_">&lt;%attr&gt;</A>
	</UL>

	<LI><A HREF="#filtering">FILTERING</A>
	<UL>

		<LI><A HREF="#_lt_filter_gt_section">&lt;%filter&gt; section</A>
		<LI><A HREF="#_m_call_self_command">$m->call_self command</A>
		<LI><A HREF="#how_filtering_works">How filtering works</A>
	</UL>

	<LI><A HREF="#other_syntax">OTHER SYNTAX</A>
	<UL>

		<LI><A HREF="#e_lt_doce_gt_">&lt;%doc&gt;</A>
		<LI><A HREF="#e_lt_texte_gt_">&lt;%text&gt;</A>
		<LI><A HREF="#escaping_expressions">Escaping expressions</A>
		<LI><A HREF="#_at_end_of_line">\ at end of line</A>
	</UL>

	<LI><A HREF="#data_caching">DATA CACHING</A>
	<UL>

		<LI><A HREF="#basic_usage">Basic Usage</A>
		<LI><A HREF="#multiple_keys_values">Multiple Keys/Values</A>
		<LI><A HREF="#expiration">Expiration</A>
		<LI><A HREF="#busy_locks">Busy Locks</A>
		<LI><A HREF="#keeping_in_memory">Keeping In Memory</A>
		<LI><A HREF="#caching_all_output">Caching All Output </A>
		<LI><A HREF="#guarantees_or_lack_thereof_">Guarantees (or lack thereof)</A>
	</UL>

	<LI><A HREF="#sending_http_headers">SENDING HTTP HEADERS</A>
	<LI><A HREF="#using_the_perl_debugger">USING THE PERL DEBUGGER</A>
	<UL>

		<LI><A HREF="#using_debug_files">Using debug files</A>
		<LI><A HREF="#specifying_when_to_create_debug_">Specifying when to create debug files</A>
		<LI><A HREF="#how_debug_files_work">How debug files work</A>
		<LI><A HREF="#when_debug_files_don_t_work">When debug files don't work</A>
	</UL>

	<LI><A HREF="#using_the_perl_profiler">USING THE PERL PROFILER</A>
	<LI><A HREF="#the_previewer">THE PREVIEWER</A>
	<LI><A HREF="#object_oriented_techniques">OBJECT-ORIENTED TECHNIQUES</A>
	<UL>

		<LI><A HREF="#determining_inheritance">Determining inheritance</A>
		<LI><A HREF="#content_wrapping">Content wrapping</A>
		<LI><A HREF="#accessing_methods_and_attributes">Accessing methods and attributes</A>
		<LI><A HREF="#sharing_data">Sharing data</A>
		<LI><A HREF="#example">Example</A>
	</UL>

	<LI><A HREF="#common_traps">COMMON TRAPS</A>
	<LI><A HREF="#author">AUTHOR</A>
	<LI><A HREF="#see_also">SEE ALSO</A>
</UL>
<!-- INDEX END -->

<HR>
<P>
<H1><A NAME="name">NAME

</A></H1>
Devel.pod - Mason Developer's Manual


<P>

<P>
<HR>
<H1><A NAME="description">DESCRIPTION

</A></H1>
This manual is written for content developers who know HTML and at least a
little Perl. The goal is to write, run, and debug Mason components.


<P>

If you are the webmaster (or otherwise responsible for the Mason
installation), you should also read <STRONG>HTML::Mason::Admin</STRONG>. There you will find information about virtual site configuration,
performance tuning, component caching, and so on.


<P>

We strongly suggest that you have a working Mason to play with as you work
through these examples. Other component examples can be found in the <CODE>samples/</CODE> directory.


<P>

<P>
<HR>
<H1><A NAME="how_to_use_this_manual">HOW TO USE THIS MANUAL

</A></H1>
If you are just learning Mason and want to get started quickly, we
recommend the following sections:


<P>

o <A HREF="#what_are_components_">What Are Components?</A>




<P>

o <A HREF="#in_line_perl_sections">In-Line Perl Sections</A>




<P>

o <A HREF="#calling_components">Calling Components</A>




<P>

o <A HREF="#passing_parameters">Passing Parameters</A>




<P>

o <A HREF="#initialization_and_cleanup">Initialization and Cleanup</A> (mainly <CODE>&lt;%init&gt;</CODE>)


<P>

o <A HREF="#data_caching">Data Caching</A>




<P>

o <A HREF="#sending_http_headers">Sending HTTP Headers</A>




<P>

o <A HREF="#common_traps">Common Traps</A>




<P>

<P>
<HR>
<H1><A NAME="what_are_components_">WHAT ARE COMPONENTS?

</A></H1>
The component - a mix of Perl and HTML - is Mason's basic building block
and computational unit. 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:


<P>

<PRE>    +---------+------------------+
    |Masthead | Banner Ad        |
    +---------+------------------+
    |         |                  |
    |+-------+|Text of Article ..|
    ||       ||                  |
    ||Related||Text of Article ..|
    ||Stories||                  |
    ||       ||Text of Article ..|
    |+-------+|                  |
    |         +------------------+
    |         | Footer           |
    +---------+------------------+
</PRE>

<P>

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.


<P>

This component approach reaps many benefits in a web environment. The first
benefit is <EM>consistency</EM>: 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. The second benefit is <EM>concurrency</EM>: in a multi-person environment, one person can edit the masthead while
another edits the table of contents. A last benefit is <EM>reuseability</EM>: 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.


<P>

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.


<P>

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.


<P>

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 <STRONG>Devel::DProf</STRONG> to profile their performance.


<P>

<P>
<HR>
<H1><A NAME="in_line_perl_sections">IN-LINE PERL SECTIONS 

</A></H1>
Here is a simple component example:


<P>

<PRE>    &lt;%perl&gt;
    my $noun = 'World';
    my @time = split /[\s:]/, localtime;
    &lt;/%perl&gt;
    Hello &lt;% $noun %&gt;,
    % if ( $time[3] &lt; 12 ) {
    good morning.
    % } else {
    good afternoon.
    % }
</PRE>

<P>

After 12 pm, the output of this component is:


<P>

<PRE>    Hello world, good afternoon.
</PRE>

<P>

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 (<CODE>&lt;%init&gt;</CODE>, <CODE>&lt;%args&gt;</CODE>, etc.) are tied to component events like initialization, cleanup, and
argument definition.


<P>

The parsing rules for these Perl sections are as follows:


<P>

<OL>
<LI><STRONG><A NAME="item_">

</A></STRONG>
Blocks of the form &lt;% xxx %&gt; are replaced with the result of
evaluating xxx as a single Perl expression. These are often used for
variable replacement. such as 'Hello, &lt;% <CODE>$name</CODE> %&gt;!'.


<P>

<LI><STRONG><A NAME="item_">

</A></STRONG>
Lines beginning with a '%' character are treated as Perl. 


<P>

<LI><STRONG><A NAME="item_">

</A></STRONG>
Multiline blocks of Perl code can be inserted with the <CODE>&lt;%perl&gt;</CODE>
.. <CODE>&lt;/%perl&gt;</CODE> tag. The enclosed text is executed as Perl and the return value, if any, is
discarded.


<P>

The <CODE>&lt;%perl&gt;</CODE> tag is case-insensitive. It may appear anywhere in the text, and may span
any number of lines. <CODE>&lt;%perl&gt;</CODE> blocks cannot be nested inside one another.


<P>

</OL>
<P>
<HR>
<H2><A NAME="examples_and_recommended_usage">Examples and Recommended Usage

</A></H2>
<STRONG>% lines</STRONG>




<P>

Most useful for conditional and loop structures - if, while, foreach, ,
etc. - as well as side-effect commands like assignments. Examples:


<P>

o Conditional code


<P>

<PRE>    % my $ua = $r-&gt;header_in('User-Agent');
    % if ($ua =~ /msie/i) {
    Welcome, Internet Explorer users
    ...
    % } elsif ($ua =~ /mozilla/i) {
    Welcome, Netscape users
    ...
    % }
</PRE>

<P>

o HTML list formed from array


<P>

<PRE>    &lt;ul&gt;
    % foreach $item (@list) {
    &lt;li&gt;&lt;% $item %&gt;
    % }
    &lt;/ul&gt;
</PRE>

<P>

o HTML list formed from hash


<P>

<PRE>    &lt;ul&gt;
    % while (my ($key,$value) = each(%ENV)) {
    &lt;li&gt;
    &lt;b&gt;&lt;% $key %&gt;&lt;/b&gt;: &lt;% $value %&gt;
    % }
    &lt;/ul&gt;
</PRE>

<P>

o HTML table formed from list of hashes


<P>

<PRE>    &lt;table&gt;
    &lt;tr&gt;
    % foreach my $h (@loh) {
    &lt;td&gt;&lt;% $h-&gt;{foo} %&gt;&lt;/td&gt;
    &lt;td bgcolor=#ee0000&gt;&lt;% $h-&gt;{bar} %&gt;&lt;/td&gt;
    &lt;td&gt;&lt;% $h-&gt;{baz} %&gt;&lt;/td&gt;
    % }
    &lt;/tr&gt;
    &lt;/table&gt;
</PRE>

<P>

<STRONG>&lt;% xxx %&gt;</STRONG>




<P>

Most useful for printing out variables, as well as more complex
expressions. Examples:


<P>

<PRE>  Dear &lt;% $name %&gt;: We will come to your house at &lt;% $address %&gt; in the
  fair city of &lt;% $city %&gt; to deliver your $&lt;% $amount %&gt; dollar prize!
</PRE>

<P>

<PRE>  The answer is &lt;% ($y+8) % 2 %&gt;.
</PRE>

<P>

<PRE>  You are &lt;% $age&lt;18 ? 'not' : '' %&gt; permitted to enter this site.
</PRE>

<P>

<STRONG>&lt;%perl&gt; xxx &lt;%/perl&gt;</STRONG>




<P>

Useful for Perl blocks of more than a few lines.


<P>

<P>
<HR>
<H1><A NAME="mason_objects">MASON OBJECTS

</A></H1>
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.


<P>

<P>
<HR>
<H2><A NAME="request_objects">Request Objects

</A></H2>
Two global per-request objects are available to all components:
<CODE>$r</CODE> and $m.


<P>

$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:


<P>

<PRE>    $r-&gt;uri             # the HTTP request URI
    $r-&gt;header_in(..)   # get the named HTTP header line
    $r-&gt;content_type    # set or retrieve content-type
    $r-&gt;header_out(..)  # set or retrieve an outgoing header
</PRE>

<P>

<PRE>    $r-&gt;content         # don't use this one! (see Tips and Traps)
</PRE>

<P>

$m, the Mason request object, provides an analogous API for Mason. All
Mason features not activated by syntactic tags are accessed via
<CODE>$m</CODE> methods. You'll be introduced to these methods throughout
this document as they are needed. For a description of all methods see
<STRONG><A HREF="././Request.html#">HTML::Mason::Request</A></STRONG>.


<P>

Note to pre-0.8 users: The <CODE>$m</CODE> API replaces both the old <CODE>mc_</CODE> command set and the <CODE>$REQ</CODE> variable. See <STRONG><A HREF="././Commands.html#">HTML::Mason::Commands</A></STRONG> for a conversion guide. There is also a utility provided with the
distribution, <EM>bin/convert0.8.pl</EM>, that performs appropriate conversions on your existing component tree.


<P>

<P>
<HR>
<H2><A NAME="system_objects">System Objects

</A></H2>
Three system objects share the work of serving requests in Mason: Parser,
Interp, and ApacheHandler. 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.


<P>

<P>
<HR>
<H2><A NAME="component_objects">Component Objects

</A></H2>
Mason provides an object API for components, allowing you to query a
component's various asociated files, arguments, etc. For a description of
all methods see <STRONG><A HREF="././Component.html#">HTML::Mason::Component</A></STRONG>. Typically you get a handle on a component object from request methods
like
<CODE>$m-&gt;current_comp</CODE> and <CODE>$m-&gt;fetch_comp</CODE>. 


<P>

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.


<P>

<P>
<HR>
<H1><A NAME="calling_components">CALLING COMPONENTS

</A></H1>
Mason pages often are built not from a single component, but from multiple
components that call each other in a hierarchical fashion.


<P>

<P>
<HR>
<H2><A NAME="components_that_output_html">Components that output HTML

</A></H2>
To call one component from another, use the &lt;&amp; &amp;&gt; tag:


<P>

<PRE>    &lt;&amp; comp_path, [name=&gt;value, ...] &amp;&gt;
</PRE>

<P>

<DL>
<DT><STRONG><A NAME="item_comp_path_">comp_path:

</A></STRONG><DD>
The component path. With a leading '/', the path is relative to the
component root (<A HREF="././Interp.html#item_comp_root">comp_root</A>). Otherwise, it is relative to the location of the calling component.


<P>

<DT><STRONG><A NAME="item_name_value_pairs_">name=&gt;value pairs:

</A></STRONG><DD>
Parameters are passed as one or more name=&gt;value pairs, e.g. <CODE>player=&gt;'M.&nbsp;Jordan'</CODE>. 


<P>

</DL>
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 <CODE>[A-Za-z0-9/_.]</CODE>, comp_path is assumed to be a literal string running up to the first comma
or &amp;&gt;. Otherwise, comp_path is evaluated as an expression.


<P>

Here are some examples:


<P>

<PRE>    # relative component paths
    &lt;&amp; topimage &amp;&gt;
    &lt;&amp; tools/searchbox &amp;&gt;
</PRE>

<P>

<PRE>    # absolute component path
    &lt;&amp; /shared/masthead, color=&gt;'salmon' &amp;&gt;
</PRE>

<P>

<PRE>    # this component path MUST have quotes because it contains a comma
    &lt;&amp; &quot;sugar,eggs&quot;, mix=&gt;1 &amp;&gt;
</PRE>

<P>

<PRE>    # variable component path
    &lt;&amp; $comp &amp;&gt;
    
    # variable component and arguments
    &lt;&amp; $comp, %args &amp;&gt;
</PRE>

<P>

<PRE>    # you can use arbitrary expression for component path, but it cannot
    # begin with a letter or number; delimit with () to remedy this
    &lt;&amp; (int(rand(2)) ? 'thiscomp' : 'thatcomp'), id=&gt;123 &amp;&gt;
</PRE>

<P>

Several request methods also exist for calling components.  <CODE>$m-&gt;comp</CODE>
performs the equivalent action to &lt;&amp; &amp;&gt;:


<P>

<PRE>    $m-&gt;comp('/shared/masthead', color=&gt;'salmon');
</PRE>

<P>

<CODE>$m-&gt;scomp</CODE> is like the sprintf version of <CODE>$m-&gt;comp</CODE>: it returns the component output, allowing the caller to examine and
modify it before printing:


<P>

<PRE>    my $masthead = $m-&gt;scomp('/shared/masthead', color=&gt;'salmon');
    $masthead =~ ...;
    $m-&gt;out($masthead);
</PRE>

<P>

<P>
<HR>
<H2><A NAME="components_that_compute_values">Components that compute values

</A></H2>
So far you have seen components used solely to output HTML. However,
components may also be used to compute a value. For example, you might have
a component <CODE>is_netscape</CODE> that analyzes the user agent to determine whether it is a Netscape browser:


<P>

<PRE>    &lt;%perl&gt;
    my $ua = $r-&gt;header_in('User-Agent');
    return ($ua =~ /Mozilla/i &amp;&amp; $ua !~ /MSIE/i) ? 1 : 0;
    &lt;/%perl&gt;
</PRE>

<P>

Because components are implemented underneath with Perl subroutines, they
can return values and even understand scalar/list context.


<P>

The &lt;&amp; &amp;&gt; notation only calls a component for its side-effect, and
discards its return value, if any. To get at the return value of a
component, use the <CODE>$m-&gt;comp</CODE> command:


<P>

<PRE>    % if ($m-&gt;comp('is_netscape')) {
    Welcome, Netscape user!
    % }
</PRE>

<P>

Mason adds a <CODE>return undef</CODE> to the bottom of each component to provide an empty default return value.
To return your own value from a component, you <EM>must</EM> use an explicit <CODE>return</CODE> statement. You cannot rely on the usual Perl trick of letting return values
``fall through''.


<P>

Generally components are divided into two types: those that output HTML,
and those that return a value. There is very little reason for a component
to do both. For example, it would not be very friendly for <CODE>is_netscape</CODE> to output ``hi Mom'' while it was computing its value, thereby surprising
the <CODE>if</CODE> statement! Conversely, any value returned by an HTML component would
typically be discarded by the &lt;&amp; &amp;&gt; tag that invoked it.


<P>

<P>
<HR>
<H1><A NAME="top_level_components">TOP-LEVEL COMPONENTS

</A></H1>
The first component invoked for a page (the ``top-level component'')
resides within the DocumentRoot and is chosen based on the URL. For
example:


<P>

<PRE>    http://www.foo.com/mktg/products?id=372
</PRE>

<P>

Apache resolves 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


<P>

<PRE>    $m-&gt;comp('/mktg/products', id=&gt;372)
</PRE>

<P>

This component might in turn call other components and execute some Perl
code, or it might be nothing more than static HTML.


<P>

<P>
<HR>
<H2><A NAME="dhandlers">dhandlers

</A></H2>
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 <EM>dhandler</EM> (``default handler''). If found, the dhandler is invoked and is expected to
use
<CODE>$m-&gt;dhandler_arg</CODE> 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.


<P>

Consider the following URL, in which <CODE>newsfeeds/</CODE> exists but not the subdirectory <CODE>LocalNews</CODE> nor the component <CODE>Story1</CODE>:


<P>

<PRE>    http://myserver/newsfeeds/LocalNews/Story1
</PRE>

<P>

In this case Mason constructs the following search path:


<P>

<PRE>    /newsfeeds/LocalNews/Story1         =&gt; no such thing
    /newsfeeds/LocalNews/dhandler       =&gt; no such thing
    /newsfeeds/dhandler                 =&gt; found! (search ends)
    /dhandler
</PRE>

<P>

The found dhandler would read ``LocalNews/Story1'' from
<CODE>$m-&gt;dhandler_arg</CODE> and use it as a retrieval key into a database of stories.


<P>

Here's how a simple /newsfeeds/dhandler might look:


<P>

<PRE>    &lt;&amp; header &amp;&gt;
    &lt;b&gt;&lt;% $headline %&gt;&lt;/b&gt;&lt;p&gt;
    &lt;% $body %&gt;
    &lt;&amp; footer &amp;&gt;
    
    &lt;%init&gt;
    my $arg = $m-&gt;dhandler_arg;                # get rest of path
    my ($section,$story) = split(&quot;/&quot;,$arg);    # split out pieces
    my $sth = $DBH-&gt;prepare
        (&quot;SELECT headline,body FROM news WHERE section='$section' AND story='$story'&quot;);
    my ($headline,$body) = $sth-&gt;fetchrow_array;
    return 404 if !$headline;                  # return &quot;not found&quot; if no such story
    &lt;/%init&gt;
</PRE>

<P>

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 <A HREF="././Admin.html#allowing_requests_for_directorie">Allowing requests for directories</A>.


<P>

A component or dhandler that does not want to handle a particular request
may defer control to the next dhandler by calling <CODE>$m-&gt;decline</CODE>.


<P>

The administrator can customize the file name used for dhandlers, or turn
off dhandlers entirely, with the <A HREF="./Interp.html#item_dhandler_name">dhandler_name</A> Interp parameter.


<P>

<P>
<HR>
<H2><A NAME="autohandlers">autohandlers

</A></H2>
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.


<P>

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
<CODE>$m-&gt;call_next</CODE> to transfer control to the original intended component. 


<P>

<CODE>$m-&gt;call_next</CODE> works just like <CODE>$m-&gt;comp</CODE> except that the component path and arguments are implicit. You can pass
additional arguments to
<CODE>$m-&gt;call_next</CODE>; 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.


<P>

Here is an autohandler that adds a common header and footer to each page
underneath its directory:


<P>

<PRE>    &lt;HTML&gt;
    &lt;HEAD&gt;&lt;TITLE&gt;McHuffy Incorporated&lt;/TITLE&gt;&lt;/HEAD&gt;
    &lt;BODY BGCOLOR=&quot;salmon&quot;&gt;
    
    &lt;% $m-&gt;call_next %&gt;
    
    &lt;HR&gt;
    Copyright 1999 McHuffy Inc.
    &lt;/BODY&gt;
    &lt;/HTML&gt;
</PRE>

<P>

Same idea, using components for the header/footer:


<P>

<PRE>    &lt;&amp; /shared/header &amp;&gt;
    &lt;% $m-&gt;call_next %&gt;
    &lt;&amp; /shared/footer &amp;&gt;
</PRE>

<P>

The next autohandler applies a filter to its pages, adding an absolute
hostname to relative image URLs:


<P>

<PRE>    &lt;% $m-&gt;call_next %&gt;
    
    &lt;%filter&gt;
    s{(&lt;img\s+src=\&quot;)/} {$1http://images.mysite.com/}ig;
    &lt;/%filter&gt;
</PRE>

<P>

Most of the time autohandler can simply call <CODE>$m-&gt;call_next</CODE>
without needing to know what the next component is. However, should you
need it, the component object is available from
<CODE>$m-&gt;fetch_next</CODE>. This is useful for calling the component manually, e.g. if you want to
suppress some original arguments or if you want to use <CODE>$m-&gt;scomp</CODE> to store and process the output.


<P>

What happens if more than one autohandler applies to a page? Prior to
version 0.85, only the most specific autohandler would execute. In 0.85 and
beyond each autohandler gets a chance to run. The top-most autohandler runs
first; each <CODE>$m-&gt;call_next</CODE> 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.


<P>

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, <A HREF="././Devel.html#object_oriented_techniques">Object-Oriented Techniques</A>.


<P>

The administrator can customize the file name used for autohandlers, or
turn off autohandlers entirely, with the <A HREF="./Interp.html#item_autohandler_name">autohandler_name</A>
Interp parameter.


<P>

<P>
<HR>
<H2><A NAME="dhandlers_vs_autohandlers">dhandlers vs. autohandlers

</A></H2>
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.


<P>

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.


<P>

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.


<P>

<P>
<HR>
<H1><A NAME="passing_parameters">PASSING PARAMETERS

</A></H1>
This section describes Mason's facilities for passing parameters to
components (either from HTTP requests or component calls) and for accessing
parameter values inside components.


<P>

<P>
<HR>
<H2><A NAME="in_component_calls">In Component Calls

</A></H2>
Any Perl data type can be passed in a component call:


<P>

<PRE>    &lt;&amp; /sales/header, s=&gt;'dog', l=&gt;[2,3,4], h=&gt;{a=&gt;7,b=&gt;8} &amp;&gt;
</PRE>

<P>

This command passes a scalar ($s), a list (@l), and a hash (%h). The list
and hash must be passed as references, but they will be automatically
dereferenced in the called component.


<P>

<P>
<HR>
<H2><A NAME="in_http_requests">In HTTP requests

</A></H2>
Consider a CGI-style URL with a query string:


<P>

<PRE>    http://www.foo.com/mktg/prods.html?str=dog&amp;lst=2&amp;lst=3&amp;lst=4
</PRE>

<P>

or an HTTP request with some POST content. Mason automatically parses the
GET/POST values and makes them available to the component as parameters.


<P>

<P>
<HR>
<H2><A NAME="accessing_parameters">Accessing Parameters

</A></H2>
Component parameters, whether they come from GET/POST or another component,
can be accessed in two ways.


<P>

1. Declared named arguments: Components can define an
<CODE>&lt;%args&gt;</CODE> section listing argument names, types, and default values. For example:


<P>

<PRE>    &lt;%args&gt;
    $a       
    @b       # a comment
    %c
</PRE>

<P>

<PRE>    # another comment
    $d=&gt;5
    $e=&gt;$d*2
    @f=&gt;('foo','baz')
    %g=&gt;(joe=&gt;1,bob=&gt;2)
    &lt;/%args&gt;
</PRE>

<P>

Here, <EM>$a</EM>, <EM>@b</EM>, and <EM>%c</EM> are required arguments; the component generates an error if the caller
leaves them unspecified. <EM>$d</EM>, <EM>$e</EM>, <EM>@f</EM> and <EM>%g</EM> are optional arguments; they are assigned the specified default values if
unspecified. All the arguments are available as lexically scoped (``my'')
variables in the rest of the component.


<P>

Arguments are separated by one or more newlines. Comments may be used at
the end of a line or on their own line.


<P>

Default expressions are evaluated in top-to-bottom order, and one
expression may reference an earlier one (as <CODE>$e</CODE> references
<CODE>$d</CODE> above).


<P>

Only valid Perl variable names may be used in <CODE>&lt;%args&gt;</CODE>
sections. Parameters with non-valid variable names cannot be pre-declared
and must be fetched manually out of the <CODE>%ARGS</CODE> hash (see
below). One common example of undeclarable parameters are the
``button.x/button.y'' parameters sent for a form submit.


<P>

2. <CODE>%ARGS</CODE> 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. <CODE>%ARGS</CODE> can be used with or without an
<CODE>&lt;%args&gt;</CODE> section, and its contents are unrelated to what you have declared in <CODE>&lt;%args&gt;</CODE>.


<P>

Here's how to pass all of a component's parameters to another component:


<P>

<PRE>    &lt;&amp; template, %ARGS &amp;&gt;
</PRE>

<P>

<P>
<HR>
<H2><A NAME="parameter_passing_examples">Parameter Passing Examples

</A></H2>
The following examples illustrate the different ways to pass and receive
parameters.


<P>

1. Passing a scalar <EM>id</EM> with value 5.


<P>

<PRE>  In a URL: /my/URL?id=5
  In a component call: &lt;&amp; /my/comp, id =&gt; 5 &amp;&gt;
  In the called component, if there is a declared argument named...
    $id, then $id will equal 5
    @id, then @id will equal (5)
    %id, then an error occurs
  In addition, $ARGS{id} will equal 5.
</PRE>

<P>

2. Passing a list <EM>colors</EM> with values red, blue, and green.


<P>

<PRE>  In a URL: /my/URL?colors=red&amp;colors=blue&amp;colors=green
  In an component call: &lt;&amp; /my/comp, colors =&gt; ['red', 'blue', 'green'] &amp;&gt;
  In the called component, if there is a declared argument named...
    $colors, then $colors will equal ['red', 'blue', 'green']
    @colors, then @colors will equal ('red', 'blue', 'green')
    %colors, then an error occurs
  In addition, $ARGS{colors} will equal ['red', 'blue', 'green'].
</PRE>

<P>

3. Passing a hash <EM>grades</EM> with pairs Alice =&gt; 92 and Bob =&gt; 87.


<P>

<PRE>  In a URL: /my/URL?grades=Alice&amp;grades=92&amp;grades=Bob&amp;grades=87
  In an component call: &lt;&amp; /my/comp, grades =&gt; {Alice =&gt; 92, Bob =&gt; 87} &amp;&gt;
  In the called component, if there is a declared argument named...
    $grades, then $grades will equal {Alice =&gt; 92, Bob =&gt; 87}
    @grades, then @grades will equal ('Alice', 92, 'Bob', 87)
    %grades, then %grades will equal (Alice =&gt; 92, Bob =&gt; 87)
  In addition, $ARGS{grades} will equal ['Alice',92,'Bob',87] in the
    URL case, or {Alice =&gt; 92, Bob =&gt; 87} in the component call case.
    (The discrepancy exists because, in a query string, there is no detectable
    difference between a list or hash.)
</PRE>

<P>

<P>
<HR>
<H2><A NAME="using_instead">Using @_ instead

</A></H2>
If you don't like named parameters, you can pass a traditional list of
ordered parameters:


<P>

<PRE>    &lt;&amp; /mktg/prods.html', 'dog', [2,3,4], {a=&gt;7,b=&gt;8} &amp;&gt;
</PRE>

<P>

and access them as usual through Perl's <CODE>@_</CODE> array:


<P>

<PRE>    my ($scalar, $listref, $hashref) = @_;
</PRE>

<P>

In this case no <CODE>&lt;%args&gt;</CODE> section is necessary.


<P>

We generally recommend named parameters for the benefits of readability,
syntax checking, and default value automation. However using
<CODE>@_</CODE> may be convenient for very small components, especially
subcomponents created with <CODE>&lt;%def&gt;</CODE>.


<P>

<P>
<HR>
<H1><A NAME="initialization_and_cleanup">INITIALIZATION AND CLEANUP

</A></H1>
The following sections contain blocks of Perl to execute at specific times.


<P>

<P>
<HR>
<H2><A NAME="e_lt_inite_gt_">&lt;%init&gt;

</A></H2>
This section contains initialization code that executes as soon as the
component is called. For example: checking that a user is logged in;
selecting rows from a database into a list; parsing the contents of a file
into a data structure.


<P>

Technically a &lt;<CODE>%init</CODE>&gt; block is equivalent to a &lt;<CODE>%perl</CODE>&gt;
block at the beginning of the component. However, there is an aesthetic
advantage of placing this block at the end of the component rather than the
beginning.


<P>

We've found that the most readable components (especially for
non-programmers) contain HTML in one continuous block at the top, with
simple substitutions for dynamic elements but no distracting blocks of Perl
code. At the bottom an &lt;<CODE>%init</CODE>&gt; block sets up the substitution variables. This organization allows
non-programmers to work with the HTML without getting distracted or
discouraged by Perl code. For example:


<P>

<PRE>    &lt;html&gt;
    &lt;head&gt;&lt;title&gt;&lt;% $headline %&gt;&lt;/title&gt;&lt;/head&gt;
    &lt;body&gt;
    &lt;h2&gt;&lt;% $headline %&gt;&lt;/h2&gt;
    By &lt;% $author %&gt;, &lt;% $date %&gt;&lt;p&gt;
    
    &lt;% $body %&gt;
    
    &lt;/body&gt;&lt;/html&gt;
</PRE>

<P>

<PRE>    &lt;%init&gt;
    # Fetch article from database
    my $dbh = DBI::connect ...;
    my $sth = $dbh-&gt;prepare(&quot;select * from articles where id = $article_id&quot;);
    my ($headline,$date,$author,$body) = $sth-&gt;fetchrow_array;
    # Massage the fields
    $headline = uc($headline);
    my ($year,$month,$day) = split('-',$date);
    $date = &quot;$month/$day&quot;;
    &lt;/%init&gt;
</PRE>

<P>

<PRE>    &lt;%args&gt;
    $article_id
    &lt;/%args&gt;
</PRE>

<P>

<P>
<HR>
<H2><A NAME="e_lt_cleanupe_gt_">&lt;%cleanup&gt;

</A></H2>
This section contains cleanup code that executes just before the component
exits. For example: closing a database connection or closing a file handle.


<P>

Technically a &lt;<CODE>%cleanup</CODE>&gt; block is equivalent to a &lt;<CODE>%perl</CODE>&gt; block at the end of the component. Since a component corresponds a
subroutine block, and since Perl is so darned good at cleaning up stuff at
the end of blocks,
&lt;<CODE>%cleanup</CODE>&gt; sections are rarely needed.


<P>

<P>
<HR>
<H2><A NAME="e_lt_oncee_gt_">&lt;%once&gt;

</A></H2>
This code executes once when the component is loaded. Variables declared in
this section can be seen in all of a component's code and persist for the
lifetime of the component.


<P>

Useful for declaring persistent component-scoped lexical variables
(especially objects that are expensive to create), declaring subroutines
(both named and anonymous), and initializing state.


<P>

This code does not run inside a request context. You cannot call components
or access <CODE>$m</CODE> from this section.


<P>

Normally this code will execute individually from every HTTP child that
uses the component. However, if the component is preloaded, this code will
only execute once in the parent. Unless you have total control over what
components will be preloaded, it is safest to avoid initializing variables
that can't survive a <CODE>fork(),</CODE> e.g. DBI handles. Use the
following trick to initialize such variables in the &lt;<CODE>%init</CODE>&gt;
section:


<P>

<PRE>    &lt;%once&gt;
    my $dbh;    # declare but don't assign
    ...
    &lt;/%once&gt;
</PRE>

<P>

<PRE>    &lt;%init&gt;
    if ($m-&gt;current_comp-&gt;first_time) {
        $dbh = DBI::connect ...
    }
    ...
    &lt;/%init&gt;
</PRE>

<P>

<P>
<HR>
<H2><A NAME="e_lt_sharede_gt_">&lt;%shared&gt;

</A></H2>
As with <CODE>&lt;%once&gt;</CODE>, variables declared in this section can be seen in all of a component's
code: the main component, subcomponents, and methods. However, the code
runs once per request (whenever the component is used) and its variables
last only til the end of the request.


<P>

Useful for initializing variables needed in, say, the main body and one
more subcomponents or methods. See <A HREF="././Devel.html#object_oriented_techniques">Object-Oriented Techniques</A> for an example of usage.


<P>

Avoid using <CODE>&lt;%shared&gt;</CODE> for side-effect code that needs to run at a predictable time during page
generation. You may assume only that
<CODE>&lt;%shared&gt;</CODE> runs just before the first code that needs it and runs at most once per
request. <CODE>&lt;%init&gt;</CODE> offers more a predictable execution time.


<P>

Any component with a <CODE>&lt;%shared&gt;</CODE> section incurs an extra performance penalty, because (as currently
implemented) 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
<CODE>&lt;%shared&gt;</CODE> when patently unnecessary, e.g. when an <CODE>&lt;%init&gt;</CODE> would work as well.


<P>

<P>
<HR>
<H1><A NAME="embedded_components">EMBEDDED COMPONENTS

</A></H1>
<P>
<HR>
<H2><A NAME="e_lt_def_i_name_e_gt_">&lt;%def <EM>name</EM>&gt;

</A></H2>
Each instance of this section creates a <EM>subcomponent</EM> embedded inside the current component. Inside you may place anything that a
regular component contains, with the exception of <CODE>&lt;%def&gt;</CODE>, <CODE>&lt;%method&gt;</CODE>,
<CODE>&lt;%once&gt;</CODE>, and <CODE>&lt;%shared&gt;</CODE> tags.


<P>

The <EM>name</EM> consists of characters in the set <CODE>[A-Za-z0-9._-]</CODE>. To call a subcomponent simply use its name in &lt;&amp; &amp;&gt; or <CODE>$m-&gt;comp</CODE>. A subcomponent can only be seen from the surrounding component.


<P>

If you define a subcomponent with the same name as a file-based component
in the current directory, the subcomponent takes precedence. You would 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. The author prefers to start subcomponent names with
``.''.


<P>

While inside a subcomponent, you may use absolute or relative paths to call
file-based components and also call any of your ``sibling'' subcomponents.


<P>

The lexical scope of a subcomponent is separate from the main component.
However a subcomponent can declare its own <CODE>&lt;%args&gt;</CODE> section and have relevant values passed in. You can also use a <CODE>&lt;%shared&gt;</CODE>
section to declare variables visible from both scopes.


<P>

In the following example, we create a ``.link'' subcomponent to produce a
standardized hyperlink:


<P>

<PRE>    &lt;%def .link&gt;
    &lt;font size=&quot;4&quot; face=&quot;Verdana,Arial,Helvetica&quot;&gt;
    &lt;a href=&quot;http://www.&lt;% $site %&gt;.com&quot;&gt;&lt;% $label %&gt;&lt;/a&gt;
    &lt;/font&gt;&lt;br&gt;
    &lt;%args&gt;
    $site
    $label=&gt;ucfirst($site)
    &lt;/%args&gt;
    &lt;/%def&gt;
    
    Visit these sites:
    &lt;ul&gt;
    &lt;li&gt;&lt;&amp; .link, site=&gt;'yahoo' &amp;&gt;&lt;br&gt;
    &lt;li&gt;&lt;&amp; .link, site=&gt;'cmp', label=&gt;'CMP Media' &amp;&gt;&lt;br&gt;
    &lt;li&gt;&lt;&amp; .link, site=&gt;'excite' &amp;&gt;
    &lt;/ul&gt;
</PRE>

<P>

<P>
<HR>
<H2><A NAME="e_lt_method_i_name_e_gt_">&lt;%method <EM>name</EM>&gt;

</A></H2>
Each instance of this section creates a <EM>method</EM> 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.


<P>

There are two ways to call a method. First, via a path of the form
``comp:method'':


<P>

<PRE>    &lt;&amp; /foo/bar:method1 &amp;&gt;
</PRE>

<P>

<PRE>    $m-&gt;comp('/foo/bar:method1');
</PRE>

<P>

Second, via the call_method component method:


<P>

<PRE>    my $comp = $m-&gt;fetch_comp('/foo/bar');
    ...
    $comp-&gt;call_method('method1');
</PRE>

<P>

Methods are commonly used in conjunction with autohandlers to make
templates more flexible. See <A HREF="././Devel.html#object_oriented_techniques">Object-Oriented Techniques</A> for more information.


<P>

<P>
<HR>
<H1><A NAME="flags_and_attributes">FLAGS AND ATTRIBUTES

</A></H1>
The &lt;<CODE>%flags</CODE>&gt; and &lt;<CODE>%attr</CODE>&gt; sections consist of key/value pairs, one per line, joined by '=&gt;'. The
key and value in each pair must be valid Perl hash keys and values
respectively. An optional comment may follow each line.


<P>

<P>
<HR>
<H2><A NAME="e_lt_flagse_gt_">&lt;%flags&gt;

</A></H2>
Use this section to set official Mason flags that affect the current
component's behavior.


<P>

Currently there is only one flag, &lt;tt&gt;inherit&lt;/tt&gt;, which specifies the component's &lt;i&gt;parent&lt;/i&gt; in the form of a relative or absolute component path. A component
inherits methods and attributes from its parent; see <A HREF="././Devel.html#object_oriented_techniques">Object-Oriented Techniques</A> for examples.


<P>

<PRE>    &lt;%flags&gt;
    inherit=&gt;'/site_handler'
    &lt;/%flags&gt;
</PRE>

<P>

<P>
<HR>
<H2><A NAME="e_lt_attre_gt_">&lt;%attr&gt;

</A></H2>
Use this section to assign static key/value attributes that can be queried
from other components.


<P>

<PRE>    &lt;%attr&gt;
    color=&gt;'blue'
    fonts=&gt;[qw(arial geneva helvetica)]
    &lt;/%attr&gt;
</PRE>

<P>

To query an attribute of a component, use the <CODE>attr</CODE> method:


<P>

<PRE>    my $color = $comp-&gt;attr('color')
</PRE>

<P>

where <CODE>$comp</CODE> is a component object.


<P>

Mason evaluates attribute values once when loading the component. This
makes them faster but less flexible than methods.


<P>

<P>
<HR>
<H1><A NAME="filtering">FILTERING

</A></H1>
This section describes several ways to apply filtering functions over the
results of the current component. By separating out and hiding a filter
that, say, changes HTML in a complex way, we allow non-programmers to work
in a cleaner HTML environment.


<P>

<P>
<HR>
<H2><A NAME="_lt_filter_gt_section">&lt;%filter&gt; section

</A></H2>
The <CODE>&lt;%filter&gt;</CODE> section allows you to arbitrarily filter the output of the current
component. Upon entry to this code, <CODE>$_</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.


<P>

This simple filter converts the component output to UPPERCASE:


<P>

<PRE>    &lt;%filter&gt;
    tr/a-z/A-Z/
    &lt;/%filter&gt;
</PRE>

<P>

The following navigation bar uses a filter to ``unlink'' and highlight the
item corresponding to the current page:


<P>

<PRE>    &lt;a href=&quot;/&quot;&gt;Home&lt;/a&gt; | &lt;a href=&quot;/products/&quot;&gt;Products&lt;/a&gt; | 
    &lt;a href=&quot;/bg.html&quot;&gt;Background&lt;/a&gt; | &lt;a href=&quot;/finance/&quot;&gt;Financials&lt;/a&gt; | 
    &lt;a href=&quot;/support/&quot;&gt;Tech Support&lt;/a&gt; | &lt;a href=&quot;/contact.html&quot;&gt;Contact Us&lt;/a&gt;
</PRE>

<P>

<PRE>    &lt;%filter&gt;
    my $uri = $r-&gt;uri;
    s{&lt;a href=&quot;$uri/?&quot;&gt;(.*?)&lt;/a&gt;} {&lt;b&gt;$1&lt;/b&gt;}i;
    &lt;/%filter&gt;
</PRE>

<P>

This allows a designer to code such a navigation bar intuitively without <CODE>if</CODE> 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.


<P>

<P>
<HR>
<H2><A NAME="_m_call_self_command">$m->call_self command

</A></H2>
This command allows you to filter both the output and the return value of
the current component. It is fairly advanced; for most purposes the
<CODE>&lt;%filter&gt;</CODE> tag above will be sufficient and simpler.


<P>

<CODE>$m-&gt;call_self</CODE> takes two arguments. The first is a scalar reference and will be populated
with the component output. The second is either a scalar or list reference
and will be populated with the component return value; the type of
reference determines whether the component will be called in scalar or list
context. Both of these arguments are optional; you may pass undef if you
don't care about one of them.


<P>

<CODE>$m-&gt;call_self</CODE> acts like a <CODE>fork()</CODE> in the sense that it will return twice with
different values. When it returns 0, you allow control to pass through to
the rest of your component. When it returns 1, that means the component has
finished and you can begin filtering the output and/or return value. (Don't
worry, it doesn't really do a fork! See next section for explanation.)


<P>

The following examples would generally appear at the top of a <CODE>&lt;%init&gt;</CODE>
section. Here is a no-op <CODE>$m-&gt;call_self</CODE> that leaves the output and return value untouched:


<P>

<PRE>    if ($m-&gt;call_self(my \$output, my \$retval)) {  # assumes Perl 5.005 or greater
        $m-&gt;out($output);
        return $retval;
    }
</PRE>

<P>

Here is a simple output filter that makes the output all uppercase, just
like the <CODE>&lt;%filter&gt;</CODE> example above. Note that we ignore both the original and the final return
value.


<P>

<PRE>    if ($m-&gt;call_self(my \$output, undef)) {
        $m-&gt;out(uc($output));
        return;
    }
</PRE>

<P>

<CODE>$m-&gt;call_self</CODE> can even convert output to a return value or vice versa. In the next
component we provide a nice friendly format for non-programmers to
represent data with, and use a filter to construct and return a
corresponding Perl data structure from it:


<P>

<PRE>    # id        lastname        firstname
    59286       Sherman         Karen
    31776       Dawson          Robert
    29482       Lee             Brenda
    ...
</PRE>

<P>

<PRE>    &lt;%init&gt;
    if ($m-&gt;call_self(my \$output, undef)) {
        foreach (split(&quot;\n&quot;,$output)) {
            next if /^#/ || !/\S/;
            my @vals = split(/\s+/);
            push(@people,{id=&gt;$vals[0],last=&gt;$vals[1],first=&gt;$vals[2]});
        }
        return @people;
    }
    &lt;/%init&gt;
</PRE>

<P>

Now we can get a list of hashes directly from this component.    


<P>

<P>
<HR>
<H2><A NAME="how_filtering_works">How filtering works

</A></H2>
<CODE>$m-&gt;call_self</CODE> (and <CODE>&lt;%filter&gt;</CODE>, which is built on it) uses a bit of magic to accomplish everything in one
line. If you're curious, here's how it works:


<P>

o A component foo calls <CODE>$m-&gt;call_self</CODE> for the first time.


<P>

o <CODE>$m-&gt;call_self</CODE> sets an internal flag and calls foo again recursively, changing the output
stream to capture content into a buffer.


<P>

o foo again calls <CODE>$m-&gt;call_self</CODE> which, seeing the flag, returns 0 immediately.


<P>

o foo goes about its business and generates content into the <CODE>$m-&gt;call_self</CODE> buffer.


<P>

o When control is returned to <CODE>$m-&gt;call_self</CODE>, it places the content and return value in the references provided, and
returns 1.


<P>

<P>
<HR>
<H1><A NAME="other_syntax">OTHER SYNTAX

</A></H1>
<P>
<HR>
<H2><A NAME="e_lt_doce_gt_">&lt;%doc&gt;

</A></H2>
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 &lt;<CODE>%doc</CODE>&gt;
blocks to form a reference page.


<P>

Can also be used for in-line comments, though it is an admittedly
cumbersome comment marker. Another option is '%#':


<P>

<PRE>    %# this is a comment
</PRE>

<P>

These comments differ from HTML comments in that they do not appear in the
HTML.


<P>

<P>
<HR>
<H2><A NAME="e_lt_texte_gt_">&lt;%text&gt;

</A></H2>
Text in this section is passed through unmodified by Mason. Any Mason
syntax inside it is ignored. Useful, for example, when documenting Mason
itself from a component:


<P>

<PRE>    &lt;%text&gt;
    % This is an example of a Perl line.
    &lt;% This is an example of an expression block. %&gt;
    &lt;/%text&gt;
</PRE>

<P>

This works for almost everything, but doesn't let you output
&lt;/%text&gt; itself! When all else fails, use <CODE>$m-&gt;out</CODE>:


<P>

<PRE>    %$m-&gt;out('The tags are &lt;%text&gt; and &lt;/%text&gt;.');
</PRE>

<P>

<P>
<HR>
<H2><A NAME="escaping_expressions">Escaping expressions

</A></H2>
Mason has facilities for <EM>escaping</EM> the output from &lt;% %&gt; tags, on either a site-wide or a per-expression
basis.


<P>

Any &lt;% %&gt; expression may be terminated by a '|' and one or more
single-letter escape flags (plus arbitrary whitespace):


<P>

<PRE>    &lt;% $file_data |h %&gt;
</PRE>

<P>

The current valid flags are


<P>

<PRE>    h - escape for HTML ('&lt;' =&gt; '&amp;lt;', etc.)
    u - escape for URL query parameter (':' =&gt; '%3A', etc.) - all chars but [a-zA-Z0-9_.-]
    n - turn off default escape flags
</PRE>

<P>

The administrator may specify a set of default escape flags via the <A HREF="./Parser.html#item_default_escape_flags">default_escape_flags</A> Parser parameter. For example, if the administrator specifies


<P>

<PRE>    default_escape_flags=&gt;'h'
</PRE>

<P>

then all &lt;% %&gt; expressions will automatically be HTML-escaped. In this case you
would use the <CODE>n</CODE> flag to turn off HTML-escaping for a specific expression:


<P>

<PRE>    &lt;% $html_block |n %&gt;
</PRE>

<P>

Future Mason versions will allow user-defined and multi-letter escape
flags.


<P>

<P>
<HR>
<H2><A NAME="_at_end_of_line">\ at end of line

</A></H2>
A \ suppresses the newline before %-lines and section tags. In HTML
components, this is mostly useful for fixed width areas like &lt;PRE&gt;
tags, since browsers ignore white space for the most part. An example:


<P>

<PRE>    &lt;PRE&gt;
    foo
    %if ($b == 2) {
    bar
    %}
    baz
    &lt;/PRE&gt;
</PRE>

<P>

outputs


<P>

<PRE>    foo
    bar
    baz
</PRE>

<P>

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:


<P>

<PRE>    &lt;PRE&gt;
    foo\
    %if ($b == 2) {
    bar\
    %}
    baz
    &lt;/PRE&gt;
</PRE>

<P>

which prints


<P>

<PRE>    foobarbaz
</PRE>

<P>

The backslash has no special meaning outside this context. In particular,
you cannot use it to escape a newline before a plain text line.


<P>

<P>
<HR>
<H1><A NAME="data_caching">DATA CACHING

</A></H1>
Mason's <CODE>$m-&gt;cache</CODE> and <CODE>$m-&gt;cache_self</CODE> methods let components save and retrieve the results of computation for
improved performance. Anything may be cached, from a block of HTML to a
complex data structure.


<P>

Each component gets a private data cache. Except under special
circumstances, one component does not access another component's cache.
Each cached value may be set to expire under certain conditions or at a
certain time.


<P>

To use data caching, your Mason installation must be configured with a good
DBM package like Berkeley DB (DB_File) or GDBM. See
<STRONG><A HREF="././Admin.html#">HTML::Mason::Admin</A></STRONG> for more information.


<P>

<P>
<HR>
<H2><A NAME="basic_usage">Basic Usage

</A></H2>
Here's the typical usage of <CODE>$m-&gt;cache</CODE>:


<P>

<PRE>  my $result = $m-&gt;cache(action=&gt;'retrieve');
  if (!defined($result)) {
      ... compute $result&gt; ...
      $m-&gt;cache(action=&gt;'store', value=&gt;$result);
  }
</PRE>

<P>

The first <CODE>$m-&gt;cache</CODE> call attempts to retrieve this component's cache value. If the value is
available it is placed in <CODE>$result</CODE>. If the value is not available, <CODE>$result</CODE> is computed and stored in the cache by the second <CODE>$m-&gt;cache</CODE> call.


<P>

The default action for <CODE>$m-&gt;cache</CODE> is 'retrieve', so the first line can be written as


<P>

<PRE>  my $result = $m-&gt;cache;
</PRE>

<P>

<P>
<HR>
<H2><A NAME="multiple_keys_values">Multiple Keys/Values

</A></H2>
A cache file can store multiple keys and values. A value can be a scalar,
list reference, or hash reference:


<P>

<PRE>  $m-&gt;cache(action=&gt;'store',key=&gt;'name',value=&gt;$name);
  $m-&gt;cache(action=&gt;'store',key=&gt;'friends',value=&gt;\@lst);
  $m-&gt;cache(action=&gt;'store',key=&gt;'map',value=&gt;\%hsh);
</PRE>

<P>

The key defaults to 'main' when unspecified, as in the first example above.


<P>

Mason uses the <STRONG>MLDBM</STRONG> package to store and retrieve from its cache files, meaning that Mason can
cache arbitrarily deep data structures composed of lists, hashes, and
simple scalars.


<P>

<P>
<HR>
<H2><A NAME="expiration">Expiration

</A></H2>
Typical cache items have a useful lifetime after which they must expire.
Mason supports three types of expiration:


<P>

<DL>
<DT><STRONG><A NAME="item_By_Time">By Time

</A></STRONG><DD>
(e.g. the item expires in an hour, or at midnight). To expire an item by
time, pass one of these options to the 'store' action.


<P>

<EM>expire_at</EM>: takes an absolute expiration time, in Perl <CODE>time()</CODE> format
(number of seconds since the epoch)


<P>

<EM>expire_in</EM>: takes a relative expiration time of the form ``&lt;num&gt;&lt;unit&gt;'',
where &lt;num&gt; is a positive number and &lt;unit&gt; is one of seconds,
minutes, hours, days, weeks, months, years, or any reasonable abbreviation
thereof (m=month, min=minute). E.g. ``10min'', ``1hour''.


<P>

<EM>expire_next</EM>: takes a string, either 'hour' or 'day'. It indicates an expiration time
at the top of the next hour or day.


<P>

Examples:


<P>

<PRE>    $m-&gt;cache(action=&gt;'store', expire_in=&gt;'2 hours');
    $m-&gt;cache(action=&gt;'store', expire_next=&gt;'hour');
</PRE>

<P>

<DT><STRONG><A NAME="item_By_Condition">By Condition

</A></STRONG><DD>
(e.g. the item expires if a certain file or database table changes). To
expire an item based on events rather than current time, pass the
'expire_if' option to the 'retrieve' action.


<P>

<EM>expire_if</EM>: calls a given anonymous subroutine and expires if the subroutine returns
a non-zero value. The subroutine is called with one parameter, the time
when the cache value was last written.


<P>

Example:


<P>

<PRE>    # expire the cache if 'myfile' is newer
    $m-&gt;cache(action =&gt; 'retrieve',
          expire_if =&gt; sub { (stat 'myfile')[9] &gt; shift });
</PRE>

<P>

<DT><STRONG><A NAME="item_By_Explicit_Action">By Explicit Action

</A></STRONG><DD>
(e.g. a shell command or web interface is responsible for explicitly
expiring the item) To expire an item from a Perl script, for any component,
use <STRONG>access_data_cache</STRONG>. It takes the same arguments as
<CODE>$m-&gt;cache</CODE> plus one additional argument, cache_file. See the administration manual for
details on where cache files are stored and how they are named.


<P>

<PRE>    use HTML::Mason::Utils 'access_data_cache';
    access_data_cache (cache_file=&gt;'/usr/local/mason/cache/foo+2fbar',
                       action=&gt;'expire' [, key=&gt;'fookey']);
</PRE>

<P>

The 'expire' action can also take multiple keys (as a list reference); this
can be used in conjunction with the 'keys' action to expire all keys
matching a particular pattern.


<P>

<PRE>    use HTML::Mason::Utils 'access_data_cache';
    my @keys = access_data_cache (cache_file=&gt;'/usr/local/mason/cache/foo+2fbar',
                                  action=&gt;'keys');
    access_data_cache (cache_file=&gt;'/usr/local/mason/cache/foo+2fbar',
                       action=&gt;'expire', key=&gt;[grep(/^sales/,@keys)]);
</PRE>

<P>

</DL>
<P>
<HR>
<H2><A NAME="busy_locks">Busy Locks

</A></H2>
The code shown in ``Basic Usage'' above,


<P>

<PRE>  my $result = $m-&gt;cache(action=&gt;'retrieve');
  if (!defined($result)) {
      ... compute $result ...
      $m-&gt;cache(action=&gt;'store', value=&gt;$result);
  }
</PRE>

<P>

can suffer from a kind of race condition for caches that are accessed
frequently and take a long time to recompute.


<P>

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!


<P>

The solution here is to have the first process notify the others that it
has started recomputing. This can be accomplished with the busy_lock flag:


<P>

<PRE>  my $result = $m-&gt;cache(action=&gt;'retrieve',busy_lock=&gt;'10sec',...);
</PRE>

<P>

With this flag, the first process sets a lock in the cache that effectively
says ``I'm busy recomputing his value, don't bother.'' Subsequent processes
see the lock and return the old value. The lock is good for 10 seconds (in
this case) and is ignored after that. Thus the time value you pass to
busy_lock indicates how long you're willing to allow this component to use
an expired cache value.


<P>

Would some of your caches benefit from busy locks? One way to find out is
to turn on cache logging in the Mason system logs. If you see large
clusters of writes to the same cache in a short time span, then you might
want to use busy locks when writing to that cache.


<P>

<P>
<HR>
<H2><A NAME="keeping_in_memory">Keeping In Memory

</A></H2>
The keep_in_memory flag indicates that the cache value should be kept in
memory after it is stored or retrieved. Since every child process will
store its own copy, this flag should be used only for small, frequently
retrieved cache values. If used, this flag should be passed to both the
store and retrieve commands.


<P>

<P>
<HR>
<H2><A NAME="caching_all_output">Caching All Output 

</A></H2>
Occasionally you will need to cache the complete output of a component. One
way to accomplish this is to replace the component with a placeholder that
simply calls the component, then caches and prints the result. For example,
if the component were named ``foo'', we might rename it to ``foo_main'' and
put this component in its place:


<P>

<PRE>    &lt;% $foo_out %&gt;
    &lt;%init&gt;
        my $foo_out;
        if (!defined ($foo_out = $m-&gt;cache)) {
            $m-&gt;comp('foo_main', STORE=&gt;\$foo_out);
            $m-&gt;cache(action=&gt;'store',
                  expire_in=&gt;'3 hours', value=&gt;$foo_out);
        }
    &lt;/%init&gt;
</PRE>

<P>

This works, but is cumbersome. Mason offers a better shortcut: the
<CODE>$m-&gt;cache_self</CODE> command that lets a component cache it's own output and eliminates the need
for a dummy component. It is typically used right at the top of a <CODE>&lt;%init%&gt;</CODE> section:


<P>

<PRE>    &lt;%init&gt;
        return if $m-&gt;cache_self(expire_in=&gt;'3 hours'[, key=&gt;'fookey']);
        ... &lt;rest of init&gt; ...
    &lt;/%init&gt;
</PRE>

<P>

<CODE>$m-&gt;cache_self</CODE> is built on top of <CODE>$m-&gt;cache</CODE>, so it inherits all the expiration options described earlier. <CODE>$m-&gt;cache_self</CODE> can also cache a component's return value; see the reference for details.


<P>

<P>
<HR>
<H2><A NAME="guarantees_or_lack_thereof_">Guarantees (or lack thereof)

</A></H2>
Mason will make a best effort to cache data until it expires, but will not
guarantee it. The data cache is not a permanent reliable store in itself;
you should not place in the cache critical data (e.g. user session
information) that cannot be regenerated from another source such as a
database. You should write your code as if the cache might disappear at any
time. In particular,


<P>

o If the 'store' action cannot get a write lock on the cache, it simply
fails quietly.


<P>

o If the 'retrieve' action cannot get a shared lock on the cache, it simply
fails quietly. (This is much more rare.)


<P>

o Your Mason administrator will be required to remove cache files
periodically when they get too large; this can happen any time.


<P>

On the other hand, expiration in its various forms is guaranteed, because
Mason does not want you to rely on bad data to generate your content. If
you use the 'expire' action and Mason cannot get a write lock, it will
repeat the attempt several times and finally die with an error.


<P>

<P>
<HR>
<H1><A NAME="sending_http_headers">SENDING HTTP HEADERS

</A></H1>
Mason automatically sends HTTP headers via $r-&gt;send_http_header. It
tries to delay sending headers till the last possible moment, to give
components a chance to affect headers (using $r-&gt;header_out,
$r-&gt;content_type, etc.) It won't send headers if they've already been
sent manually.


<P>

To determine the exact header behavior on your system, you need to know
whether your server's <A HREF="././Interp.html#item_out_mode">out_mode</A> is 'batch' (meaning all output is buffered until the end) or 'stream' (all
output is sent immediately). Your administrator should have this
information. If your administrator doesn't know then it is probably
'batch', the default.


<P>

In batch mode the header situation is extremely simple: Mason waits until
the very end of the request to send headers. Any component can modify or
augment the headers.


<P>

In stream mode the header situation is more complex. Mason will send
headers just before sending the first non-whitespace output. Any initial
whitespace output is buffered up until after headers are sent. This means
that if you want to affect the headers in stream mode, you must do so
before any component sends non-whitespace output. Generally this takes
place in an <CODE>&lt;%init&gt;</CODE> section.


<P>

For example, the following top-level component calls another component to
see whether the user has a cookie; if not, it inserts a new cookie into the
header.


<P>

<PRE>    &lt;%init&gt;
    my $cookie = $m-&gt;comp('/shared/get_user_cookie');
    if (!$cookie) {
        $cookie = new CGI::Cookie (...);
        $r-&gt;headers_out-&gt;add('Set-cookie' =&gt; $cookie);  
    }
    ...
    &lt;/%init&gt;
</PRE>

<P>

In batch mode this code will always work. In stream mode this code will
work as long as <EM>get_user_cookie</EM> doesn't output anything besides whitespace (and given its functional
nature, it shouldn't).


<P>

The administrator can turn off automatic header sending via the
<A HREF="./ApacheHandler.html#item_auto_send_headers">auto_send_headers</A> ApacheHandler parameter.


<P>

Note to pre-0.8 users: the mc_suppress_http_header command is no longer
needed. For backwards compatibility, mc_suppress_http_header is still
defined but does nothing.


<P>

(Rationale: By the nature of HTTP headers mc_suppress_http_header was only
useful up until the first bytes of content were sent. Since Mason now waits
that long to send headers anyway, there is never any justification for
suppressing headers.)


<P>

<P>
<HR>
<H1><A NAME="using_the_perl_debugger">USING THE PERL DEBUGGER

</A></H1>
The Perl debugger is an indispensable tool for identifying and fixing bugs
in Perl programs. Unfortunately, in a mod_perl environment one is normally
unable to use the debugger since programs are run from a browser. Mason
removes this limitation by optionally creating a <EM>debug
file</EM> for each page request, allowing the request to be replayed from the command
line or Perl debugger.


<P>

Note: in early 1999 a new module, Apache::DB, was released that makes it
substantially easier to use the Perl debugger directly in conjunction with
a real Apache server. Since this mechanism is still new, we continue to
support Mason debug files, and there may be reasons to prefer Mason's
method (e.g. no need to start another Apache server). However we
acknowledge that Apache::DB may eventually eliminate the need for debug
files. For now we encourage you to try both methods and see which one works
best.


<P>

<P>
<HR>
<H2><A NAME="using_debug_files">Using debug files

</A></H2>
Here is a typical sequence for debugging a Mason page:


<P>

<OL>
<LI><STRONG><A NAME="item_Find_the_debug_file_"> Find the debug file:

</A></STRONG>
When Mason is running in debug mode, requests generate ``debug files'',
cycling through filenames ``1'' through ``20''. To find a request's debug
file, simply do a ``View Source'' in your browser after the request and
look for a comment like this at the very top:


<P>

<PRE>    &lt;!--
    Debug file is '3'.
    Full debug path is '/usr/local/mason/debug/anon/3'.
    --&gt;
</PRE>

<P>

<LI><STRONG><A NAME="item_Run_the_debug_file_"> Run the debug file:

</A></STRONG>
Debug files basically contain two things: a copy of the entire HTTP request
(serialized with <STRONG>Data::Dumper</STRONG>), and all the plumbing needed to route that request through Mason. In
other words, if you simply run the debug file like this:


<P>

<PRE>    perl /usr/local/mason/debug/anon/3
</PRE>

<P>

you should see the HTTP headers and content that the component would
normally send to the browser.


<P>

<LI><STRONG><A NAME="item_Debug_the_debug_file_"> Debug the debug file:

</A></STRONG>
Now you merely add a <CODE>-d</CODE> option to run the debug file in Perl's debugger -- at which point you have
to deal the problem of anonymous subroutines.


<P>

Mason compiles components down to anonymous subroutines which are not
easily breakpoint'able (Perl prefers line numbers or named subroutines).
Therefore, immediately before each component call, Mason calls a nonce
subroutine called <CODE>debug_hook</CODE> just so you can breakpoint it like this:


<P>

<PRE>    b HTML::Mason::Request::debug_hook
</PRE>

<P>

debug_hook is called with the component name as the second parameter so
that you can also breakpoint specific components using a conditional on
$_[1]:


<P>

<PRE>    b HTML::Mason::Request::debug_hook $_[1] =~ /component name/
</PRE>

<P>

You can avoid all that typing by adding the following to your ~/.perldb
file:


<P>

<PRE>    # Perl debugger aliases for Mason
    $DB::alias{mb} = 's/^mb\b/b HTML::Mason::Request::debug_hook/';
</PRE>

<P>

which reduces the previous examples to just: 


<P>

<PRE>    mb
    mb $_[1] =~ /component name/
</PRE>

<P>

</OL>
The use of debug files opens lots of other debugging options. For instance,
you can read a debug file into the Emacs editor, with its nifty interface
to Perl's debugger. This allows you to set break points visually or (in
trace mode) watch a cursor bounce through your code in single-step or
continue mode.


<P>

<P>
<HR>
<H2><A NAME="specifying_when_to_create_debug_">Specifying when to create debug files

</A></H2>
Details about configuring debug mode can be found in
<STRONG><A HREF="././Admin.html#">HTML::Mason::Admin</A></STRONG>. In particular, the administrator must decide which of three debugging
modes to activate:


<P>

<STRONG>never</STRONG> (no debug files)


<P>

<STRONG>always</STRONG> (create debug files for each request)


<P>

<STRONG>error</STRONG> (only generate a debug file when an error occurs)


<P>

<P>
<HR>
<H2><A NAME="how_debug_files_work">How debug files work

</A></H2>
To create a debug file, Mason calls almost every one of the mod_perl API
methods (<CODE>$r-&gt;xxx</CODE>), trapping its result in a hash. That hash is then serialized by
Data::Dumper and output into a new debug file along with some surrounding
code.


<P>

When the debug file is executed, a new object is created of the class
``HTML::Mason::FakeApache'', passing the saved hash as initialization. The
FakeApache object acts as a fake <CODE>$r</CODE>, responding to each method by getting or setting data in its hash. For
most purposes it is indistinguishable from the original <CODE>$r</CODE> except that print methods go to standard output. The debug file then
executes your <CODE>handler()</CODE>
function with the simulated <CODE>$r</CODE>.


<P>

<P>
<HR>
<H2><A NAME="when_debug_files_don_t_work">When debug files don't work

</A></H2>
The vast majority of mod_perl API methods are simple get/set functions
(e.g. <CODE>$r-&gt;uri</CODE>, <CODE>$r-&gt;content_type</CODE>) which are easy to simulate. Many pages only make use of these methods and
can be successfully simulated in debug mode.


<P>

However, a few methods perform tasks requiring the presence of a true
Apache server. These cannot be properly simulated. Some, such as
<CODE>log_error</CODE> and <CODE>send_cgi_header</CODE>, are generally tangential to the debugging effort; for these Mason simply
returns without doing anything and hopes for the best. Others, such as <CODE>internal_redirect</CODE>
and <CODE>lookup_uri</CODE>, perform such integral functions that they cannot be ignored, and for
these FakeApache aborts with an error. This category includes any method
call expected to return an Apache::Table object.


<P>

In addition, FakeApache is playing something of a catch-up game: every time
a new mod_perl release comes out with new API methods, those methods will
not be recognized by FakeApache until it is updated in the next Mason
release.


<P>

The combination of these problems and the existence of the new Apache::DB
package may eventually lead us to stop further work on FakeApache/debug
files. For now, though, we'll continue to support them as best we can.


<P>

<P>
<HR>
<H1><A NAME="using_the_perl_profiler">USING THE PERL PROFILER

</A></H1>
Debug files, mentioned in the previous section, can be used in conjunction
with Devel::DProf to profile a web request.


<P>

To use profiling, pass the <CODE>-p</CODE> flag to the debug file:


<P>

<PRE>    % ./3 -p
</PRE>

<P>

This executes the debug file under Devel::DProf and, for convenience, runs
dprofpp. If you wish you can rerun dprofpp with your choice of options.


<P>

Because components are implemented as anonymous subroutines, any time spent
in components would normally be reported under an unreadable label like
<CODE>CODE(0xb6cbc).</CODE> To remedy this, the <CODE>-p</CODE> flag automatically adjusts the tmon.out file so that components are
reported by their component paths.


<P>

Much of the time spent in a typical debug file is initialization, such as
loading Mason and other Perl modules. The effects of initialization can
swamp profile results and obscure the time actually spent in components.
One remedy is to run multiple iterations of the request inside the debug
file, thus reducing the influence of initialization time. Pass the number
of desired iterations via the <CODE>-r</CODE>
flag:


<P>

<PRE>    % ./3 -p -r20
</PRE>

<P>

Currently there are no special provisions for other profiling modules such
as Devel::SmallProf. You can try simply:


<P>

<PRE>    % perl -d:SmallProf ./3 -r20
</PRE>

<P>

However, this crashes on our Unix system -- apparently some bad interaction
between Mason and SmallProf -- so it is unsupported for now.


<P>

<P>
<HR>
<H1><A NAME="the_previewer">THE PREVIEWER

</A></H1>
Mason comes with a web-based debugging utility that lets you test your
components by throwing fake requests at them. Adjustable parameters
include: UserAgent, Time, HTTP Referer, O/S and so on. For example, imagine
a component whose color scheme is supposed to change each morning, noon,
and night. Using the Previewer, it would be simple to set the perceived
time forward 1,5 or 8 hours to test the component at various times of day.


<P>

The Previewer also provides a debug trace of a page, showing all components
being called and indicating the portion of HTML each component is
responsible for. For pages constructed from more than a few components,
these traces are quite useful for finding the component that is outputting
a particular piece of HTML.


<P>

Your administrator will give you the main Previewer URL, and a set of
preview ports that you will use to view your site under various conditions.
For the purpose of this discussion we'll assume the Previewer is up and
working, that the Previewer URL is <A
HREF="http://www.yoursite.com/preview,">http://www.yoursite.com/preview,</A>
and the preview ports are 3001 to 3005.


<P>

Take a look at the main Previewer page. The top part contains the most
frequently used options, such as time and display mode. The middle part
contains a table of your saved configurations; if this is your first time
using the Previewer, it will be empty. The bottom part contains less
frequently used options, such as setting the user agent and referer.


<P>

Try clicking ``Save''. This will save the displayed settings under the
chosen preview port, say 3001, and redraw the page. Under ``Saved Port
Settings'', you should see a single row showing this configuration. Your
configurations are saved permanently in a file. If a username/password is
required to access the Previewer, then each user has his/her own
configuration file.


<P>

The ``View'' button should display your site's home page. If not, then the
Previewer may not be set up correctly; contact your administrator or see
the Administrator's Guide.


<P>

Go back to the main Previewer page, change the display mode from ``HTML''
to ``debug'', change the preview port to 3002, and click ``Save'' again.
You should now see a second saved configuration.


<P>

Click ``View''. This time instead of seeing the home page as HTML, you'll
get a debug trace with several sections. The first section shows a numbered
hierarchy of components used to generate this page. The second section is
the HTML source, with each line annotated on the left with the number of
the component that generated it. Try clicking on the numbers in the first
section; this brings you to the place in the second section where that
component first appears. If there's a particular piece of HTML you want to
change on a page, searching in the annotated source will let you quickly
determine which component is responsible.


<P>

The final section of the debug page shows input and output HTTP headers.
Note that some of these are simulated due to your Previewer settings. For
example, if you specified a particular user agent in your Previewer
configuration, then the User-Agent header is simulated; otherwise it
reflects your actual browser.


<P>

<P>
<HR>
<H1><A NAME="object_oriented_techniques">OBJECT-ORIENTED TECHNIQUES

</A></H1>
Earlier you learned how to assign a common template to an entire hierarchy
of pages using <CODE>autohandlers</CODE>. The basic template looks like:


<P>

<PRE>    header HTML
    &lt;% $m-&gt;call_next %&gt;
    footer HTML
</PRE>

<P>

However, 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.


<P>

These issues can be addressed with the object-oriented style primitives
introduced in Mason 0.85.


<P>

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.


<P>

<P>
<HR>
<H2><A NAME="determining_inheritance">Determining inheritance

</A></H2>
Every component may have a single <EM>parent</EM>. The default parent is a component named <CODE>autohandler</CODE> 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.


<P>

You can use the <CODE>inherit</CODE> flag to override a component's parent:


<P>

<PRE>    &lt;%flags&gt;
    inherit=&gt;'/foo/bar'
    &lt;/%flags&gt;
</PRE>

<P>

If you specify undef as the parent, then the component inherits from no
one. This is how to suppress templates.


<P>

Currently there is no way to specify a parent dynamically at run-time, or
to specify multiple parents.


<P>

<P>
<HR>
<H2><A NAME="content_wrapping">Content wrapping

</A></H2>
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
<CODE>$m-&gt;call_next</CODE> passes control to the next component in the chain. This is the familiar
autohandler ``wrapping'' behavior, generalized for any number of
arbitrarily named templates.


<P>

<P>
<HR>
<H2><A NAME="accessing_methods_and_attributes">Accessing methods and attributes

</A></H2>
A template can access methods and/or attributes of the requested page.
First, use <CODE>$m-&gt;base_comp</CODE> to get a handle on the appropriate component:


<P>

<PRE>    my $self = $m-&gt;base_comp;
</PRE>

<P>

<CODE>$self</CODE> now refers to the component corresponding to the
requested page (the component at the end of the chain).


<P>

To access a method for the page, use <CODE>call_method</CODE>:


<P>

<PRE>    $self-&gt;call_method('header');
</PRE>

<P>

or alternatively a path of the form 'SELF:method':


<P>

<PRE>    &lt;&amp; SELF:header &amp;&gt;
    $m-&gt;comp('SELF:header')
</PRE>

<P>

In the context of a component path, SELF is shorthand for
<CODE>$m-&gt;base_comp</CODE>.


<P>

Each of the above 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:


<P>

<PRE>    if ($self-&gt;method_exists('header')) { ...
</PRE>

<P>

To defer to the method of your parent, use <CODE>parent</CODE>:


<P>

<PRE>    $m-&gt;current_comp-&gt;parent-&gt;call_method('header')
</PRE>

<P>

or alternatively a path of the form 'PARENT:method':


<P>

<PRE>    &lt;&amp; PARENT:header &amp;&gt;
    $m-&gt;comp('PARENT:header')
</PRE>

<P>

In the context of a component path, PARENT is shorthand for
<CODE>$m-&gt;current_comp-&gt;parent</CODE>.


<P>

The rules for attributes are similar. To access an attribute for the page,
use <CODE>attr</CODE>:


<P>

<PRE>    my $color = $self-&gt;attr('color')
</PRE>

<P>

This looks for an attribute named 'color' in the <CODE>$self</CODE>
component. If no such attribute exists, the chain of parents is searched
upwards, until ultimately an ``attribute not found'' error occurs. Use
'attr_exists' to avoid this error for questionable attributes:


<P>

<PRE>    if ($self-&gt;attr_exists('color')) { ...
</PRE>

<P>

<P>
<HR>
<H2><A NAME="sharing_data">Sharing data

</A></H2>
A component's main body and its methods occupy separate lexical scopes.
Variables declared, say, in the <CODE>&lt;%init&gt;</CODE> section of the main component cannot be seen from methods.


<P>

To share variables, declare them either in the <CODE>&lt;%once&gt;</CODE> or <CODE>&lt;%shared&gt;</CODE>
section. Both sections have an all-inclusive scope. The <CODE>&lt;%once&gt;</CODE>
section runs once when the component loads; its variables are persistent
for the lifetime of the component. The <CODE>&lt;%shared&gt;</CODE> 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.


<P>

In the following example, various sections of code require information
about the logged-in user. We use a <CODE>&lt;%shared&gt;</CODE> section to fetch these in a single request.


<P>

<PRE>    &lt;%attr&gt;
    title=&gt;sub { &quot;Account for $full_name&quot; }
    &lt;/%attr&gt;
    
    &lt;%method lefttoc&gt;
    &lt;i&gt;&lt;% $full_name %&gt;&lt;/i&gt;
    (&lt;a href=&quot;logout.html&quot;&gt;Log out&lt;/a&gt;)&lt;br&gt;
    ...
    &lt;/%method&gt;
    
    Welcome, &lt;% $fname %&gt;. Here are your options:
    
    &lt;%shared&gt;
    my $dbh = DBI::connect ...;
    my $user = $r-&gt;connection-&gt;user;
    my $sth = $dbh-&gt;prepare(&quot;select lname,fname, from users where user_id = '$user'&quot;);
    my ($lname,$fname) = $sth-&gt;fetchrow_array;
    my $full_name = &quot;$first $last&quot;;
    &lt;/%shared&gt;
</PRE>

<P>

<CODE>&lt;%shared&gt;</CODE> presents a good alternative to <CODE>&lt;%init&gt;</CODE> when data is needed across multiple scopes. Outside these situations, <CODE>&lt;%init&gt;</CODE> is preferred for its slightly greater speed and predictable execution
model.


<P>

<P>
<HR>
<H2><A NAME="example">Example

</A></H2>
Let's say we have three components:


<P>

<PRE>    /autohandler
    /products/autohandler
    /products/index.html
</PRE>

<P>

and that a request comes in for /products/index.html.


<P>

/autohandler contains a general template for the site, referring to a
number of standard methods and attributes for each page:


<P>

<PRE>    &lt;head&gt;
    &lt;title&gt;&lt;&amp; SELF:title &amp;&gt;&lt;/title&gt;
    &lt;/head&gt;
    &lt;body bgcolor=&quot;&lt;% $self-&gt;attr('bgcolor') %&gt;&quot;&gt;
    &lt;&amp; SELF:header &amp;&gt;
    &lt;table&gt;&lt;tr&gt;&lt;td&gt;
</PRE>

<P>

<PRE>    &lt;% $m-&gt;call_next %&gt;
</PRE>

<P>

<PRE>    &lt;/td&gt;&lt;/tr&gt;&lt;/table&gt;
    &lt;&amp; SELF:footer &amp;&gt;
    &lt;/body&gt;
</PRE>

<P>

<PRE>    &lt;%init&gt;
    my $self = $m-&gt;base_comp;
    ...
    &lt;/%init&gt;
</PRE>

<P>

<PRE>    &lt;%attr&gt;
    bgcolor=&gt;'white'
    &lt;/%attr&gt;
</PRE>

<P>

<PRE>    &lt;%method title&gt;
    McGuffey Inc.
    &lt;/%method&gt;
</PRE>

<P>

<PRE>    &lt;%method header&gt;
    &lt;h2&gt;&lt;&amp; SELF:title &amp;&gt;&lt;/h2&gt;&lt;p&gt;
    &lt;/%method&gt;
</PRE>

<P>

<PRE>    &lt;%method footer&gt;
    &lt;/%method&gt;
</PRE>

<P>

Notice how we provide defaults for each method and attribute, even if
blank.


<P>

/products/autohandler overrides some attributes and methods for the
/products section of the site.


<P>

<PRE>    &lt;%attr&gt;
    bgcolor=&gt;'beige'
    &lt;/%attr&gt;
    &lt;%method title&gt;
    McGuffey Inc.: Products
    &lt;/%method&gt;
</PRE>

<P>

<PRE>    &lt;% $m-&gt;call_next %&gt;
</PRE>

<P>

Note that this component, though it only defines attributes and methods,
must call <CODE>$m-&gt;call_next</CODE> if it wants the rest of the chain to run.


<P>

/products/index.html might override a few attributes, but mainly provides a
primary section for the body.


<P>

<P>
<HR>
<H1><A NAME="common_traps">COMMON TRAPS

</A></H1>
<DL>
<DT><STRONG><A NAME="item_Do_not_use_print_or_r_print">Do not use print or $r-&gt;print

</A></STRONG><DD>
Most Mason servers operate in ``batch'' mode, which means that output is
stored in a Mason buffer until the end of the request. Output sent via
print and $r-&gt;print, however, skips the Mason buffer and goes directly
to the client. This will result in output being printed out of order.
Always use <CODE>$m-&gt;out</CODE> instead of print/$r-&gt;print; it does the right thing with regards to
Mason buffering.


<P>

<DT><STRONG><A NAME="item_Do_not_call_r_content_or_new_">Do not call $r-&gt;content or ''new CGI``

</A></STRONG><DD>
Mason calls <CODE>$r-&gt;content</CODE> itself to read request input, emptying the input buffer and leaving a trap
for the unwary: subsequent calls to <CODE>$r-&gt;content</CODE> hang the server. This is a mod_perl ``feature'' that may be fixed in an
upcoming release.


<P>

For the same reason you should not create a CGI object like


<P>

<PRE>  my $query = new CGI;
</PRE>

<P>

when handling a POST; the CGI module will try to reread request input and
hang. Instead, create an empty object:


<P>

<PRE>  my $query = new CGI (&quot;&quot;);
</PRE>

<P>

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:


<P>

<PRE>  my $query = new CGI (\%ARGS);
</PRE>

<P>

</DL>
<P>
<HR>
<H1><A NAME="author">AUTHOR

</A></H1>
Jonathan Swartz, <A HREF="MAILTO:swartz@pobox.com">swartz@pobox.com</A>


<P>

<P>
<HR>
<H1><A NAME="see_also">SEE ALSO

</A></H1>
<A HREF="././Mason.html#">HTML::Mason</A>,
<A HREF="././Request.html#">HTML::Mason::Request</A>




<P>

</DL>
    </BODY>

    </HTML>