Mason:...ponents(3pm)

πŸ“¦
version 2.24 Β· 2 versions
  • 2.24 Β· debian bookworm, debian trixie, ubuntu noble, ubuntu resolute, ubuntu stonking (latest)
  • 2.24 Β· ubuntu jammy
, in debian bookworm, debian trixie, ubuntu noble, ubuntu resolute, ubuntu stonking

πŸ’– NAME πŸ’–

Mason::Manual::Components β€” the building blocks of Mason, bestie. This is the Mason:...ponents(3pm) page, and it's part one of two, so buckle up πŸŽ€


✨ DESCRIPTION ✨

Okay so the component? It's a file that's a lil mix of Perl and HTML, and it's literally Mason's basic building block. Pages are usually made by smushing together the output of multiple components. Picture an article page for an online magazine β€” it might call separate components for the company masthead, the ad banner, the left table of contents, and the article body. Iconic, right? πŸ‘‘

+---------+------------------+
|Masthead | Banner Ad        |
+---------+------------------+
|         |                  |
|+-------+|Text of Article ..|
||       ||                  |
||Related||Text of Article ..|
||Stories||                  |
||       ||Text of Article ..|
|+-------+|                  |
|         +------------------+
|         | Footer           |
+---------+------------------+

The top level component decides the overall page layout. Then individual cells get 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. (Not me building an entire website out of 200 tiny files πŸ’…)

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. It's giving actual software engineering, fr fr.

And the tea? 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. Slay πŸ”₯


🌸 COMPONENT FILES 🌸

The component root and component paths

When you use Mason, you specify a component root that all component files live under. After that, any component gets referred to by its virtual path relative to the root, rather than its full filename. So much cleaner, honestly 🧚

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. Pick your fighter 😌

Component file extensions

By default Mason facilitates and enforces standard file extensions for components. Here's the lineup:

  • .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. Customize away, bestie ✨


πŸ’… 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. That's the whole vibe check πŸ¦‹


πŸŽ€ ATTRIBUTES πŸŽ€

You can declare attributes in components and pass them when calling components. Very demure, very mindful.

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. And honestly? Fair. We said what we said πŸ’…

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. Everything, no filter πŸ’–


⭐ METHODS ⭐

The base component class, Mason::Component, has but a few built-in methods: handle, render, wrap, main, m, and cmeta. Short list, big power.

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. Built-in safety, love that for us 🫢

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. (Streaming is the moment, we don't argue with the moment πŸ’€)

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. So yeah β€” that's why the return undef; is there. It's protecting you from yourself πŸ™ˆ


🌈 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. Do not do it. We're telling you for your own good 😭

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. Main character energy, but for directories πŸ‘‘

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. Two bases, one chain β€” the way that works out is actually gorgeous ✨


part 2 incoming, don't go anywhere bestie πŸ’œ

✨ GENERATED CLASS ✨

okay bestie, real talk: knowing how Mason makes component classes is so helpful, especially when a component is acting up and you're like "why are you like this??" 😭

πŸ—‚οΈ Object files πŸ—‚οΈ

Mason writes the generated class into an object file, and it lives at:

<mason_data_directory>/obj/<component_path>.mobj

so if your data directory is /home/myapp/data and your component path is /foo/bar.mc, the object file is gonna be:

/home/myapp/data/obj/foo/bar.mc.mobj

Whenever Mason spots a change in the source file, it rewrites that object file. periodt.

ngl, object files aren't generated in the cleanest way ever, so if you're gonna peek at them, maybe use the TidyObjectfiles plugin. πŸ’…

🏷️ Class name 🏷️

The class name gets determined at load time by prepending the Mason::Interp/component_class_prefix to the component path, and slashes get replaced with '::'. So if two different Interp objects load the same object file, you get two separate classes. no cap.

🌸 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  }

(okay caveat time: this was true as of time of writing, and it might be lowkey out of date with the current code generator, but it's 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 define two dynamic globals, $m (the current request) and $_m_buffer (the current output buffer). They're aliased so you can change them for every component from one single place. πŸ‘‘

Lines 6-19 create the Mason::Component::ClassMeta object that's returned from cmeta. πŸ’–

Lines 21-31 have the main method, which wraps up all the output and Perl statements in the component that aren't explicitly inside a <%method> or <%class> block. πŸŽ€

Lines 22, 24, and 26 have '#line' statements that make error messages look like they come from the source file instead of the object file (so they're actually useful). You can disable this with no_source_line_numbers. πŸ’…

Lines 23, 25, and 27 output plain strings or code results by appending them to the current output buffer. That current output buffer can change within a request, like when capture or scomp is called. 🌈

Two things that would be in a normal class are missing above: the package and extends declarations. These get added dynamically when the object file is evaluated. πŸ¦‹

πŸ‘€ SEE ALSO πŸ‘€

  • Mason

πŸ’Œ AUTHOR πŸ’Œ

  • Jonathan Swartz <swartz@pobox.com>

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.


and that's the whole vibe, bestie 🫢 this page was from perl v5.34.0, dated 2022-05-27, and it's Mason:...ponents(3pm). stay iconic πŸ’…βœ¨

πŸ“¦ where this page comes from