__END__

=pod

=head1 NAME

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

=head1 DESCRIPTION

The I<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.

=head1 COMPONENT FILES

=head2 The component root and component paths

When you use Mason, you specify a L<component root|Mason::Interp/comp_root>
that all component files live under. Thereafter, any component will be referred
to by its virtual I<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 C<@INC>, in
which case a component path might refer to one of several files.

=head2 Component file extensions

By default Mason facilitates and enforces standard file extensions for
components.

=over

=item .mc - top-level component

A top-level component can serve as the page component in a request.

=item .mi - internal component

An internal component can only be accessed from other components.

=item .mp - pure-perl component

A pure-perl component contains only code; it is parsed as if its entire content
was within a L<%class|Mason::Manual::Syntax/E<lt>%classE<gt>> 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 L<autobase
components|/Autobase components>.

=back

These extensions are configurable via L<Mason::Interp/pure_perl_extensions> and
L<Mason::Interp/top_level_extensions>.

=head1 CALLING COMPONENTS

The initial component in a request, called the page component, is called from
L<run|Mason::Interp/run>, which in turn may be called from a PSGI handler or an
web framework view depending on your setup. See
L<Mason::Manual::RequestDispatch> for more information about how the page
component is chosen.

A component can call another component with the L<E<lt>& &E<gt>
tag|Mason::Manual::Syntax/CALLING COMPONENTS>:

    <& /path/to/comp.mi, name=>value, ... &>

or via the L<comp|Mason::Request/comp> or L<scomp|Mason::Request/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 C<handle> (for the page component) or C<main> (for an internal
component) on the instance.

=head1 ATTRIBUTES

You can declare attributes in components and pass them when calling components.

=head2 Declaring attributes

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

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

=head2 Attributes are read-write by default

L<Mason::Component::Moose> imports
L<MooseX::HasDefaults::RW|MooseX::HasDefaults> 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.

=head2 Accessing attributes

A declared attribute 'foo' can be accessed inside the component via the
Perl6-ish syntax

    $.foo

which is transformed by L<DollarDot|Mason::Plugin::DollarDot> to

    $self->foo

In the rest of this documentation we will use C<$.> notation, but feel free to
substitute C<< $self-> >> conceptually and/or in reality.

To set the attribute, you must use:

    $.foo(5);

unless you're using L<LvalueAttributes|Mason::Plugin::LvalueAttributes>, in
which case you can say

    $.foo = 5;

C<< $.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.

=head1 METHODS

The base component class, L<Mason::Component>, has but a few built-in methods:
handle, render, wrap, main, m, and cmeta.

The C<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 C<< <$method> >> section;
these methods automatically have access to C<$self> and C<$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 C<main> and other methods defined with C<< <%method> >> automatically get
a C<< 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 L<Method::Signatures::Simple> provides the C<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>

=head2 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 C<main> and other methods declared with C<< <%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.

=head1 INHERITANCE

Each component class naturally inherits from (or 'extends') a superclass. The
default superclass for components is L<Mason::Component|Mason::Component>, but
this may be overridden in two ways: the I<extends flag> and I<autobase
components>.

=head2 Extends flag

A component can declare its superclass via the C<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 C<extends> keyword in a C<< <%class> >> section will
not work reliably.

=head2 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
C<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 C<extends> flags,

=over

=item *

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

=item *

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

=back

If C<Base.mp> and C<Base.mc> appear in the same directory, they will both be
recognized; everything below will inherit from C<Base.mc>, and C<Base.mc> will
inherit from C<Base.mp>. This might be useful for separating L<content
wrapping|Mason::Component/wrap> from shared method definitions, for example.

=head1 GENERATED CLASS

It can be helpful to understand how Mason generates component classes,
especially for troubleshooting unexpected component behavior.

=head2 Object files

Mason writes the generated class into an I<object file>, located in

    <mason_data_directory>/obj/<component_path>.mobj

For example if your L<data directory|Mason::Interp/data_dir> is
F</home/myapp/data> and the component path is F</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 L<TidyObjectfiles
plugin|Mason::Plugin::TidyObjectfiles>.

=head2 Class name

The class name is determined at load time by prepending the
C<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.

=head2 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
C<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 L<Mason::Component::Moose>, which imports L<Moose>, L<CLASS>,
L<Method::Signatures::Simple> and other things into the current package.

Lines 2-4 defines two dynamic globals, C<$m> (the current request) and
C<$_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 L<Mason::Component::ClassMeta> object returned from
L<cmeta|Mason::Component/cmeta>.

Lines 21-31 contain the L<main|Mason::Component/main> method, which
encapsulates all the output and Perl statements in the component that aren't
explicitly inside a C<< <%method> >> or C<< <%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
L<no_source_line_numbers|Mason::Interp/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 L<capture|Mason::Request/capture> or
L<scomp|Mason::Request/scomp> is called.

Two things that would be in a normal class are missing above: the C<package>
and C<extends> declarations. These are added dynamically when the object file
is evaluated.

=head1 SEE ALSO

L<Mason|Mason>

=head1 AUTHOR

Jonathan Swartz <swartz@pobox.com>

=head1 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.

=cut