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