The Perl Toolchain Summit needs more sponsors. If your company depends on Perl, please support this very important event.

NAME

Mason::Manual::Components - The building blocks of Mason

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.mc' refers to the file '/opt/web/comps/foo/bar.mc'.

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.

.mc - 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.

.mp - 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.

These extensions are configurable via "pure_perl_extensions" in Mason::Interp and "top_level_extensions" in Mason::Interp.

CALLING COMPONENTS

The initial component in a request, called the page component, is called from run, which in turn may be called from a PSGI handler or an web 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 or scomp 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.

Declaring attributes

Use Moose 'has' syntax to declare attributes within a <%class> section:

    <%class>
    has 'foo';
    has 'bar' => (required => 1);
    has 'baz' => (isa => 'Int', default => 17);
    </%class>

Attributes 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.

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;

$.args will return a hashref of all of the parameters passed to the component when it was created/called, regardless of whether they correspond to declared attributes.

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 overridden 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.mp" and "Base.mc" - you can customize this with the autobase_names parameter.

For example, in this directory hierarchy,

    Base.mp
    main.mc
    colors/
       red.mc
       blue.mc
    flavors/
       Base.mc
       vanilla.mc
       chocolate.mc

assuming that no components have extends flags,

  • /Base.mp is the superclass of /main.mc, /colors/red.mc, /colors/blue.mc, and /flavors/Base.mc.

  • /flavors/Base.mc is the superclass of vanilla.mc and chocolate.mc.

If Base.mp and Base.mc appear in the same directory, they will both be recognized; everything below will inherit from Base.mc, and Base.mc will inherit from Base.mp. 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.mc, the corresponding object file will be

    /home/myapp/data/obj/foo/bar.mc.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.mc',
    16          'source_file'  => '/home/myapp/comps/hi.mc',
    17      );
    18  }
    19  sub _class_cmeta { $_class_cmeta }
    20  
    21  method main {
    22  #line 1 "/home/myapp/comps/hi.mc"
    23      $$_m_buffer .= 'Hi there! The time is ';
    24  #line 1 "/home/myapp/comps/hi.mc"
    25      for ( scalar( scalar(localtime) ) ) { $$_m_buffer .= $_ if defined }
    26  #line 1 "/home/myapp/comps/hi.mc"
    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.

Lines 6-19 create the Mason::Component::ClassMeta object returned from cmeta.

Lines 21-31 contain the main 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.

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 or scomp 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

Mason

AUTHOR

Jonathan Swartz <swartz@pobox.com>

COPYRIGHT AND LICENSE

This software is copyright (c) 2012 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.