home *** CD-ROM | disk | FTP | other *** search
/ PC Professionell 2004 December / PCpro_2004_12.ISO / files / webserver / tsw / TSW_3.4.0.exe / Apache2 / perl / Devel.pod < prev    next >
Encoding:
Text File  |  2003-11-12  |  71.3 KB  |  2,092 lines

  1. =head1 NAME
  2.  
  3. HTML::Mason::Devel - Mason Developer's Manual
  4.  
  5. =head1 DESCRIPTION
  6.  
  7. This manual is written for content developers who know HTML and at
  8. least a little Perl. The goal is to write, run, and debug Mason
  9. components.
  10.  
  11. If you are the webmaster (or otherwise responsible for the Mason
  12. installation), you should also read L<the administrator's
  13. manual|HTML::Mason::Admin>. There you will find information about site
  14. configuration, performance tuning, component caching, and so on.
  15.  
  16. If you are a developer just interested in knowing more about Mason's
  17. capabilities and implementation, then L<the administrator's
  18. manual|HTML::Mason::Admin> is for you too.
  19.  
  20. We strongly suggest that you have a working Mason to play with as you
  21. work through these examples. Other component examples can be found in
  22. the C<samples/> directory.
  23.  
  24. While Mason can be used for tasks besides implementing a dynamic web
  25. site, that is what I<most> people want to do with Mason, and is thus
  26. the focus of this manual.
  27.  
  28. If you are planning to use Mason outside of the web, this manual will
  29. still be useful, of course.  Also make sure to read the L<running
  30. outside of mod_perl|HTML::Mason::Admin/running
  31. outside of mod_perl> section of the administrator's manual.
  32.  
  33. =head1 HOW TO USE THIS MANUAL
  34.  
  35. If you are just learning Mason and want to get started quickly, we
  36. recommend the following sections:
  37.  
  38. o L<What Are Components?|"What Are Components?">
  39.  
  40. o L<In-Line Perl Sections|"In-Line Perl Sections">
  41.  
  42. o L<Calling Components|"Calling Components">
  43.  
  44. o L<Top-Level Components|"Top-Level Components">
  45.  
  46. o L<Passing Parameters|"Passing Parameters">
  47.  
  48. o L<Initialization and Cleanup|"Initialization and Cleanup"> (mainly C<< <%init> >>)
  49.  
  50. o L<Web-Specific Features|"Web-Specific Features">
  51.  
  52. o L<Common Traps|"Common Traps">
  53.  
  54. =head1 WHAT ARE COMPONENTS?
  55.  
  56. The component - a mix of Perl and HTML - is Mason's basic building
  57. block and computational unit. Under Mason, web pages are formed by
  58. combining the output from multiple components.  An article page for a
  59. news publication, for example, might call separate components for the
  60. company masthead, ad banner, left table of contents, and article
  61. body. Consider this layout sketch:
  62.  
  63.     +---------+------------------+
  64.     |Masthead | Banner Ad        |
  65.     +---------+------------------+
  66.     |         |                  |
  67.     |+-------+|Text of Article ..|
  68.     ||       ||                  |
  69.     ||Related||Text of Article ..|
  70.     ||Stories||                  |
  71.     ||       ||Text of Article ..|
  72.     |+-------+|                  |
  73.     |         +------------------+
  74.     |         | Footer           |
  75.     +---------+------------------+
  76.  
  77. The top level component decides the overall page layout, perhaps with
  78. HTML tables. Individual cells are then filled by the output of
  79. subordinate components, one for the Masthead, one for the Footer,
  80. etc. In practice pages are built up from as few as one, to as many as
  81. twenty or more components.
  82.  
  83. This component approach reaps many benefits in a web environment. The
  84. first benefit is I<consistency>: by embedding standard design
  85. elements in components, you ensure a consistent look and make it
  86. possible to update the entire site with just a few edits. The second
  87. benefit is I<concurrency>: in a multi-person environment, one person
  88. can edit the masthead while another edits the table of contents.  A
  89. last benefit is I<reuseability>: a component produced for one site
  90. might be useful on another. You can develop a library of generally
  91. useful components to employ on your sites and to share with others.
  92.  
  93. Most components emit chunks of HTML. "Top level" components, invoked
  94. from a URL, represent an entire web page. Other, subordinate
  95. components emit smaller bits of HTML destined for inclusion in top
  96. level components.
  97.  
  98. Components receive form and query data from HTTP requests. When called
  99. from another component, they can accept arbitrary parameter lists just
  100. like a subroutine, and optionally return values.  This enables a type
  101. of component that does not print any HTML, but simply serves as a
  102. function, computing and returning a result.
  103.  
  104. Mason actually compiles components down to Perl subroutines, so you
  105. can debug and profile component-based web pages with standard Perl
  106. tools that understand the subroutine concept, e.g. you can use the
  107. Perl debugger to step through components, and B<Devel::DProf> to
  108. profile their performance.
  109.  
  110. =head1 IN-LINE PERL SECTIONS
  111.  
  112. Here is a simple component example:
  113.  
  114.     <%perl>
  115.     my $noun = 'World';
  116.     my @time = localtime;
  117.     </%perl>
  118.     Hello <% $noun %>,
  119.     % if ( $time[2] < 12 ) {
  120.     good morning.
  121.     % } else {
  122.     good afternoon.
  123.     % }
  124.  
  125. After 12 pm, the output of this component is:
  126.  
  127.     Hello World, good afternoon.
  128.  
  129. This short example demonstrates the three primary "in-line" Perl
  130. sections. In-line sections are generally embedded within HTML and
  131. execute in the order they appear. Other sections (C<< <%init> >>,
  132. C<< <%args> >>, etc.) are tied to component events like initialization,
  133. cleanup, and argument definition.
  134.  
  135. The parsing rules for these Perl sections are as follows:
  136.  
  137. =over
  138.  
  139. =item 1.
  140.  
  141. Blocks of the form <% xxx %> are replaced with the result of
  142. evaluating xxx as a single Perl expression.  These are often used for
  143. variable replacement. such as 'Hello, <% $name %>!'.
  144.  
  145. =item 2.
  146.  
  147. Lines beginning with a '%' character are treated as Perl.
  148.  
  149. =item 3.
  150.  
  151. Multiline blocks of Perl code can be inserted with the C<< <%perl> >>
  152. .. C<< </%perl> >> tag. The enclosed text is executed as Perl and the return
  153. value, if any, is discarded.
  154.  
  155. The C<< <%perl> >> tag, like all block tags in Mason, is
  156. case-insensitive. It may appear anywhere in the text, and may span any
  157. number of lines. C<< <%perl> >> blocks cannot be nested inside one
  158. another.
  159.  
  160. =back
  161.  
  162. =head2 Examples and Recommended Usage
  163.  
  164. B<% lines>
  165.  
  166. Most useful for conditional and loop structures - if, while, foreach,
  167. , etc. - as well as side-effect commands like assignments. Examples:
  168.  
  169. o Conditional code
  170.  
  171.     % my $ua = $r->header_in('User-Agent');
  172.     % if ($ua =~ /msie/i) {
  173.     Welcome, Internet Explorer users
  174.     ...
  175.     % } elsif ($ua =~ /mozilla/i) {
  176.     Welcome, Netscape users
  177.     ...
  178.     % }
  179.  
  180. o HTML list formed from array
  181.  
  182.     <ul>
  183.     % foreach $item (@list) {
  184.     <li><% $item %>
  185.     % }
  186.     </ul>
  187.  
  188. o HTML list formed from hash
  189.  
  190.     <ul>
  191.     % while (my ($key,$value) = each(%ENV)) {
  192.     <li>
  193.     <b><% $key %></b>: <% $value %>
  194.     % }
  195.     </ul>
  196.  
  197. o HTML table formed from list of hashes
  198.  
  199.     <table>
  200.     % foreach my $h (@loh) {
  201.     <tr>
  202.     <td><% $h->{foo} %></td>
  203.     <td bgcolor=#ee0000><% $h->{bar} %></td>
  204.     <td><% $h->{baz} %></td>
  205.     </tr>
  206.     % }
  207.     </table>
  208.  
  209. B<< <% xxx %> >>
  210.  
  211. Most useful for printing out variables, as well as more complex
  212. expressions. Examples:
  213.  
  214.   Dear <% $name %>: We will come to your house at <% $address %> in the
  215.   fair city of <% $city %> to deliver your $<% $amount %> dollar prize!
  216.  
  217.   The answer is <% ($y+8) % 2 %>.
  218.  
  219.   You are <% $age < 18 ? 'not' : '' %> permitted to enter this site.
  220.  
  221. B<< <%perl> xxx </%perl> >>
  222.  
  223. Useful for Perl blocks of more than a few lines.
  224.  
  225. =head1 MASON OBJECTS
  226.  
  227. This section describes the various objects in the Mason universe.
  228. If you're just starting out, all you need to worry about initially
  229. are the request objects.
  230.  
  231. =head2 Request Objects
  232.  
  233. Two global per-request objects are available to all components: $r and
  234. $m.
  235.  
  236. $r, the mod_perl request object, provides a Perl API to the current
  237. Apache request.  It is fully described in Apache.pod. Here is a
  238. sampling of methods useful to component developers:
  239.  
  240.     $r->uri             # the HTTP request URI
  241.     $r->header_in(..)   # get the named HTTP header line
  242.     $r->content_type    # set or retrieve content-type
  243.     $r->header_out(..)  # set or retrieve an outgoing header
  244.  
  245.     $r->content         # don't use this one! (see Tips and Traps)
  246.  
  247. $m, the Mason request object, provides an analogous API for
  248. Mason. Almost all Mason features not activated by syntactic tags are
  249. accessed via $m methods.  You'll be introduced to these methods
  250. throughout this document as they are needed.  For a description of all
  251. methods see B<L<HTML::Mason::Request|HTML::Mason::Request>>.
  252.  
  253. Because these are always set inside components, you should not ever
  254. define other variables with the same name, or else your code may fail
  255. in strange and mysterious ways.
  256.  
  257. =head2 Component Objects
  258.  
  259. Mason provides an object API for components, allowing you to query a
  260. component's various asociated files, arguments, etc. For a description
  261. of all methods see
  262. B<L<HTML::Mason::Component|HTML::Mason::Component>>.  Typically you
  263. get a handle on a component object from request methods like C<<
  264. $m->current_comp >> and C<< $m->fetch_comp >>.
  265.  
  266. Note that for many basic applications all you'll want to do with
  267. components is call them, for which no object method is needed. See
  268. next section.
  269.  
  270. =head2 System Objects
  271.  
  272. Many system objects share the work of serving requests in Mason:
  273. L<HTML::Mason::Lexer|HTML::Mason::Lexer>,
  274. L<HTML::Mason::Compiler|HTML::Mason::Compiler>,
  275. L<HTML::Mason::Interp|HTML::Mason::Interp>,
  276. L<HTML::Mason::Resolver|HTML::Mason::Resolver>,
  277. and L<HTML::Mason::ApacheHandler|HTML::Mason::ApacheHandler> are examples. The
  278. administrator creates these objects and provides parameters that shape
  279. Mason's behavior. As a pure component developer you shouldn't need to
  280. worry about or access these objects, but occasionally we'll mention a
  281. relevant parameter.
  282.  
  283. =head1 CALLING COMPONENTS
  284.  
  285. Mason pages often are built not from a single component, but from
  286. multiple components that call each other in a hierarchical fashion.
  287.  
  288. =head2 Components that output HTML
  289.  
  290. To call one component from another, use the <& &> tag:
  291.  
  292.     <& comp_path, [name=>value, ...] &>
  293.  
  294. =over
  295.  
  296. =item comp_path:
  297.  
  298. The component path. With a leading '/', the path is relative to the
  299. component root (L<comp_root|HTML::Mason::Params/comp_root>). Otherwise, it is relative to the
  300. location of the calling component.
  301.  
  302. =item name => value pairs:
  303.  
  304. Parameters are passed as one or more C<< name => value >> pairs,
  305. e.g. S<C<< player => 'M. Jordan' >>>.
  306.  
  307. =back
  308.  
  309. comp_path may be a literal string (quotes optional) or a Perl expression
  310. that evaluates to a string. To eliminate the need for quotes in most
  311. cases, Mason employs some magic parsing: If the first character is
  312. one of C<[\w/_.]>, comp_path is assumed to be a literal
  313. string running up to the first comma or &>. Otherwise, comp_path
  314. is evaluated as an expression.
  315.  
  316. Here are some examples:
  317.  
  318.     # relative component paths
  319.     <& topimage &>
  320.     <& tools/searchbox &>
  321.  
  322.     # absolute component path
  323.     <& /shared/masthead, color=>'salmon' &>
  324.  
  325.     # this component path MUST have quotes because it contains a comma
  326.     <& "sugar,eggs", mix=>1 &>
  327.  
  328.     # variable component path
  329.     <& $comp &>
  330.  
  331.     # variable component and arguments
  332.     <& $comp, %args &>
  333.  
  334.     # you can use arbitrary expression for component path, but it cannot
  335.     # begin with a letter or number; delimit with () to remedy this
  336.     <& (int(rand(2)) ? 'thiscomp' : 'thatcomp'), id=>123 &>
  337.  
  338. Several request methods also exist for calling components.  C<< $m->comp >>
  339. performs the equivalent action to <& &>:
  340.  
  341.     $m->comp('/shared/masthead', color=>'salmon');
  342.  
  343. C<< $m->scomp >> is like the sprintf version of C<< $m->comp >>: it returns
  344. the component output, allowing the caller to examine and modify it
  345. before printing:
  346.  
  347.     my $masthead = $m->scomp('/shared/masthead', color=>'salmon');
  348.     $masthead =~ ...;
  349.     $m->print($masthead);
  350.  
  351. =head2 Component Calls with Content
  352.  
  353. Components can be used to filter part of the page's content using an
  354. extended component syntax.
  355.  
  356.     <&| /path/to/comp &> this is the content </&>
  357.     <&| comp, arg1 => 'hi' &> filters can take arguments </&>
  358.     <&| comp &> content can include <% "tags" %> of all kinds </&>
  359.     <&| comp1 &> nesting is also <&| comp2 &> OK </&> </&>
  360.     <&| SELF:method1 &> subcomponents can be filters </&>
  361.  
  362. The filtering component can be called in all the same ways a normal
  363. component is called, with arguments and so forth.  The only difference
  364. between a filtering component and a normal component is that a
  365. filtering component is expected to fetch the content by calling
  366. $m->content and do something with it.
  367.  
  368. Here is an example of a component used for localization.  Its content
  369. is a series of strings in different languages, and it selects the
  370. correct one based on a global C<$lang> variable, which could be setup
  371. in a site-level autohandler.
  372.  
  373.    <&| /i18n/itext &>
  374.       <en>Hello, <% $name %> This is a string in English</en>
  375.       <de>Schoene Gruesse, <% $name %>, diese Worte sind auf Deutsch</de>
  376.       <pig>ellohay <% substr($name,2).substr($name,1,1).'ay' %>,
  377.       isthay isay igpay atinlay</pig>
  378.    </&>
  379.  
  380. Here is the F</i18n/itext> component:
  381.  
  382.    <% $text %>
  383.  
  384.    <%init>
  385.    # this assumes $lang is a global variable which has been set up earlier.
  386.    local $_ = $m->content;
  387.    my ($text) = m{<$lang>(.*?)</$lang>};
  388.    </%init>
  389.  
  390. You can explicitly check whether a component has passed content by
  391. checking the boolean C<< $m->has_content >>.  This allows you to write
  392. a component that will do different things depending on whether it was
  393. passed content. However, before overloading a component in this way,
  394. consider whether splitting the behavior into two distinct components
  395. would work as well.
  396.  
  397. If a normal component which does not call C<< $m->content >> is called
  398. with content, the content will not be output.
  399.  
  400. If you wrap a filtering component call around the entire component,
  401. the result will be functionally similar to a C<< <%filter> >> section.
  402. See also L<Filtering|"Filtering">.
  403.  
  404. =head2 Advanced Components Calls with Content
  405.  
  406. Internally C<< $m->content >> is implemented with a closure containing
  407. the part of the component which is the content.  In English, that
  408. means that any mason tags and perl code in the content are evaluated
  409. when C<< $m->content >> is called, and C<< $m->content >> returns the
  410. text which would have been output by mason.  Because the contents are
  411. evaluated at the time that C<< $m->content >> is called, one can write
  412. components which act as control structures or which output their
  413. contents multiple times with different values for the variables (can
  414. you say taglibs?).
  415.  
  416. The tricky part of using filter components as control structures is
  417. setting up variables which can be accessed from both the filter
  418. component and the content, which is in the component which calls the
  419. filter component.  The content has access to all variables in the
  420. surrounding component, but the filtering component does not.  There
  421. are two ways to do this: use global variables, or pass a reference to
  422. a lexical variable to the filter component.
  423.  
  424. Here is a simple example using the second method:
  425.  
  426.     % my $var;
  427.     <ol>
  428.     <&| list_items , list => \@items, var => \$var &>
  429.     <li> <% $var %>
  430.     </&>
  431.     </ol>
  432.  
  433. list_items component:
  434.  
  435.     <%args>
  436.     @list
  437.     $var
  438.     </%args>
  439.     % foreach (@list) {
  440.     % $$var = $_;  # $var is a reference
  441.     <% $m->content %>
  442.     % }
  443.  
  444. Using global variables can be somewhat simpler.  Below is the same
  445. example, with C<$var> defined as a global variable.  The site
  446. administrator must make sure that C<$var> is included in Mason's
  447. allow_globals parameter.  Local-izing C<$var> within the filter
  448. component will allow the list_items component to be nested.
  449.  
  450.     <ol>
  451.     <&| list_items, list => \@items &>
  452.     <li> <% $var %>
  453.     </&>
  454.     </ol>
  455.  
  456. list_items component:
  457.  
  458.     <%args>
  459.     @list
  460.     </%args>
  461.     % foreach (@list) {
  462.     % local $var = $_;
  463.     <% $m->content %>
  464.     % }
  465.  
  466. Besides remembering to include C<$var> in allow_globals, the
  467. developers should take care not to use that variable is other places
  468. where it might conflict with usage by the filter component.
  469. Local-izing $var will also provide some protection against using it in
  470. other places.
  471.  
  472. An even simpler method is to use the C<$_> variable.  It is already
  473. global, and is automatically local-ized by the foreach statement:
  474.  
  475.     <ol>
  476.     <&| list_items, list => \@items &>
  477.     <li> <% $_ %>
  478.     </&>
  479.     </ol>
  480.  
  481. list_items component:
  482.  
  483.     <%args>
  484.     @list
  485.     </%args>
  486.     % foreach (@list) {
  487.     <% $m->content %>
  488.     % }
  489.  
  490. =head2 Components that compute values
  491.  
  492. So far you have seen components used solely to output HTML.  However,
  493. components may also be used to compute a value. For example, you might
  494. have a component C<is_netscape> that analyzes the user agent to
  495. determine whether it is a Netscape browser:
  496.  
  497.     <%perl>
  498.     my $ua = $r->header_in('User-Agent');
  499.     return ($ua =~ /Mozilla/i && $ua !~ /MSIE/i) ? 1 : 0;
  500.     </%perl>
  501.  
  502. Because components are implemented underneath with Perl subroutines,
  503. they can return values and even understand scalar/list
  504. context. e.g. The result of wantarray() inside a component will reflect
  505. whether the component was called in scalar or list context.
  506.  
  507. The <& &> notation only calls a component for its side-effect, and
  508. discards its return value, if any.  To get at the return value of a
  509. component, use the C<< $m->comp >> command:
  510.  
  511.     % if ($m->comp('is_netscape')) {
  512.     Welcome, Netscape user!
  513.     % }
  514.  
  515. Mason adds a C<return undef> to the bottom of each component to
  516. provide an empty default return value. To return your own value from a
  517. component, you I<must> use an explicit C<return> statement. You cannot
  518. rely on the usual Perl trick of letting return values "fall through".
  519.  
  520. Generally components are divided into two types: those that output
  521. HTML, and those that return a value. There is very little reason for
  522. a component to do both. For example, it would not be very friendly
  523. for C<is_netscape> to output "hi Mom" while it was computing its value,
  524. thereby surprising the C<if> statement! Conversely, any value returned
  525. by an HTML component would typically be discarded by the <& &> tag
  526. that invoked it.
  527.  
  528. =head2 Subrequests
  529.  
  530. You may sometimes want to have a component call go through all the
  531. steps that the initial component call goes through, such as checking
  532. for autohandlers and dhandlers.  To do this, you need to execute a
  533. subrequest.
  534.  
  535. A subrequest is simply a Mason Request object and has all of the
  536. methods normally associated with one.
  537.  
  538. To create a subrequest you simply use the C<< $m->make_subrequest >>
  539. method.  This method can take any parameters belonging to
  540. L<HTML::Mason::Request|HTML::Mason::Request>, such as L<autoflush|HTML::Mason::Params/autoflush> or
  541. L<out_method|HTML::Mason::Params/out_method>.  Once you have a new request object you simply call its
  542. C<exec> method to execute it, which takes exactly the same parameters
  543. as the C<comp> method.
  544.  
  545. Since subrequests inherit their parent request's parameters, output
  546. from a component called via a subrequest goes to the same desintation
  547. as output from components caled during the parent request.  Of course,
  548. you can change this.
  549.  
  550. Here are some examples:
  551.  
  552.   <%perl>
  553.    my $req = $m->make_subrequest( comp => '/some/comp', args => [ id => 172 ] );
  554.    $req->exec;
  555.   </%perl>
  556.  
  557. If you want to capture the subrequest's output in a scalar, you can
  558. simply pass an L<out_method|HTML::Mason::Params/out_method> parameter to C<< $m->make_subrequest >>:
  559.  
  560.   <%perl>
  561.    my $buffer;
  562.    my $req =
  563.        $m->make_subrequest
  564.            ( comp => '/some/comp', args => [ id => 172 ], out_method => \$buffer );
  565.    $req->exec;
  566.   </%perl>
  567.  
  568. Now C<$buffer> contains all the output from that call to F</some/comp>.
  569.  
  570. For convenience, Mason also provides an C<< $m->subexec >> method.
  571. This method takes the same arguments as C<< $m->comp >> and internally
  572. calls C<< $m->make_subrequest >> and then C<exec> on the created
  573. request, all in one fell swoop.  This is useful in cases where you
  574. have no need to override any of the parent request object's
  575. attributes.
  576.  
  577. By default, output from a subrequest appears inline in the calling
  578. component, at the point where it is executed.  If you wish to do
  579. something else, you will need to explicitly override the subrequest's
  580. L<out_method|HTML::Mason::Params/out_method> parameter.
  581.  
  582. Mason Request objects are only designed to handle a single call to
  583. C<exec>.  If you wish to make multiple subrequests, you must create
  584. a new subrequest object for each one.
  585.  
  586. =head1 TOP-LEVEL COMPONENTS
  587.  
  588. The first component invoked for a page (the "top-level component")
  589. resides within the DocumentRoot and is chosen based on the URL. For
  590. example:
  591.  
  592.     http://www.foo.com/mktg/prods.html?id=372
  593.  
  594. Mason converts this URL to a filename,
  595. e.g. F</usr/local/www/htdocs/mktg/prods.html>.  Mason loads and
  596. executes that file as a component. In effect, Mason calls
  597.  
  598.     $m->comp('/mktg/prods.html', id=>372)
  599.  
  600. This component might in turn call other components and execute some Perl
  601. code, or it might contain nothing more than static HTML.
  602.  
  603. =head2 dhandlers
  604.  
  605. What happens when a user requests a component that doesn't exist? In
  606. this case Mason scans backward through the URI, checking each
  607. directory for a component named I<dhandler> ("default handler").  If
  608. found, the dhandler is invoked and is expected to use
  609. C<< $m->dhandler_arg >> as the parameter to some
  610. access function, perhaps a database lookup or location in another
  611. filesystem. In a sense, dhandlers are similar in spirit to Perl's
  612. AUTOLOAD feature; they are the "component of last resort" when a URL
  613. points to a non-existent component.
  614.  
  615. Consider the following URL, in which F<newsfeeds/> exists but not the
  616. subdirectory F<LocalNews> nor the component F<Story1>:
  617.  
  618.     http://myserver/newsfeeds/LocalNews/Story1
  619.  
  620. In this case Mason constructs the following search path:
  621.  
  622.     /newsfeeds/LocalNews/Story1         => no such thing
  623.     /newsfeeds/LocalNews/dhandler       => no such thing
  624.     /newsfeeds/dhandler                 => found! (search ends)
  625.     /dhandler
  626.  
  627. The found dhandler would read "LocalNews/Story1" from
  628. C<< $m->dhandler_arg >> and use it as a retrieval key into a
  629. database of stories.
  630.  
  631. Here's how a simple /newsfeeds/dhandler might look:
  632.  
  633.     <& header &>
  634.     <b><% $headline %></b><p>
  635.     <% $body %>
  636.     <& footer &>
  637.  
  638.     <%init>
  639.     my $arg = $m->dhandler_arg;                # get rest of path
  640.     my ($section, $story) = split("/", $arg);  # split out pieces
  641.     my $sth = $DBH->prepare
  642.     (qq{SELECT headline,body FROM news
  643.             WHERE section = ? AND story = ?);
  644.     $sth->execute($section, $story);
  645.     my ($headline, $body) = $sth->fetchrow_array;
  646.     return 404 if !$headline;                  # return "not found" if no such story
  647.     </%init>
  648.  
  649. By default dhandlers do not get a chance to handle requests to a
  650. directory itself (e.g. F</newsfeeds>). These are automatically
  651. deferred to Apache, which generates an index page or a FORBIDDEN
  652. error.  Often this is desirable, but if necessary the administrator
  653. can let in directory requests as well; see the L<allowing directory
  654. requests|HTML::Mason::Admin/allowing directory
  655. requests> section of the administrator's manual.
  656.  
  657. A component or dhandler that does not want to handle a particular
  658. request may defer control to the next dhandler by calling C<<
  659. $m->decline >>.
  660.  
  661. When using dhandlers under mod_perl, you may find that sometimes
  662. Apache will not set a content type for a response.  This usually
  663. happens when a dhandler handles a request for a non-existent file or
  664. directory.  You can add a C<< <Location> >> or C<< <LocationMatch> >>
  665. block containing a C<SetType> directive to your Apache config file, or
  666. you can just set the content type dynamically by calling C<<
  667. $r->content_type >>.
  668.  
  669. The administrator can customize the file name used for dhandlers with
  670. the L<dhandler_name|HTML::Mason::Params/dhandler_name> parameter.
  671.  
  672. =head2 autohandlers
  673.  
  674. Autohandlers allow you to grab control and perform some action just
  675. before Mason calls the top-level component.  This might mean adding a
  676. standard header and footer, applying an output filter, or setting up
  677. global variables.
  678.  
  679. Autohandlers are directory based.  When Mason determines the top-level
  680. component, it checks that directory and all parent directories for a
  681. component called F<autohandler>. If found, the autohandler is called
  682. first.  After performing its actions, the autohandler typically calls
  683. C<< $m->call_next >> to transfer control to the original intended
  684. component.
  685.  
  686. C<< $m->call_next >> works just like C<< $m->comp >> except that the component path
  687. and arguments are implicit. You can pass additional arguments to
  688. C<< $m->call_next >>; these are merged with the original arguments, taking
  689. precedence in case of conflict.  This allows you, for example, to
  690. override arguments passed in the URL.
  691.  
  692. Here is an autohandler that adds a common header and footer to each
  693. page underneath its directory:
  694.  
  695.     <HTML>
  696.     <HEAD><TITLE>McHuffy Incorporated</TITLE></HEAD>
  697.     <BODY BGCOLOR="salmon">
  698.  
  699.     % $m->call_next;
  700.  
  701.     <HR>
  702.     Copyright 1999 McHuffy Inc.
  703.     </BODY>
  704.     </HTML>
  705.  
  706. Same idea, using components for the header/footer:
  707.  
  708.     <& /shared/header &>
  709.     % $m->call_next;
  710.     <& /shared/footer &>
  711.  
  712. The next autohandler applies a filter to its pages, adding an absolute
  713. hostname to relative image URLs:
  714.  
  715.     % $m->call_next;
  716.  
  717.     <%filter>
  718.     s{(<img[^>]+src=\")/} {$1http://images.mysite.com/}ig;
  719.     </%filter>
  720.  
  721. Most of the time autohandler can simply call C<< $m->call_next >>
  722. without needing to know what the next component is. However, should
  723. you need it, the component object is available from
  724. C<< $m->fetch_next >>. This is useful for calling the component manually,
  725. e.g. if you want to suppress some original arguments or if you want to
  726. use C<< $m->scomp >> to store and process the output.
  727.  
  728. What happens if more than one autohandler applies to a page? Prior to
  729. version 0.85, only the most specific autohandler would execute.  In
  730. 0.85 and beyond each autohandler gets a chance to run.  The top-most
  731. autohandler runs first; each C<< $m->call_next >> transfers control to the
  732. next autohandler and finally to the originally called component. This
  733. allows you, for example, to combine general site-wide templates and
  734. more specific section-based templates.
  735.  
  736. Autohandlers can be made even more powerful in conjunction with
  737. Mason's object-oriented style features: methods, attributes, and
  738. inheritance.  In the interest of space these are discussed in a
  739. separate section, L<Object-Oriented Techniques|"Object-Oriented
  740. Techniques">.
  741.  
  742. The administrator can customize the file name used for autohandlers
  743. with the L<autohandler_name|HTML::Mason::Params/autohandler_name> parameter.
  744.  
  745. =head2 dhandlers vs. autohandlers
  746.  
  747. dhandlers and autohandlers both provide a way to exert control over a
  748. large set of URLs. However, each specializes in a very different
  749. application.  The key difference is that dhandlers are invoked only
  750. when no appropriate component exists, while autohandlers are invoked
  751. only in conjunction with a matching component.
  752.  
  753. As a rule of thumb: use an autohandler when you have a set of
  754. components to handle your pages and you want to augment them
  755. with a template/filter. Use a dhandler when you want to create a set
  756. of "virtual URLs" that don't correspond to any actual components,
  757. or to provide default behavior for a directory.
  758.  
  759. dhandlers and autohandlers can even be used in the same directory. For
  760. example, you might have a mix of real URLs and virtual URLs to which
  761. you would like to apply a common template/filter.
  762.  
  763. =head1 PASSING PARAMETERS
  764.  
  765. This section describes Mason's facilities for passing parameters to
  766. components (either from HTTP requests or component calls) and for
  767. accessing parameter values inside components.
  768.  
  769. =head2 In Component Calls
  770.  
  771. Any Perl data type can be passed in a component call:
  772.  
  773.     <& /sales/header, s => 'dog', l => [2, 3, 4], h => {a => 7, b => 8} &>
  774.  
  775. This command passes a scalar ($s), a list (@l), and a hash (%h). The
  776. list and hash must be passed as references, but they will be automatically
  777. dereferenced in the called component.
  778.  
  779. =head2 In HTTP requests
  780.  
  781. Consider a CGI-style URL with a query string:
  782.  
  783.     http://www.foo.com/mktg/prods.html?str=dog&lst=2&lst=3&lst=4
  784.  
  785. or an HTTP request with some POST content. Mason automatically parses
  786. the GET/POST values and makes them available to the component as
  787. parameters.
  788.  
  789. =head2 Accessing Parameters
  790.  
  791. Component parameters, whether they come from GET/POST or another
  792. component, can be accessed in two ways.
  793.  
  794. 1.  Declared named arguments: Components can define an
  795. C<< <%args> >> section listing argument names, types, and
  796. default values. For example:
  797.  
  798.     <%args>
  799.     $a
  800.     @b       # a comment
  801.     %c
  802.  
  803.     # another comment
  804.     $d => 5
  805.     $e => $d*2
  806.     @f => ('foo', 'baz')
  807.     %g => (joe => 1, bob => 2)
  808.     </%args>
  809.  
  810. Here, I<$a>, I<@b>, and I<%c> are required arguments; the component generates
  811. an error if the caller leaves them unspecified. I<$d>, I<$e>, I<@f> and I<%g> are
  812. optional arguments; they are assigned the specified default values if
  813. unspecified.  All the arguments are available as lexically scoped ("my")
  814. variables in the rest of the component.
  815.  
  816. Arguments are separated by one or more newlines. Comments may be used at
  817. the end of a line or on their own line.
  818.  
  819. Default expressions are evaluated in top-to-bottom order, and one
  820. expression may reference an earlier one (as $e references $d above).
  821.  
  822. Only valid Perl variable names may be used in C<< <%args> >>
  823. sections.  Parameters with non-valid variable names cannot be
  824. pre-declared and must be fetched manually out of the %ARGS hash (see
  825. below).  One common example of undeclarable parameters are the
  826. "button.x/button.y" parameters sent for a form submit.
  827.  
  828. 2. %ARGS hash: This variable, always available, contains all of the
  829. parameters passed to the component (whether or not they were
  830. declared).  It is especially handy for dealing with large numbers of
  831. parameters, dynamically named parameters, or parameters with non-valid
  832. variable names. %ARGS can be used with or without an
  833. C<< <%args> >> section, and its contents are unrelated to what you
  834. have declared in C<< <%args> >>.
  835.  
  836. Here's how to pass all of a component's parameters to another component:
  837.  
  838.     <& template, %ARGS &>
  839.  
  840. =head2 Parameter Passing Examples
  841.  
  842. The following examples illustrate the different ways to pass and receive parameters.
  843.  
  844. 1.  Passing a scalar I<id> with value 5.
  845.  
  846.   In a URL: /my/URL?id=5
  847.   In a component call: <& /my/comp, id => 5 &>
  848.   In the called component, if there is a declared argument named...
  849.     $id, then $id will equal 5
  850.     @id, then @id will equal (5)
  851.     %id, then an error occurs
  852.   In addition, $ARGS{id} will equal 5.
  853.  
  854. 2.  Passing a list I<colors> with values red, blue, and green.
  855.  
  856.   In a URL: /my/URL?colors=red&colors=blue&colors=green
  857.   In an component call: <& /my/comp, colors => ['red', 'blue', 'green'] &>
  858.   In the called component, if there is a declared argument named...
  859.     $colors, then $colors will equal ['red', 'blue', 'green']
  860.     @colors, then @colors will equal ('red', 'blue', 'green')
  861.     %colors, then an error occurs
  862.   In addition, $ARGS{colors} will equal ['red', 'blue', 'green'].
  863.  
  864. 3.  Passing a hash I<grades> with pairs Alice => 92 and Bob => 87.
  865.  
  866.   In a URL: /my/URL?grades=Alice&grades=92&grades=Bob&grades=87
  867.   In an component call: <& /my/comp, grades => {Alice => 92, Bob => 87} &>
  868.   In the called component, if there is a declared argument named...
  869.     @grades, then @grades will equal ('Alice', 92, 'Bob', 87)
  870.     %grades, then %grades will equal (Alice => 92, Bob => 87)
  871.   In addition, $grade and $ARGS{grades} will equal
  872.     ['Alice',92,'Bob',87] in the URL case, or {Alice => 92, Bob => 87}
  873.     in the component call case.  (The discrepancy exists because, in a
  874.     query string, there is no detectable difference between a list or
  875.     hash.)
  876.  
  877. =head2 Using @_ instead
  878.  
  879. If you don't like named parameters, you can pass a traditional
  880. list of ordered parameters:
  881.  
  882.     <& /mktg/prods.html', 'dog', [2, 3, 4], {a => 7, b => 8} &>
  883.  
  884. and access them as usual through Perl's @_ array:
  885.  
  886.     my ($scalar, $listref, $hashref) = @_;
  887.  
  888. In this case no C<< <%args> >> section is necessary.
  889.  
  890. We generally recommend named parameters for the benefits of
  891. readability, syntax checking, and default value automation.  However
  892. using C<@_> may be convenient for very small components, especially
  893. subcomponents created with C<< <%def> >>.
  894.  
  895. Before Mason 1.21, @_ contained I<copies> of the caller's arguments.
  896. In Mason 1.21 and beyond, this unnecessary copying was eliminated and
  897. @_ now contains I<aliases> to the caller's arguments, just as with
  898. regular Perl subroutines. For example, if a component updates $_[0],
  899. the corresponding argument is updated (or an error occurs if it is not
  900. updatable).
  901.  
  902. Most users won't notice this change because C<< <%args> >> variables
  903. and the C<%ARGS> hash always contain copies of arguments.
  904.  
  905. See perlsub for more information on @_ aliasing.
  906.  
  907. =head1 INITIALIZATION AND CLEANUP
  908.  
  909. The following sections contain blocks of Perl to execute at specific
  910. times.
  911.  
  912. =head2 <%init>
  913.  
  914. This section contains initialization code that executes as soon as the
  915. component is called. For example: checking that a user is logged in;
  916. selecting rows from a database into a list; parsing the contents of a
  917. file into a data structure.
  918.  
  919. Technically an C<< <%init> >> block is equivalent to a C<< <%perl> >>
  920. block at the beginning of the component. However, there is an
  921. aesthetic advantage of placing this block at the end of the component
  922. rather than the beginning.
  923.  
  924. We've found that the most readable components (especially for
  925. non-programmers) contain HTML in one continuous block at the top, with
  926. simple substitutions for dynamic elements but no distracting blocks of
  927. Perl code.  At the bottom an C<< <%init> >> block sets up the substitution
  928. variables.  This organization allows non-programmers to work with the
  929. HTML without getting distracted or discouraged by Perl code. For example:
  930.  
  931.     <html>
  932.     <head><title><% $headline %></title></head>
  933.     <body>
  934.     <h2><% $headline %></h2>
  935.     By <% $author %>, <% $date %><p>
  936.  
  937.     <% $body %>
  938.  
  939.     </body></html>
  940.  
  941.     <%init>
  942.     # Fetch article from database
  943.     my $dbh = DBI::connect ...;
  944.     my $sth = $dbh->prepare("select * from articles where id = ?");
  945.     $sth->execute($article_id);
  946.     my ($headline, $date, $author, $body) = $sth->fetchrow_array;
  947.     # Massage the fields
  948.     $headline = uc($headline);
  949.     my ($year, $month, $day) = split('-', $date);
  950.     $date = "$month/$day";
  951.     </%init>
  952.  
  953.     <%args>
  954.     $article_id
  955.     </%args>
  956.  
  957. =head2 <%cleanup>
  958.  
  959. This section contains cleanup code that executes just before the
  960. component exits. For example: closing a database connection or closing
  961. a file handle.
  962.  
  963. Technically a << <%cleanup> >> block is equivalent to a C<< <%perl> >>
  964. block at the end of the component. Since a component corresponds a
  965. subroutine block, and since Perl is so darned good at cleaning up
  966. stuff at the end of blocks, C<< <%cleanup> >> sections are rarely
  967. needed.
  968.  
  969. The C<< <%cleanup> >> block is not executed if the component returns
  970. (via an explicit C<return> statement) or if an error or abort occurs
  971. in this component or one of its children. This makes C<< <%cleanup> >> 
  972. useless for real cleanup code that needs a guarantee of execution.
  973. We hope to remedy this in the next major release.
  974.  
  975. =head2 <%once>
  976.  
  977. This code executes once when the component is loaded. Variables
  978. declared in this section can be seen in all of a component's code and
  979. persist for the lifetime of the component.
  980.  
  981. This section is useful for declaring persistent component-scoped
  982. lexical variables (especially objects that are expensive to create),
  983. declaring subroutines (both named and anonymous), and initializing
  984. state.
  985.  
  986. This code does not run inside a request context. You cannot call
  987. components or access C<$m> or C<$r> from this section. Also, do not
  988. attempt to C<return()> from a C<< <%once> >> section; the current
  989. compiler cannot properly handle it.
  990.  
  991. Normally this code will execute individually from every HTTP child
  992. that uses the component. However, if the component is preloaded, this
  993. code will only execute once in the parent.  Unless you have total control
  994. over what components will be preloaded, it is safest to avoid
  995. initializing variables that can't survive a fork(), e.g. DBI handles.
  996. Use code like this to initialize such variables in the C<< <%init> >>
  997. section:
  998.  
  999.     <%once>
  1000.     my $dbh;      # declare but don't assign
  1001.     ...
  1002.     </%once>
  1003.  
  1004.     <%init>
  1005.     $dbh ||= DBI::connect ...
  1006.     ...
  1007.     </%init>
  1008.  
  1009. In addition, using C<$m> or <$r> in this section will not work in a
  1010. preloaded component, because neither of those variable exist when a
  1011. component is preloaded.
  1012.  
  1013. =head2 <%shared>
  1014.  
  1015. As with C<< <%once> >>, lexical (C<my>) variables declared in this
  1016. section can be seen in all the rest of a component's code: the main
  1017. body, subcomponents, and methods.  However, unlike C<< <%once> >>, the
  1018. code runs once per request (whenever the component is used) and its
  1019. variables last only until the end of the request.
  1020.  
  1021. A C<< <%shared> >> section is useful for initializing variables needed in, say, the
  1022. main body and one more subcomponents or methods. See L<Object-Oriented
  1023. Techniques|"Object-Oriented Techniques"> for an example of usage.
  1024.  
  1025. It's important to realize that you do not have access to the C<%ARGS>
  1026. hash or variables created via an C<< <%args> >> block inside a shared
  1027. section.  However, you can access arguments via
  1028. L<$m-E<gt>request_args|HTML::Mason::Request/item_request_args>.
  1029.  
  1030. Additionally, you cannot call a components' own methods or
  1031. subcomponents from inside a C<< <%shared> >>, though you can call
  1032. other components.
  1033.  
  1034. Avoid using C<< <%shared> >> for side-effect code that needs to run at a
  1035. predictable time during page generation. You may assume only that
  1036. C<< <%shared> >> runs just before the first code that needs it and runs at
  1037. most once per request.
  1038.  
  1039. In the current implementation, the scope sharing is done with
  1040. closures, so variables will only be shared if they are visible at
  1041. compile-time in the other parts of the component.  In addition, you
  1042. can't rely on the specific destruction time of the shared variables,
  1043. because they may not be destroyed until the first time the C<<
  1044. <%shared> >> section executes in a future request.  C<< <%init> >>
  1045. offers a more predictable execution and destruction time.
  1046.  
  1047. Currently any component with a C<< <%shared> >> section incurs an
  1048. extra performance penalty, because Mason must recreate its
  1049. anonymous subroutines the first time each new request uses the
  1050. component.  The exact penalty varies between systems and for most
  1051. applications will be unnoticeable. However, one should avoid using
  1052. C<< <%shared> >> when patently unnecessary, e.g. when an C<< <%init> >>
  1053. would work just as well.
  1054.  
  1055. Do not attempt to C<return()> from a C<< <%shared> >> section; the
  1056. current compiler cannot properly handle it.
  1057.  
  1058. =head1 EMBEDDED COMPONENTS
  1059.  
  1060. =head2 <%def I<name>>
  1061.  
  1062. Each instance of this section creates a I<subcomponent> embedded
  1063. inside the current component. Inside you may place anything that a
  1064. regular component contains, with the exception of C<< <%def> >>, C<< <%method> >>,
  1065. C<< <%once> >>, and C<< <%shared> >> tags.
  1066.  
  1067. The I<name> consists of characters in the set C<[\w._-]>. To
  1068. call a subcomponent simply use its name in <& &> or C<< $m->comp >>. A
  1069. subcomponent can only be seen from the surrounding component.
  1070.  
  1071. If you define a subcomponent with the same name as a file-based
  1072. component in the current directory, the subcomponent takes
  1073. precedence. You would need to use an absolute path to call the
  1074. file-based component. To avoid this situation and for general clarity,
  1075. we recommend that you pick a unique way to name all of your
  1076. subcomponents that is unlikely to interfere with file-based
  1077. components. A commonly accepted practice is to start subcomponent
  1078. names with ".".
  1079.  
  1080. While inside a subcomponent, you may use absolute or relative paths to
  1081. call file-based components and also call any of your "sibling"
  1082. subcomponents.
  1083.  
  1084. The lexical scope of a subcomponent is separate from the main
  1085. component.  However a subcomponent can declare its own C<< <%args> >> section
  1086. and have relevant values passed in.  You can also use a C<< <%shared> >>
  1087. section to declare variables visible from both scopes.
  1088.  
  1089. In the following example, we create a ".link" subcomponent to produce a
  1090. standardized hyperlink:
  1091.  
  1092.     <%def .link>
  1093.     <font size="4" face="Verdana,Arial,Helvetica">
  1094.     <a href="http://www.<% $site %>.com"><% $label %></a>
  1095.     </font><br>
  1096.     <%args>
  1097.     $site
  1098.     $label=>ucfirst($site)
  1099.     </%args>
  1100.     </%def>
  1101.  
  1102.     Visit these sites:
  1103.     <ul>
  1104.     <li><& .link, site=>'yahoo' &><br>
  1105.     <li><& .link, site=>'cmp', label=>'CMP Media' &><br>
  1106.     <li><& .link, site=>'excite' &>
  1107.     </ul>
  1108.  
  1109. =head2 <%method I<name>>
  1110.  
  1111. Each instance of this section creates a I<method> embedded inside
  1112. the current component. Methods resemble subcomponents in terms of
  1113. naming, contents, and scope. However, while subcomponents can only be
  1114. seen from the parent component, methods are meant to be called from
  1115. other components.
  1116.  
  1117. There are two ways to call a method. First, via a path of the form
  1118. "comp:method":
  1119.  
  1120.     <& /foo/bar:method1 &>
  1121.  
  1122.     $m->comp('/foo/bar:method1');
  1123.  
  1124. Second, via the call_method component method:
  1125.  
  1126.     my $comp = $m->fetch_comp('/foo/bar');
  1127.     ...
  1128.     $comp->call_method('method1');
  1129.  
  1130. Methods are commonly used in conjunction with autohandlers to make
  1131. templates more flexible. See L<Object-Oriented
  1132. Techniques|"Object-Oriented Techniques"> for more information.
  1133.  
  1134. You cannot create a subcomponent and method with the same name. 
  1135. This is mostly to prevent obfuscation and accidental errors.
  1136.  
  1137. =head1 FLAGS AND ATTRIBUTES
  1138.  
  1139. The C<< <%flags> >> and C<< <%attr> >> sections consist of key/value
  1140. pairs, one per line, joined by '=>'.  In each pair, the key must be
  1141. any valid Perl "bareword identifier" (made of letters, numbers, and
  1142. the underscore character), and the value may be any scalar value,
  1143. including references.  An optional comment may follow each line.
  1144.  
  1145. =head2 <%flags>
  1146.  
  1147. Use this section to set official Mason flags that affect the current
  1148. component's behavior.
  1149.  
  1150. Currently there is only one flag, C<inherit>, which specifies the
  1151. component's I<parent> in the form of a relative or absolute component
  1152. path. A component inherits methods and attributes from its parent; see
  1153. L<Object-Oriented Techniques|"Object-Oriented Techniques"> for
  1154. examples.
  1155.  
  1156.     <%flags>
  1157.     inherit=>'/site_handler'
  1158.     </%flags>
  1159.  
  1160. =head2 <%attr>
  1161.  
  1162. Use this section to assign static key/value attributes that can be
  1163. queried from other components.
  1164.  
  1165.     <%attr>
  1166.     color => 'blue'
  1167.     fonts => [qw(arial geneva helvetica)]
  1168.     </%attr>
  1169.  
  1170. To query an attribute of a component, use the C<attr> method:
  1171.  
  1172.     my $color = $comp->attr('color')
  1173.  
  1174. where $comp is a component object.
  1175.  
  1176. Mason evaluates attribute values once when loading the component.
  1177. This makes them faster but less flexible than methods.
  1178.  
  1179. =head1 FILTERING
  1180.  
  1181. This section describes several ways to apply filtering functions over
  1182. the results of the current component.  By separating out and hiding a
  1183. filter that, say, changes HTML in a complex way, we allow
  1184. non-programmers to work in a cleaner HTML environment.
  1185.  
  1186. =head2 <%filter> section
  1187.  
  1188. The C<< <%filter> >> section allows you to arbitrarily filter the output of
  1189. the current component. Upon entry to this code, C<$_> contains the
  1190. component output, and you are expected to modify it in place. The code
  1191. has access to component arguments and can invoke subroutines, call
  1192. other components, etc.
  1193.  
  1194. This simple filter converts the component output to UPPERCASE:
  1195.  
  1196.     <%filter>
  1197.     tr/a-z/A-Z/
  1198.     </%filter>
  1199.  
  1200. The following navigation bar uses a filter to "unlink" and highlight
  1201. the item corresponding to the current page:
  1202.  
  1203.     <a href="/">Home</a> | <a href="/products/">Products</a> |
  1204.     <a href="/bg.html">Background</a> | <a href="/finance/">Financials</a> |
  1205.     <a href="/support/">Tech Support</a> | <a href="/contact.html">Contact Us</a>
  1206.  
  1207.     <%filter>
  1208.     my $uri = $r->uri;
  1209.     s{<a href="$uri/?">(.*?)</a>} {<b>$1</b>}i;
  1210.     </%filter>
  1211.  
  1212. This allows a designer to code such a navigation bar intuitively
  1213. without C<if> statements surrounding each link!  Note that the regular
  1214. expression need not be very robust as long as you have control over what
  1215. will appear in the body.
  1216.  
  1217. A filter block does not have access to variables declared in a
  1218. component's C<< <%init> >> section, though variables declared in the
  1219. C<< <%args> >>, C<< <%once> >> or C<< <%shared> >> blocks are
  1220. usable in a filter.
  1221.  
  1222. It should be noted that a filter cannot rely on receiving all of a
  1223. component's output at once, and so may be called multiple times with
  1224. different chunks of output.  This can happen if autoflush is on, or if
  1225. a filter-containing component, or the components it calls, call the
  1226. C<< $m->flush_buffer() >> method.
  1227.  
  1228. You should never call Perl's C<return()> function inside a filter
  1229. section, or you will not see any output at all.
  1230.  
  1231. You can use L<Component Calls with Content|"Component Calls with
  1232. Content"> if you want to filter specific parts of a component rather
  1233. than the entire component.
  1234.  
  1235. =head1 OTHER SYNTAX
  1236.  
  1237. =head2 <%doc>
  1238.  
  1239. Text in this section is treated as a comment and ignored. Most useful
  1240. for a component's main documentation.  One can easily write a program
  1241. to sift through a set of components and pull out their C<< <%doc> >>
  1242. blocks to form a reference page.
  1243.  
  1244. Can also be used for in-line comments, though it is an admittedly
  1245. cumbersome comment marker.  Another option is '%#':
  1246.  
  1247.     %# this is a comment
  1248.  
  1249. These comments differ from HTML comments in that they do not appear in
  1250. the HTML.
  1251.  
  1252. =head2 <%text>
  1253.  
  1254. Text in this section is passed through unmodified by Mason.  Any Mason
  1255. syntax inside it is ignored.  This is useful, for example, when
  1256. documenting Mason itself from a component:
  1257.  
  1258.     <%text>
  1259.     % This is an example of a Perl line.
  1260.     <% This is an example of an expression block. %>
  1261.     </%text>
  1262.  
  1263. This works for almost everything, but doesn't let you output
  1264. C<< </%text> >> itself! When all else fails, use C<< $m->print >>:
  1265.  
  1266.     % $m->print('The tags are <%text> and </%text>.');
  1267.  
  1268. =head2 Escaping expressions
  1269.  
  1270. Mason has facilities for I<escaping> the output from C<< <% %> >>
  1271. tags, on either a site-wide or a per-expression basis.
  1272.  
  1273. Any C<< <% %> >> expression may be terminated by a '|' and one or more
  1274. escape flags (plus arbitrary whitespace), separated by commas:
  1275.  
  1276.     <% $file_data |h %>
  1277.  
  1278. The current valid flags are:
  1279.  
  1280. =over
  1281.  
  1282. =item * h
  1283.  
  1284. Escape HTML ('<' => '<', etc.) using C<HTML::Entities::encode()>.
  1285. Before Perl 5.8.0 this module assumes that text is in the ISO-8859-1
  1286. character set; see L<the next section|HTML::Mason::Devel/"User-defined
  1287. Escapes"> for how to override this escaping. After 5.8.0, the encoding
  1288. assumes that text is in Unicode.
  1289.  
  1290. =item * u
  1291.  
  1292. Escape a URL query string (':' => '%3A', etc.) - all but
  1293. [a-zA-Z0-9_.-]
  1294.  
  1295. =item * n
  1296.  
  1297. This is a special flag indicating that the default escape flags should
  1298. I<not> be used for this substitution.
  1299.  
  1300. =back
  1301.  
  1302. The administrator may specify a set of default escape flags via the
  1303. L<default_escape_flags|HTML::Mason::Params/default_escape_flags> parameter. For example, if the administrator
  1304. sets L<default_escape_flags|HTML::Mason::Params/default_escape_flags> to C<['h']>, then all <% %> expressions
  1305. will automatically be HTML-escaped.  In this case you would use the
  1306. C<n> flag to turn off HTML-escaping for a specific expression:
  1307.  
  1308.     <% $html_block |n %>
  1309.  
  1310. Multiple escapes can be specified as a comma-separated list:
  1311.  
  1312.     <% $uri | u, n %>
  1313.  
  1314. The old pre-defined escapes, 'h', 'u', and 'n', can be used I<without>
  1315. commas, so that this is legal:
  1316.  
  1317.     <% $uri | un %>
  1318.  
  1319. However, this only works for these three escapes, and no others.  If
  1320. you are using user-defined escapes as well, you I<must> use a comma:
  1321.  
  1322.     <% $uri | u, add_session %>
  1323.  
  1324. =head3 User-defined Escapes
  1325.  
  1326. Besides the default escapes mentioned above, it is possible for the
  1327. user to define their own escapes or to override the built-in 'h' and
  1328. 'u' escapes.
  1329.  
  1330. This is done via the Interp object's L<escape_flags|HTML::Mason::Params/escape_flags> parameter or
  1331. L<set_escape()|HTML::Mason::Interp/item_set_escape> method.  Escape
  1332. names may be any number of characters as long as it matches the regex
  1333. C</^[\w-]+$/>.  The one exception is that you cannot override the 'n'
  1334. flag.
  1335.  
  1336. Each escape flag is associated with a subroutine reference.  The
  1337. subroutine should expect to receive a scalar reference, which should
  1338. be manipulated in place.  Any return value from this subroutine is
  1339. ignored.
  1340.  
  1341. Escapes can be defined at any time but using an escape that is not
  1342. defined will cause an error when executing that component.
  1343.  
  1344. A common use for this feature is to override the built-in HTML
  1345. escaping, which will not work with non-ISO-8559-1 encodings.  If
  1346. you are using such an encoding and want to switch the 'h' flag to do
  1347. escape just the minimal set of characters (C<E<lt>>, C<E<gt>>, C<&>,
  1348. C<">), put this in your Apache configuration:
  1349.  
  1350.    PerlSetVar  MasonEscapeFlags  "h => \&HTML::Mason::Escapes::basic_html_escape"
  1351.  
  1352. Or, in a top-level autohandler:
  1353.  
  1354.     $m->interp->set_escape( h => \&HTML::Mason::Escapes::basic_html_escape );
  1355.  
  1356. Or you could write your own escape function for a particular encoding:
  1357.  
  1358.     $ah->interp->set_escape( h => \&my_html_escape );
  1359.  
  1360. And of course this can be used for all sorts of other things, like a
  1361. naughty words filter for the easily offended:
  1362.  
  1363.     $interp->set_escape( 'no-naughty' => \&remove_naughty_words );
  1364.  
  1365. =head3 Manually applying escapes
  1366.  
  1367. You can manually apply one or more escapes to text using the L<Interp
  1368. object's C<apply_escapes()>
  1369. method|HTML::Mason::Interp/item_apply_escapes>. e.g.
  1370.  
  1371.     $m->interp->apply_escapes( 'some html content', 'h' );
  1372.  
  1373. =head2 Backslash at end of line
  1374.  
  1375. A backslash (\) at the end of a line suppresses the newline. In HTML
  1376. components, this is mostly useful for fixed width areas like C<< <pre> >>
  1377. tags, since browsers ignore white space for the most part. An example:
  1378.  
  1379.     <pre>
  1380.     foo
  1381.     % if (1) {
  1382.     bar
  1383.     % }
  1384.     baz
  1385.     </pre>
  1386.  
  1387. outputs
  1388.  
  1389.     foo
  1390.     bar
  1391.     baz
  1392.  
  1393. because of the newlines on lines 2 and 4. (Lines 3 and 5 do not
  1394. generate a newline because the entire line is taken by Perl.)
  1395. To suppress the newlines:
  1396.  
  1397.     <pre>
  1398.     foo\
  1399.     % if (1) {
  1400.     bar\
  1401.     % }
  1402.     baz
  1403.     </pre>
  1404.  
  1405. which prints
  1406.  
  1407.     foobarbaz
  1408.  
  1409. =head1 DATA CACHING
  1410.  
  1411. Mason's data caching interface allows components to cache the results
  1412. of computation for improved performance.  Anything may be cached, from
  1413. a block of HTML to a complex data structure.
  1414.  
  1415. Each component gets its own private, persistent data cache. Except
  1416. under special circumstances, one component does not access another
  1417. component's cache. Each cached value may be set to expire at a certain
  1418. time.
  1419.  
  1420. Data caching is implemented on top of DeWitt Clinton's C<Cache::Cache>
  1421. package. Mason implements its own extended subclass of Dewitt's module
  1422. called L<HTML::Mason::Cache::BaseCache|HTML::Mason::Cache::BaseCache>.
  1423. See that module's documentation for a companion API reference to this
  1424. section.
  1425.  
  1426. =head2 Basic Usage
  1427.  
  1428. The C<< $m->cache >> method returns an
  1429. L<object|HTML::Mason::Cache::BaseCache> representing the cache for
  1430. this component. Here's the typical usage of C<< $m->cache >>:
  1431.  
  1432.     my $result = $m->cache->get('key');
  1433.     if (!defined($result)) {
  1434.         ... compute $result ...
  1435.         $m->cache->set('key', $result);
  1436.     }
  1437.  
  1438. C<< $m->cache->get >> attempts to retrieve this component's cache
  1439. value. If the value is available it is placed in C<$result>. If the
  1440. value is not available, C<$result> is computed and stored in the
  1441. cache by C<< $m->cache->set >>.
  1442.  
  1443. =head2 Multiple Keys/Values
  1444.  
  1445. A cache can store multiple key/value pairs. A value can be
  1446. anything serializable by C<Storable>, from a simple scalar to an
  1447. arbitrary complex list or hash reference:
  1448.  
  1449.     $m->cache->set(name => $string);
  1450.     $m->cache->set(friends => \@list);
  1451.     $m->cache->set(map => \%hash);
  1452.  
  1453. You can fetch all the keys in a cache with
  1454.  
  1455.     my @idents = $m->cache->get_keys;
  1456.  
  1457. It should be noted that Mason reserves all keys beginning with
  1458. C<__mason> for its own use.
  1459.  
  1460. =head2 Expiration
  1461.  
  1462. You can pass an optional third argument to C<< $m->cache->set >>
  1463. indicating when the item should expire:
  1464.  
  1465.     $m->cache->set('name1', $string1, '5 min');  # Expire in 5 minutes
  1466.     $m->cache->set('name2', $string2, '3h');     # Expire in 3 hours
  1467.  
  1468. To change the expiration time for a piece of data, call C<set> again
  1469. with the new expiration. To expire an item immediately, use
  1470. C<< $m->cache->remove >>.
  1471.  
  1472. You can also specify an expiration condition when you fetch the item,
  1473. using the I<expire_if> option:
  1474.  
  1475.     my $result = $m->cache->get('key',
  1476.         expire_if=>sub { $_[0]->get_created_at < (stat($file))[9] });
  1477.  
  1478. I<expire_if> takes an anonymous subroutine, which is called with the
  1479. L<cache object|"Cache Object"> as its only parameter. If the
  1480. subroutine returns a true value, the item is expired. In the example
  1481. above, we expire the item whenever a certain file changes.
  1482.  
  1483. Finally, you can expire a cache item from an external script; see
  1484. L<Accessing a Cache Externally|"Accessing a Cache Externally"> below.
  1485.  
  1486. =head2 Avoiding Concurrent Recomputation with Busy Locks
  1487.  
  1488. The code shown in "Basic Usage" above,
  1489.  
  1490.    my $result = $m->cache->get('key');
  1491.    if (!defined($result)) {
  1492.        ... compute $result ...
  1493.        $m->cache->set('key', $result);
  1494.    }
  1495.  
  1496. can suffer from a kind of race condition for caches that
  1497. are accessed frequently and take a long time to recompute.
  1498.  
  1499. Suppose that a particular cache value is accessed five times a
  1500. second and takes three seconds to recompute.  When the cache expires,
  1501. the first process comes in, sees that it is expired, and starts to
  1502. recompute the value.  The second process comes in and does the same thing.
  1503. This sequence continues until the first process finishes and stores
  1504. the new value.  On average, the value will be recomputed and written
  1505. to the cache 15 times!
  1506.  
  1507. Mason offers a solution with the I<busy_lock> flag:
  1508.  
  1509.    my $result = $m->cache->get('key', busy_lock=>'30 sec');
  1510.  
  1511. In this case, when the value cannot be retrieved, C<get()> sets
  1512. the expiration time of the value 30 seconds in the future before
  1513. returning C<undef>.  This tells the first process to compute the new
  1514. value while causing subsequent processes to use the old value for 30
  1515. seconds. 
  1516.  
  1517. Should the 30 seconds expire before the first process is done, a second
  1518. process will start computing the new value while setting the expiration
  1519. time yet another 30 seconds in the future, and so on.
  1520.  
  1521. =head2 Caching All Output
  1522.  
  1523. Occasionally you will need to cache the complete output of a
  1524. component.  For this purpose, Mason offers the C<< $m->cache_self >>
  1525. method.  This method causes Mason to check to see if this component
  1526. has already been run and its output cached.  If this is the case, this
  1527. output is simply sent as output.  Otherwise, the component run
  1528. normally and its output and return value cached.
  1529.  
  1530. It is typically used right at the top of an C<< <%init> >> section:
  1531.  
  1532.     <%init>
  1533.     return if $m->cache_self([key => 'fookey', expires_in => '3 hours',
  1534.                              ... <other cache options> ... ]);
  1535.      ... <rest of init> ...
  1536.     </%init>
  1537.  
  1538. A full list of parameters and examples are available in the
  1539. L<cache_self|HTML::Mason::Request/item_cache_self> section of the Request
  1540. manual.
  1541.  
  1542. =head2 Cache Object
  1543.  
  1544. C<< $m->cache->get_object >> returns the C<Cache::Object> associated
  1545. with a particular key. You can use this to retrieve useful
  1546. meta-data:
  1547.  
  1548.     my $co = $m->cache->get_object('name1');
  1549.     $co->get_created_at();    # when was object stored in cache
  1550.     $co->get_accessed_at();   # when was object last accessed
  1551.     $co->get_expires_at();    # when does object expire
  1552.  
  1553. =head2 Choosing a Cache Subclass
  1554.  
  1555. The cache API is implemented by a variety of backend subclasses. For
  1556. example, C<FileCache> implements the interface with a set of
  1557. directories and files, C<MemoryCache> implements the interface in
  1558. process memory, and C<SharedMemoryCache> implements the interface in
  1559. shared memory. See the C<Cache::Cache> package for a full list of
  1560. backend subclasses.
  1561.  
  1562. By default C<< $m->cache >> uses C<FileCache>, but you can override
  1563. this with the I<cache_class> keyword. The value must be the name of a
  1564. C<Cache::Cache> subclass; the prefix "Cache::" need not be included.
  1565. For example:
  1566.  
  1567.     my $result = $m->cache(cache_class => 'MemoryCache')->get('key');
  1568.     $m->cache(cache_class => 'MemoryCache')->set(key => $result);
  1569.  
  1570. You can even specify different subclasses for different keys in the
  1571. same component. Just make sure the correct value is passed to all
  1572. calls to C<< $m->cache >>; Mason does not remember which subclass you
  1573. have used for a given component or key.
  1574.  
  1575. The administrator can set the default cache subclass used by all
  1576. components with the L<data_cache_defaults|HTML::Mason::Params/data_cache_defaults> parameter.
  1577.  
  1578. =head2 Accessing a Cache Externally
  1579.  
  1580. To access a component's cache from outside the component (e.g. in an
  1581. external Perl script), you'll need have the following information:
  1582.  
  1583. =over
  1584.  
  1585. =item *
  1586.  
  1587. the namespace associated with the component. The function
  1588. C<HTML::Mason::Utils::data_cache_namespace>,
  1589. given a component id (usually just the component path), returns the
  1590. namespace.
  1591.  
  1592. =item *
  1593.  
  1594. the cache_root, for file-based caches only. Defaults to the
  1595. "cache" subdirectory under the Mason data directory.
  1596.  
  1597. =back
  1598.  
  1599. Given this information you can get a handle on the component's cache.
  1600. For example, the following code removes a cache item for component
  1601. F</foo/bar>, assuming the data directory is F</usr/local/www/mason>
  1602. and the cache subclass is C<FileCache>:
  1603.  
  1604.     use HTML::Mason::Utils qw(data_cache_namespace);
  1605.  
  1606.     my $cache = new Cache::FileCache
  1607.         ( { namespace => data_cache_namespace("/foo/bar"),
  1608.         cache_root => "/usr/local/www/mason/cache" } );
  1609.  
  1610.     # Remove one key
  1611.     $cache->remove('key1');
  1612.  
  1613.     # Remove all keys
  1614.     $cache->clear;
  1615.  
  1616. =head2 Mason 1.0x Cache API
  1617.  
  1618. For users upgrading from 1.0x and earlier, any existing $m-E<gt>cache
  1619. code will be incompatible with the new API. However, if you wish to
  1620. continue using the 1.0x cache API for a while, you (or your
  1621. administrator) can set L<data_cache_api|HTML::Mason::Params/data_cache_api> to '1.0'. All of the
  1622. $m-E<gt>cache options with the exception of C<tie_class> should be
  1623. supported.
  1624.  
  1625. The C<access_data_cache> function is no longer available; this will
  1626. need to be converted to use C<Cache::Cache> directly, as described in
  1627. the L<previous section|HTML::Mason::Devel/Accessing a Cache
  1628. Externally>.
  1629.  
  1630. =head1 WEB-SPECIFIC FEATURES
  1631.  
  1632. =head2 Sending HTTP Headers
  1633.  
  1634. Mason automatically sends HTTP headers via C<< $r->send_http_header >>
  1635. but it will not send headers if they've already been sent manually.
  1636.  
  1637. To determine the exact header behavior on your system, you need to
  1638. know whether your server's default is to have L<autoflush|HTML::Mason::Params/autoflush> on or off.
  1639. Your administrator should have this information.  If your administrator
  1640. doesn't know then it is probably off, the default.
  1641.  
  1642. With autoflush off the header situation is extremely simple: Mason
  1643. waits until the very end of the request to send headers. Any component
  1644. can modify or augment the headers.
  1645.  
  1646. With autoflush on the header situation is more complex.  Mason will
  1647. send headers just before sending the first output.  This means that if
  1648. you want to affect the headers with autoflush on, you must do so
  1649. before any component sends any output.  Generally this takes place in
  1650. an C<< <%init> >> section.
  1651.  
  1652. For example, the following top-level component calls another component
  1653. to see whether the user has a cookie; if not, it inserts a new cookie
  1654. into the header.
  1655.  
  1656.     <%init>
  1657.     my $cookie = $m->comp('/shared/get_user_cookie');
  1658.     if (!$cookie) {
  1659.     $cookie = new CGI::Cookie (...);
  1660.     $r->header_out('Set-cookie' => $cookie);
  1661.     }
  1662.     ...
  1663.     </%init>
  1664.  
  1665. With autoflush off this code will always work.  Turn autoflush on and
  1666. this code will only work as long as F</shared/get_user_cookie> doesn't
  1667. output anything (given its functional nature, it shouldn't).
  1668.  
  1669. The administrator can turn off automatic header sending via the
  1670. L<auto_send_headers|HTML::Mason::Params/auto_send_headers> parameter.
  1671.  
  1672. =head2 Returning HTTP Status
  1673.  
  1674. The value returned from the top-most component becomes the status code
  1675. of the request. If no value is explicitly returned, it defaults to OK
  1676. (0).
  1677.  
  1678. Simply returning an error status (such as 404) from the top-most
  1679. component has two problems in practice. First, the decision to return
  1680. an error status often resides further down in the component
  1681. stack. Second, you may have generated some content by the time this
  1682. decision is made. (Both of these are more likely to be true when using
  1683. autohandlers.)
  1684.  
  1685. Thus the safer way to generate an error status is
  1686.  
  1687.    $m->clear_buffer;
  1688.    $m->abort($status);
  1689.  
  1690. C<< $m->abort >> bypasses the component stack and ensures that
  1691. C<$status> is returned from the top-most component. It works by
  1692. throwing an exception. If you wrapped this code (directly or
  1693. indirectly) in an eval, you must take care to rethrow the exception,
  1694. or the status will not make it out:
  1695.  
  1696.    eval { $m->comp('...') };
  1697.    if (my $err = $@) {
  1698.       if ($m->aborted) {
  1699.           die $err;
  1700.       } else {
  1701.           # deal with non-abort exceptions
  1702.       }
  1703.    }
  1704.  
  1705. =head3 Filters and $m->abort
  1706.  
  1707. A filter section will still be called after a component aborts with
  1708. C<< $m->abort >>.  You can always check C<< $m->aborted >> in your
  1709. C<< <%filter> >> block if you don't want to run the filter after an abort.
  1710.  
  1711.   <%filter>
  1712.   unless ( $m->aborted ) {
  1713.       $_ .= ' filter stuff';
  1714.   }
  1715.   </%filter>
  1716.  
  1717. =head2 External Redirects
  1718.  
  1719. Because it is so commonly needed, Mason 1.1x and on provides an
  1720. external redirect method:
  1721.  
  1722.     $m->redirect($url);    # Redirects with 302 status
  1723.  
  1724. This method uses the clear_buffer/abort technique mentioned above,
  1725. so the same warnings apply regarding evals.
  1726.  
  1727. Also, if you generate any output I<after> calling C<< $m->redirect >>,
  1728. then this output will be sent, and will break the redirect.  For
  1729. example:
  1730.  
  1731.   % eval { $m->comp('redirect', ...) };
  1732.  
  1733.   % die $@ if $@;
  1734.  
  1735. The blank line between the two Perl lines is new output generated
  1736. after the redirect.  Either remove it or call C<< $m->clear_buffer >>
  1737. immediately before calling C<die()>.
  1738.  
  1739. =head2 Internal Redirects
  1740.  
  1741. There are two ways to perform redirects that are invisible to the
  1742. client.
  1743.  
  1744. First, you can use a Mason subrequest (see L</Subrequests>). This only
  1745. works if you are redirecting to another Mason page.
  1746.  
  1747. Second, you can use Apache's internal_redirect method, which works
  1748. whether or not the new URL will be handled by Mason.  Use it this way:
  1749.  
  1750.     $r->internal_redirect($url);
  1751.     $m->auto_send_headers(0);
  1752.     $m->clear_buffer;
  1753.     $m->abort;
  1754.  
  1755. The last three lines prevent the original request from accidentally
  1756. generating extra headers or content.
  1757.  
  1758. =head1 USING THE PERL DEBUGGER
  1759.  
  1760. You can use the perl debugger in conjunction with a live
  1761. mod_perl/Mason server with the help of Apache::DB, available from
  1762. CPAN. Refer to the Apache::DB documentation for details.
  1763.  
  1764. The only tricky thing about debugging Mason pages is that components
  1765. are implemented by anonymous subroutines, which are not easily
  1766. breakpoint'able. To remedy this, Mason calls the dummy subroutine
  1767. C<debug_hook> at the beginning of each component. You can breakpoint
  1768. this subroutine like so:
  1769.  
  1770.     b HTML::Mason::Request::debug_hook
  1771.  
  1772. debug_hook is called with two parameters: the current Request object
  1773. and the full component path. Thus you can breakpoint specific
  1774. components using a conditional on $_[1]:
  1775.  
  1776.     b HTML::Mason::Request::debug_hook $_[1] =~ /component name/
  1777.  
  1778. You can avoid all that typing by adding the following to your
  1779. ~/.perldb file:
  1780.  
  1781.     # Perl debugger aliases for Mason
  1782.     $DB::alias{mb} = 's/^mb\b/b HTML::Mason::Request::debug_hook/';
  1783.  
  1784. which reduces the previous examples to just: 
  1785.  
  1786.     mb
  1787.     mb $_[1] =~ /component name/
  1788.  
  1789. Mason normally inserts '#line' directives into compiled components so
  1790. that line numbers are reported relative to the source file. Depending
  1791. on your task, this can be a help or a hindrance when using the
  1792. debugger.  The administrator can turn off '#line' directives with
  1793. the L<use_source_line_numbers|HTML::Mason::Params/use_source_line_numbers> parameter.
  1794.  
  1795. =head1 OBJECT-ORIENTED TECHNIQUES
  1796.  
  1797. Earlier you learned how to assign a common template to an entire
  1798. hierarchy of pages using I<autohandlers>. The basic template looks like:
  1799.  
  1800.     header HTML
  1801.     % $m->call_next;
  1802.     footer HTML
  1803.  
  1804. However, sometimes you'll want a more flexible template that adjusts
  1805. to the requested page.  You might want to allow each page or
  1806. subsection to specify a title, background color, or logo image while
  1807. leaving the rest of the template intact. You might want some pages or
  1808. subsections to use a different template, or to ignore templates
  1809. entirely.
  1810.  
  1811. These issues can be addressed with the object-oriented style
  1812. primitives introduced in Mason 0.85.
  1813.  
  1814. Note: we use the term object-oriented loosely. Mason borrows concepts
  1815. like inheritance, methods, and attributes from object methodology but
  1816. implements them in a shallow way to solve a particular set of
  1817. problems. Future redesigns may incorporate a deeper object
  1818. architecture if the current prototype proves successful.
  1819.  
  1820. =head2 Determining inheritance
  1821.  
  1822. Every component may have a single I<parent>. The default parent is a
  1823. component named C<autohandler> in the closest parent directory.  This
  1824. rule applies to autohandlers too: an autohandler may not have itself
  1825. as a parent but may have an autohandler further up the tree as its
  1826. parent.
  1827.  
  1828. You can use the C<inherit> flag to override a component's parent:
  1829.  
  1830.     <%flags>
  1831.     inherit => '/foo/bar'
  1832.     </%flags>
  1833.  
  1834. If you specify undef as the parent, then the component inherits from
  1835. no one.  This is how to suppress templates.
  1836.  
  1837. Currently there is no way to specify a parent dynamically at run-time,
  1838. or to specify multiple parents.
  1839.  
  1840. =head2 Content wrapping
  1841.  
  1842. At page execution time, Mason builds a chain of components from the
  1843. called component, its parent, its parent's parent, and so
  1844. on. Execution begins with the top-most component; calling
  1845. C<< $m->call_next >> passes control to the next component in the chain.  This
  1846. is the familiar autohandler "wrapping" behavior, generalized for any
  1847. number of arbitrarily named templates.
  1848.  
  1849. =head2 Accessing methods and attributes
  1850.  
  1851. A template can access methods and/or attributes of the requested
  1852. page. First, use C<< $m->request_comp >> to get a handle on the
  1853. appropriate component:
  1854.  
  1855.     my $self = $m->request_comp;
  1856.  
  1857. $self now refers to the component corresponding to the requested page
  1858. (the component at the end of the chain).
  1859.  
  1860. To access a method for the page, use C<call_method>:
  1861.  
  1862.     $self->call_method('header');
  1863.  
  1864. This looks for a method named 'header' in the page component.  If no
  1865. such method exists, the chain of parents is searched upwards, until
  1866. ultimately a "method not found" error occurs. Use 'method_exists' to
  1867. avoid this error for questionable method calls:
  1868.  
  1869.     if ($self->method_exists('header')) { ...
  1870.  
  1871. The component returned by the C<< $m->request_comp >> method never
  1872. changes during request execution.  In contrast, the component returned
  1873. by C<< $m->base_comp >> may change several times during request
  1874. execution.
  1875.  
  1876. When execution starts, the base component is the same as the requested
  1877. component.  Whenever a component call is executed, the base component
  1878. may become the component that was called.  The base component will
  1879. change for all component calls B<except> in the following cases:
  1880.  
  1881. =over
  1882.  
  1883. =item *
  1884.  
  1885. A component is called via its component object rather than its path,
  1886. for example:
  1887.  
  1888.   <& $m->fetch_comp('/some/comp'), foo => 1 &>
  1889.  
  1890. =item *
  1891.  
  1892. A method is called via the use of C<SELF:>, C<PARENT:>, or
  1893. C<REQUEST:>.  These are covered in more detail below.
  1894.  
  1895. =back
  1896.  
  1897. In all other cases, the base component is the called component or the
  1898. called component's owner component if that called component is a
  1899. method.
  1900.  
  1901. As hinted at above, Mason provides a shortcut syntax for method calls.
  1902.  
  1903. If a component call path starts with C<SELF:>, then Mason will start
  1904. looking for the method (the portion of the call after C<SELF:>), in
  1905. the base component.
  1906.  
  1907.     <& SELF:header &>
  1908.     $m->comp('SELF:header')
  1909.  
  1910. If the call path starts with C<PARENT:>, then Mason will start looking
  1911. in the current component's parent for the named method.
  1912.  
  1913.     <& PARENT:header &>
  1914.     $m->comp('PARENT:header')
  1915.  
  1916. In the context of a component path, PARENT is shorthand for
  1917. C<< $m->current_comp->parent >>.
  1918.  
  1919. If the call path begins with C<REQUEST:>, then Mason looks for the
  1920. method in the requested component.  REQUEST is shorthand for C<<
  1921. $m->request_comp >>.
  1922.  
  1923. The rules for attributes are similar. To access an attribute for the
  1924. page, use C<attr>:
  1925.  
  1926.     my $color = $self->attr('color')
  1927.  
  1928. This looks for an attribute named 'color' in the $self component. If
  1929. no such attribute exists, the chain of parents is searched upwards,
  1930. until ultimately an "attribute not found" error occurs. Use
  1931. C<attr_exists> or C<attr_if_exist> to avoid this error for
  1932. questionable attributes:
  1933.  
  1934.     if ($self->attr_exists('color')) { ...
  1935.  
  1936.     my $color = $self->attr_if_exists('color'); # if it doesn't exist $color is undef
  1937.  
  1938. =head2 Sharing data
  1939.  
  1940. A component's main body and its methods occupy separate lexical
  1941. scopes. Variables declared, say, in the C<< <%init> >> section of the main
  1942. component cannot be seen from methods.
  1943.  
  1944. To share variables, declare them either in the C<< <%once> >> or C<< <%shared> >>
  1945. section. Both sections have an all-inclusive scope. The C<< <%once> >>
  1946. section runs once when the component loads; its variables are
  1947. persistent for the lifetime of the component. The C<< <%shared> >> section
  1948. runs once per request (when needed), just before any code in the
  1949. component runs; its variables last only til the end of the request.
  1950.  
  1951. In the following example, various sections of code require information
  1952. about the logged-in user. We use a C<< <%shared> >> section to fetch these
  1953. in a single request.
  1954.  
  1955.     <%attr>
  1956.     title=>sub { "Account for $full_name" }
  1957.     </%attr>
  1958.  
  1959.     <%method lefttoc>
  1960.     <i><% $full_name %></i>
  1961.     (<a href="logout.html">Log out</a>)<br>
  1962.     ...
  1963.     </%method>
  1964.  
  1965.     Welcome, <% $fname %>. Here are your options:
  1966.  
  1967.     <%shared>
  1968.     my $dbh = DBI::connect ...;
  1969.     my $user = $r->connection->user;
  1970.     my $sth = $dbh->prepare("select lname,fname, from users where user_id = ?");
  1971.     $sth->execute($user);
  1972.     my ($lname, $fname) = $sth->fetchrow_array;
  1973.     my $full_name = "$first $last";
  1974.     </%shared>
  1975.  
  1976. C<< <%shared> >> presents a good alternative to C<< <%init> >> when data is needed
  1977. across multiple scopes. Outside these situations, C<< <%init> >> is preferred
  1978. for its slightly greater speed and predictable execution model.
  1979.  
  1980. =head2 Example
  1981.  
  1982. Let's say we have three components:
  1983.  
  1984.     /autohandler
  1985.     /products/autohandler
  1986.     /products/index.html
  1987.  
  1988. and that a request comes in for /products/index.html.
  1989.  
  1990. F</autohandler> contains a general template for the site, referring to a
  1991. number of standard methods and attributes for each page:
  1992.  
  1993.     <head>
  1994.     <title><& SELF:title &></title>
  1995.     </head>
  1996.     <body bgcolor="<% $self->attr('bgcolor') %>">
  1997.     <& SELF:header &>
  1998.     <table><tr><td>
  1999.  
  2000.     % $m->call_next;
  2001.  
  2002.     </td></tr></table>
  2003.     <& SELF:footer &>
  2004.     </body>
  2005.  
  2006.     <%init>
  2007.     my $self = $m->base_comp;
  2008.     ...
  2009.     </%init>
  2010.  
  2011.     <%attr>
  2012.     bgcolor => 'white'
  2013.     </%attr>
  2014.  
  2015.     <%method title>
  2016.     McGuffey Inc.
  2017.     </%method>
  2018.  
  2019.     <%method header>
  2020.     <h2><& SELF:title &></h2><p>
  2021.     </%method>
  2022.  
  2023.     <%method footer>
  2024.     </%method>
  2025.  
  2026. Notice how we provide defaults for each method and attribute, even if blank.
  2027.  
  2028. F</products/autohandler> overrides some attributes and methods for the
  2029. F</products> section of the site.
  2030.  
  2031.     <%attr>
  2032.     bgcolor => 'beige'
  2033.     </%attr>
  2034.     <%method title>
  2035.     McGuffey Inc.: Products
  2036.     </%method>
  2037.  
  2038.     % $m->call_next;
  2039.  
  2040. Note that this component, though it only defines attributes and
  2041. methods, must call C<< $m->call_next >> if it wants the rest of the
  2042. chain to run.
  2043.  
  2044. F</products/index.html> might override a few attributes, but mainly provides
  2045. a primary section for the body.
  2046.  
  2047. =head1 COMMON TRAPS
  2048.  
  2049. =over
  2050.  
  2051. =item Do not call $r->content or "new CGI"
  2052.  
  2053. Mason calls C<< $r->content >> itself to read request input, emptying
  2054. the input buffer and leaving a trap for the unwary: subsequent calls
  2055. to C<< $r->content >> hang the server. This is a mod_perl "feature" that
  2056. may be fixed in an upcoming release.
  2057.  
  2058. For the same reason you should not create a CGI object like
  2059.  
  2060.   my $query = new CGI;
  2061.  
  2062. when handling a POST; the CGI module will try to reread request input
  2063. and hang. Instead, create an empty object:
  2064.  
  2065.   my $query = new CGI ("");
  2066.  
  2067. such an object can still be used for all of CGI's useful HTML output
  2068. functions. Or, if you really want to use CGI's input functions,
  2069. initialize the object from %ARGS:
  2070.  
  2071.   my $query = new CGI (\%ARGS);
  2072.  
  2073. =back
  2074.  
  2075. =head1 MASON AND SOURCE FILTERS
  2076.  
  2077. Modules which work as source filters, such as C<Switch.pm>, will only
  2078. work when you are using object files.  This is because of how source
  2079. filters are implemented, and cannot be changed by the Mason authors.
  2080.  
  2081. =head1 AUTHORS
  2082.  
  2083. Jonathan Swartz <swartz@pobox.com>, Dave Rolsky <autarch@urth.org>, Ken Williams <ken@mathforum.org>
  2084.  
  2085. =head1 SEE ALSO
  2086.  
  2087. L<HTML::Mason|HTML::Mason>,
  2088. L<HTML::Mason::Admin|HTML::Mason::Admin>,
  2089. L<HTML::Mason::Request|HTML::Mason::Request>
  2090.  
  2091. =cut
  2092.