NAME
Mason::Manual::Components - The building blocks of Mason
VERSION
version 2.00
DESCRIPTION
The component - a file with a mix of Perl and HTML - is Mason's basic building block. Pages are usually formed by combining the output from multiple components. An article page for a online magazine, for example, might call separate components for the company masthead, ad banner, left table of contents, and article body.
+---------+------------------+
|Masthead | Banner Ad |
+---------+------------------+
| | |
|+-------+|Text of Article ..|
|| || |
||Related||Text of Article ..|
||Stories|| |
|| ||Text of Article ..|
|+-------+| |
| +------------------+
| | Footer |
+---------+------------------+
The top level component decides the overall page layout. Individual cells are then filled by the output of subordinate components. Pages might be built up from as few as one, to as many as hundreds of components, with each component contributing a chunk of HTML.
Splitting up a page into multiple components gives you roughly the same benefits as splitting up an application into multiple classes: encapsulation, reusability, development concurrency, separation of concerns, etc.
Mason actually compiles components down to Perl/Moose classes, which means that many of the tools you use to develop regular classes - profilers, debuggers, and the like - can be used with Mason components with slight tweaking.
COMPONENT FILES
The component root and component paths
When you use Mason, you specify a component root that all component files live under. Thereafter, any component will be referred to by its virtual path relative to the root, rather than its full filename.
For example, if the component root is '/opt/web/comps', then the component path '/foo/bar.m' refers to the file '/opt/web/comps/foo/bar.m'.
It is also possible to specify multiple component roots, ala Perl's @INC
, in which case a component path might refer to one of several files.
Component file extensions
By default Mason facilitates and enforces standard file extensions for components.
- .m - top-level component
-
A top-level component can serve as the page component in a request.
- .mi - internal component
-
An internal component can only be accessed from other components.
- .pm - pure-perl component
-
A pure-perl component contains only code; it is parsed as if its entire content was within a %class block. You do not need to (and are not allowed to) include Mason tags in this component, and it will not produce any output if called. This is just a way of defining a class that other components can easily interact with and extend. Some applications include: controller logic, web form handlers, and autobase components.
CALLING COMPONENTS
The initial component in a request, called the page component, is called from "run" in Mason::Interp, which in turn may be called from a PSGI handler or an MVC framework view depending on your setup. See Mason::Manual::RequestDispatch for more information about how the page component is chosen.
A component can call another component with the <& &> tag:
<& /path/to/comp.mi, name=>value, ... &>
or via the "comp" in Mason::Request or "scomp" in Mason::Request methods:
<%init>
$m->comp('/some/component.mi', foo => 5);
my $output = $m->scomp('/some/other/component.mi');
</%init>
From the implementation perspective, calling a component means creating a new instance of the component's class with the specified parameters, and then calling method handle
(for the page component) or main
(for an internal component) on the instance.
ATTRIBUTES
You can declare attributes in components and pass them when calling components.
Components are read-write by default
Mason::Component::Moose imports MooseX::HasDefaults::RW into all components, which makes attributes read-write unless stated otherwise. This is not considered best practice for general OO programming, but component instances are short-lived and not usually accessed outside of their class so we feel the convenience is warranted.
Declaring incoming attributes - <%args>
The <%args>
block is the most convenient way to declare incoming attributes:
<%args>
$.a
$.b => 'default value'
$.c => (isa => 'Str', default => 'something')
</%args>
The '$.' prefix on each line is optional and harmless. This is equivalent to the following Moose syntax:
<%class>
has 'a' => ();
has 'b' => (default => 'default value');
has 'c' => (isa => 'Str',
default => 'something');
</%class>
and as mentioned above there is an implicit "is => 'rw'" in each.
Declaring internal attributes - <%shared>
The <%shared>
block lets you define attributes that are shared between all the methods of the component, but cannot be initialized from the outside. The syntax is idental:
<%shared>
d
e => 'default value'
f => (isa => 'Str', default => 'something')
</%shared>
and the translation is nearly identical:
<%class>
has 'd' => (init_arg => 1);
has 'e' => (init_arg => 1, default => 'default value');
has 'f' => (init_arg => 1,
isa => 'Str',
default => 'something');
</%class>
except that all are declared with init_arg => 1
(meaning they can't be passed in).
Comments and blank lines in attribute declarations
You may place a '#' comment at the end of an attribute line or on its own line, and you may put blank lines in <%args>
or << <%shared> >> sections. Both are ignored.
<%args>
g # a comment
# another comment
h
</%args>
Accessing attributes
A declared attribute 'foo' can be accessed inside the component via the Perl6-ish syntax
$.foo
which is transformed by DollarDot to
$self->foo
In the rest of this documentation we will use $.
notation, but feel free to substitute $self->
conceptually and/or in reality.
To set the attribute, you must use:
$.foo(5);
unless you're using LvalueAttributes, in which case you can say
$.foo = 5;
$.cmeta->args
will return a hashref of all of the attributes passed to the component when it was created/called.
METHODS
The base component class, Mason::Component, has but a few built-in methods: handle, render, wrap, main, m, and cmeta.
The main
method contains the mix of HTML and Perl in the main part of the component.
You can add other methods that output HTML via the <$method>
section; these methods automatically have access to $self
and $m
.
<%method leftcol>
<table><tr>
<td><% $foo %></td>
...
</tr></table>
</%method>
...
<% # call leftcol method and insert HTML here %>
<% $.leftcol %>
Methods can also take argument lists:
<%method list ($style, $items)>
<ul style="<% $style %>">
% foreach my $item (@$items) {
...
% }
</ul>
</%method>
Both main
and other methods defined with <%method>
automatically get a return undef
at their end, so that they don't accidentally return values.
Pure-Perl methods that return a value can be added within the << <%class> >> section.
<%class>
method multiply ($a, $b) {
return $a * $b;
}
</%class>
...
<%init>
my $value = $.multiply(5, 6);
</%init>
Note that Method::Signatures::Simple provides the method
keyword and argument lists; this is used throughout Mason internals as well. If you prefer straight-up Perl subroutines:
<%class>
sub multiply {
my ($self, $a, $b) = @_;
return $a * $b;
}
</%class>
Output versus return value
Most Mason methods output content such as HTML. The content is not actually returned, but is instead appended to an implicit buffer. This is slightly more complicated but is necessary for supporting streaming applications.
When Mason generates main
and other methods declared with <%method>
, it puts an implicit
return undef;
at the bottom of the method, so that unless you specify otherwise, there will be no return value. This is important because of syntactical shortcuts like
<% inner() %>
<% $.leftcol %>
which would (undesirably) print the return value if it existed.
INHERITANCE
Each component class naturally inherits from (or 'extends') a superclass. The default superclass for components is Mason::Component, but this may be overriden in two ways: the extends flag and autobase components.
Extends flag
A component can declare its superclass via the extends
flag:
<%flags>
extends => '/some/other/component'
</%flags>
The path may be absolute as shown above, or relative to the component's path.
Note that including a raw extends
keyword in a <%class>
section will not work reliably.
Autobase components
Autobase components are specially named components that automatically become the superclass of all components in their directory and subdirectories. The default names are "Base.pm" and "Base.m" - you can customize this with the autobase_names
parameter.
For example, in this directory hierarchy,
Base.pm
main.m
colors/
red.m
blue.m
flavors/
Base.m
vanilla.m
chocolate.m
assuming that no components have extends
flags,
/Base.pm is the superclass of /main.m, /colors/red.m, /colors/blue.m, and /flavors/Base.m.
/flavors/Base.m is the superclass of vanilla.m and chocolate.m.
If Base.pm
and Base.m
appear in the same directory, they will both be recognized; everything below will inherit from Base.m
, and Base.m
will inherit from Base.pm
. This might be useful for separating "Content wrapping" from shared method definitions, for example.
GENERATED CLASS
It can be helpful to understand how Mason generates component classes, especially for troubleshooting unexpected component behavior.
Object files
Mason writes the generated class into an object file, located in
<mason_data_directory>/obj/<component_path>.mobj
For example if your data directory is /home/myapp/data and the component path is /foo/bar.m, the corresponding object file will be
/home/myapp/data/obj/foo/bar.m.mobj
The object file is rewritten whenever Mason detects a change in the source file.
Object files aren't generated in a particularly clean way, so if you're going to be peeking at them, consider using the TidyObjectfiles plugin.
Class name
The class name is determined at load time by prepending the Mason::Interp/component_class_prefix
to the component path, which slashes replaced with '::'. Two different Interp objects loading the same object file will thus create two separate classes.
A simple example
Here's a simple component:
Hello world! The local time is <% scalar(localtime) %>.
and here's the class that gets generated for it, filtered with TidyObjectFiles
:
1 use Mason::Component::Moose;
2 our ( $m, $_m_buffer );
3 *m = \$Mason::Request::current_request;
4 *_m_buffer = \$Mason::Request::current_buffer;
5 sub _inner { inner() }
6 my $_class_cmeta;
7
8 method _set_class_cmeta ($interp) {
9 $_class_cmeta = $interp->component_class_meta_class->new(
10 'class' => CLASS,
11 'dir_path' => '/',
12 'interp' => $interp,
13 'is_top_level' => '1',
14 'object_file' => __FILE__,
15 'path' => '/hi.m',
16 'source_file' => '/home/myapp/comps/hi.m',
17 );
18 }
19 sub _class_cmeta { $_class_cmeta }
20
21 method main {
22 #line 1 "/home/myapp/comps/hi.m"
23 $$_m_buffer .= 'Hi there! The time is ';
24 #line 1 "/home/myapp/comps/hi.m"
25 for ( scalar( scalar(localtime) ) ) { $$_m_buffer .= $_ if defined }
26 #line 1 "/home/myapp/comps/hi.m"
27 $$_m_buffer .= '.
28 ';
29
30 return;
31 }
(Caveat: the above is as of time of writing and may well be out of date with the current code generator, but it is accurate enough for explanatory purposes.)
Line 1 brings in Mason::Component::Moose, which imports Moose, CLASS, Method::Signatures::Simple and other things into the current package.
Lines 2-4 defines two dynamic globals, $m
(the current request) and $_m_buffer
(the current output buffer). These are aliased so that they can be changed for every component from a single place. See also Mason::Manual::ComponentGlobals.
Lines 6-19 create the Mason::Component::ClassMeta object returned from "cmeta" in Mason::Component.
Lines 21-31 contain the "main" in Mason::Component method, which encapsulates all the output and Perl statements in the component that aren't explicitly inside a <%method>
or <%class>
block.
Lines 22, 24, and 26 contain '#line' statements which make error messages appear to come from the source file rather than the object file (and hence more useful). This can be disabled with "no_source_line_numbers" in Mason::Interp.
Lines 23, 25, and 27 output plain strings or the results of code by appending them to the current output buffer. The current output buffer can change within a request, for example when "capture" in Mason::Request or "scomp" in Mason::Request is called.
Two things that would be in a normal class are missing above: the package
and extends
declarations. These are added dynamically when the object file is evaluated.
SEE ALSO
AUTHOR
Jonathan Swartz <swartz@pobox.com>
COPYRIGHT AND LICENSE
This software is copyright (c) 2011 by Jonathan Swartz.
This is free software; you can redistribute it and/or modify it under the same terms as the Perl 5 programming language system itself.