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