Appendix A. The Mason API

To provide a convenient reference to the main elements of the Mason class hierarchy, we’ve collected the APIs of the Interpreter, Resolver, Compiler, Lexer, ApacheHandler, CGIHandler, Component, and Request classes. The parameters to each class’s new( ) method are listed in Appendix B. Many of these parameters also correspond to simple accessor methods for getting/setting their values; those methods are not listed here, so see Appendix B for a complete list.

We have attempted to show the arguments taken by each method. Replaceable text is shown in angle brackets (<>). indicating a value you must specify. An ellipsis (...) indicates a list of values. Optional arguments are indicated by square brackets ([]). An optional list of arguments doesn’t get both kinds of brackets, because we figure that’s just a list with no elements in it. If alternate sets of parameters can be given (such as comp_source versus comp_file for the Interpreter’s make_component( ) method), we sometimes indicate this by separate listings.

We intend this appendix to be a quick reference; in many cases the official Mason documentation will provide more detail.

Interpreter

The Interpreter is the main entry point for Mason and coordinates the efforts of several other classes. The default Interpreter class is HTML::Mason::Interp .

new(<parameters...>)

Creates a new Mason Interpreter and returns it. See Appendix B for a list of parameters accepted.

Object Properties

compiler( )

Returns the Compiler object associated with this Interpreter.

resolver( )

Returns the Resolver object associated with this Interpreter.

static_source( )

Returns true or false, depending on whether the static_source parameter is currently set for this Interpreter.

autoflush([<true or false>])

Returns true or false, depending on whether the output buffers will be flushed immediately upon receiving output or not. An optional argument sets the value.

autohandler_name( )

Returns the name of the file to be used for Mason’s autohandler mechanism (i.e., "autohandler").

dhandler_name([<name>])

Returns the name of the file to be used for Mason’s dhandler mechanism (i.e., "dhandler"). An optional argument sets the value.

code_cache_max_size([<size>])

Returns the number of bytes allowed for caching of compiled component code. An optional argument sets the value.

ignore_warnings_expr([<regex>])

Returns a regular expression indicating warnings to ignore when calling or compiling components. An optional argument sets the value.

data_cache_defaults([<hash reference>])

Returns a hash reference of parameters that will be passed to the caching methods by default. An optional hash reference argument sets the value.

max_recurse([<integer>])

Returns an integer indicating the level of nesting allowed in component calls, as a deterrent to infinite component call loops. An optional argument sets the value.

use_object_files( )

Returns true or false, depending on whether the Interpreter will cache compiled components to disk as object files.

preloads( )

Returns reference to an array of glob-like patterns specifying components to be loaded when the Interpreter is created.

files_written( )

Returns a list of all files created by the Interpreter. This may be useful if you want to enforce certain file permissions or ownership.

Directories

comp_root( )

A pass-through method to the Resolver method of the same name.

object_dir( )

Returns a string containing the name of the directory in which Mason’s component objects will be cached.

data_dir( )

Returns the current value of the data_dir parameter.

Runtime Methods

exec(<component>, <args...>)

Initiates a new Mason request. The first argument should be the component to execute, specified either as an absolute pathname or as a component object. Any additional arguments will be passed to the component.

load(<absolute component path>)

Returns the component at the path specified by the argument. Throws an exception if no such component exists.

comp_exists(<absolute component path>)

Returns true or false, depending on whether a component exists at the path specified by the argument.

make_component(comp_file => <path> [, name => <string> ])
make_component(comp_source => <string> [, name => <string> ])

Creates a component object and returns it. The text of the component may be specified as a string in the comp_source parameter or as a filename in the comp_file parameter. You may also provide a name parameter to associate with this component. If no name is provided, the name will default to a string like "<anonymous component>".

set_global(<name> => <value>)

Sets the value of a Perl global variable so that it will be available to components at runtime. The first argument names the variable in a string (i.e., '$user'), including the leading $, @, or % character. The remaining arguments specify the value to assign. The name of the variable should not be fully package-qualified with :: characters; the variable will be created in the same package in which components execute.

Request

The Request class represents a chain of components executing in a particular context. A request is begun by invoking the Interpreter’s exec( ) method. The current Request object is available by default in components as the variable $m.

new(<parameters...>)

Creates a new Request object. See Appendix B for a list of parameters accepted. Typically a Request is not created directly, but rather by invoking the Interpreter’s exec( ) method. The default Request class is HTML::Mason::Request , though it is different when using ApacheHandler or CGIHandler.

instance( )

Returns the Request currently running. This can be called as a class method (i.e., HTML::Mason::Interp->instance( )) from code in which $m is unavailable. In a subrequest, the subrequest object, not the main request, will be returned.

Object Properties

interp( )

Returns the Interpreter object associated with this Request.

count( )

Returns the Interpreter’s counter value for this Request.

error_mode([<'fatal’ or ‘output'>])

Returns the string fatal or output, depending on whether error conditions should trigger an exception (fatal) or display an error message in the regular output channel (output). The mode can be set with an optional argument.

error_format([<format>])

Returns a string indicating how error messages will be formatted. The currently available choices are brief, text, line, and html. An optional argument sets the format.

out_method([<subroutine_reference or scalar_reference>])

Returns the current value of the out_method parameter or optionally sets it if you pass a subroutine reference or a scalar reference as an argument.

cgi_object( )

This method is not present in the regular HTML::Mason::Request class, but it is added as a way to access the CGI.pm request object when using HTML::Mason::CGIHandler. It is also added when using HTML::Mason::ApacheHandler with the CGI args_method.

ah()

Only available when using HTML::Mason::ApacheHandler, in which case the Apache Handler object is returned.

apache_req()

Only available when using HTML::Mason::ApacheHandler, in which case the mod_perl request object $r is returned.

Altering the Request Flow

abort([<value>])

Terminates the current Request. You may optionally specify a value to be returned by the Interpreter’s exec( ) method. In a web environment this value will ultimately become the HTTP response code. Accepts an optional exception argument to examine, otherwise $@ will be examined.

aborted( )

Returns true if the current request was aborted (and caught by an eval block), or false otherwise. Accepts an exception argument to examine, otherwise $@ will be examined.

aborted_value( )

If the current request was aborted, this returns the value passed to the abort method.

decline( )

Stops the execution of the current component and passes control to the next applicable dhandler. Any output already generated will be discarded. If no dhandler exists to handle this request, an exception will be thrown.

dhandler_arg( )

If the current request is being handled by a dhandler, this method will return the remainder of the request path with the dhandler’s directory removed. If no dhandler is executing, this method will return undef.

Caching

See Chapter 4 for more information on the data cache and how to use it.

cache(<arguments...>)

Returns the Cache::Cache object that manages this component’s data cache.

cache_self(<arguments...>)

Facilitates automatic caching of the current component’s output and return value. The arguments to cache_self( ) specify how long the cached data should persist, whether it should be associated with a particular key, and the details of how the data should be cached.

Introspection

caller( )

Returns the component that invoked the currently executing component or undef if this is the topmost component executing.

callers([<n>])

When called with no arguments, returns a list of all components currently executing. This is known as the ‘component stack.’ When called with an integer argument n, returns the component n levels up the execution stack. For instance, $m->callers(1) is equivalent to $m->caller.

caller_args(<n>)

Given an integer argument n, returns an array (if called in list context) or a hash reference (if called in scalar context) of the arguments passed to the component n levels up the execution stack.

depth( )

Returns the current depth of the component stack. For instance, with components /autohandler, /dir/autohandler, and /dir/component.html in the default setup, the depth will be 1 when queried in /autohandler, 2 in /dir/autohandler, and 3 in /dir/component.html. If /dir/component.html calls another component, the depth will be 4 inside that component.

Content and Output

print(<strings...>)

A synonym for print( ). This method will output the content of any arguments. In recent versions of Mason you may also print to Perl’s STDOUT filehandle, as this is tied to Mason’s buffers.

clear_buffer( )

Discards the contents of Mason’s output buffers.

flush_buffer( )

Sends the contents of Mason’s output buffers to their destination.

content( )

Returns the content block passed to the current component or undef if this component was called without a content block. The content block will be evaluated in the lexical context of the calling component. See Section 2.3.3.1 in Chapter 2 for more details.

file(<path>)

Given a file path, Mason will look for this file and return its contents as a string.

An absolute path refers to a file on the filesystem. If a relative path is given, Mason will prepend the current component’s directory, if it has one. Otherwise Mason will simply make the path absolute by prepending the system’s root directory to the path.

Fetching/Running Components

These methods deal with fetching and running components. Some of the methods (in particular comp( ) and scomp( )) let you specify the component by path or by supplying a component object, while other methods (fetch_comp( ) and comp_exists( )) allow only a path. For any of these four methods, if a relative pathname is given, it is considered relative to the dir_path of the current component.

fetch_comp(<path>)

Given a string argument specifying a component path, returns the component at that path or undef if no such component exists.

fetch_next( )

Fetches the next component in the content-wrapping chain. This is the same component that will be invoked by the call_next( ) method.

fetch_next_all( )

Fetches all remaining components in the content-wrapping chain and returns them as a list. This is usually called from an autohandler and will return multiple components when multiple autohandlers are in use.

comp(<component>, <arguments...>)

Calls a Mason component. The component is specified by the first argument, which should be either the name of the component to call or a component object. Any remaining arguments to comp( ) are fed to the called component, either as key/value pairs declared in the component’s <%args> section, the special %ARGS variable, or the Perl argument array @_. Any component output will be sent to the current component’s output stream, and the component’s return value will become the return value of comp( ).

scomp(<component>, <arguments...>)

Identical to the comp( ) method, but instead of sending the called component’s output to the output stream, is returned as a string. Any return value from the component will be discarded.

comp_exists(<path>)

Given a string argument, returns true if a component exists with that path or false otherwise.

call_next(<arguments...>)

Calls the next component in the component execution stack. Typically this is used by an autohandler to call the component it is wrapping around. Mason will pass any current component arguments (the %ARGS hash) to the next component, as well as any additional arguments passed to the call_next( ) method.

current_comp( )

Returns an object representing the currently executing component.

request_comp( )

Returns an object representing the component that was originally requested in the Interpreter’s exec( ) method.

base_comp( )

Returns the current base component for methods and attributes. The base component is initially set to the request_comp( ). Calling a component method will set the base component to the component used in the method call. Calling a regular (nonmethod) component will set the base component to the called component.

request_args( )

Returns the arguments passed to the originally requested component. If called in a list context, the arguments will be returned as a list. If called in a scalar context, the arguments will be returned as a hash reference.

Subrequests

make_subrequest(comp => <path>, args => [...], <parameters...>)

Returns a new Request object with the given parameters. Other parameters will be inherited from the current request.

exec( )

Sets the new request in motion with the given arguments passed to the given component. This should be used only when the request was created with the make_subrequest( ) method, since exec( ) can happen only once for each request. In particular, it is illegal to call $m->exec(...) inside a component.

subexec(<component>, <arguments...>)

Combines the make_subrequest and exec methods into one step. Any arguments are passed to the given component, and the subrequest created will inherit all inheritable properties from the current request.

Component

This class represents a Mason component. It may be a file-based component on disk, a component created on the fly, or a method or subcomponent. The default Component class is HTML::Mason::Component::FileBased.

new(<parameters...>)

Creates a new component. See Appendix B for a list of parameters that affect the component behavior.

The new( ) method is not the proper way to create a component from scratch, since components must be associated with an Interpreter. See the make_component( ) Interpreter method if you wish to create a component from scratch.

Object Properties

title( )

Returns a unique string identifying this component.

name( )

Returns a short string identifying this component. There may be more than one component with the same name.

path( )

Returns the path of this component relative to the source root.

dir_path( )

Returns the component’s notion of a current directory, relative to the component root.

source_dir( )

Returns the component’s enclosing directory if it is a file-based component. Note that Mason does not actually chdir( ) to a component’s directory before executing it, so you may need to use source_dir to establish context.

object_file( )

Returns the full pathname of the object file associated with this component or undef if this component is not associated with any object file.

load_time( )

Returns the time this component object (not its source file) was created, in number of seconds since the epoch.

declared_args( )

Returns a hash reference indicating the variables declared in this component’s <%args> section. Each key in this hash reference is the name of a Perl variable (including the initial sigil, $, @, or %), and the value is a hash reference containing (at least) a default key. Its value, in turn, contains Perl code to be evaluated to get the default value for this component argument.

flag(<name>)

Given a string argument, returns the value of the Mason flag by that name for this component, as declared in a <%flags> section. Throws an exception if the argument is not the name of a valid Mason flag. Currently, there is only one flag allowed in <%flags> sections, the inherit flag that specifies a parent component.

Note that flag values do not inherit from parent components.

is_subcomp( )

Returns true if the component is a subcomponent or method or false otherwise.

is_file_based( )

Returns true if the component was loaded from a source or object file or false otherwise.

Component Relationships

subcomps( )

Returns a reference to a hash containing all subcomponents declared by this component, with names as keys and component objects as values. If you provide a string argument, returns only the subcomponent with that name or undef if no such subcomponent exists.

methods( )

Returns a reference to a hash containing all methods declared by this component, with names as keys and component objects as values. If you provide a string argument, returns only the method with that name or undef if no such subcomponent exists.

Note that this does not search for methods in any parent components. See the method_exists and call_method entries in the next section if you wish to perform such a search.

parent( )

Returns the parent component of this component or undef if this component has no parent.

owner( )

If this component is a subcomponent or method, returns the component object in which it was declared.

Inheritance

attr(<name>)

Given a string argument, returns the value of the attribute (declared in an <%attr> block) by that name in this component or its parents. If no such attribute exists, an exception will be thrown.

attr_exists(<name>)

Given a string argument, returns true if an attribute by that name exists in this component or its parents or false otherwise.

attr_if_exists([<name>])

Given a string argument, returns the value of the attribute by that name in this component or its parents. If no such attribute exists, returns undef.

call_method(<name> [, <arguments...>])

Given a string argument, searches for a method by that name in this component or its parents and executes it. If no such method exists, a fatal exception will be thrown.

scall_method(<name> [, <arguments...>])

Just like call_method, but returns the component’s output as a string instead of outputting it. Any return value will be discarded.

method_exists(<name>)

Given a string argument, returns true if a method by that name exists in this component or its parents or false otherwise.

Resolver

The Resolver is responsible for handling the interactions between the Interpreter and the storage medium of component source files. The default resolver class is HTML::Mason::Resolver::File.

new(<parameters...>)

Returns a new Resolver object. See Appendix B for a list of parameters accepted by the new( ) method.

get_info(<path> )

Given a component path, returns an HTML::Mason::ComponentSource object that may be queried to get information about the component source.

comp_root([<new_root>])

Returns the current value of the component root. The value returned may be a string or a reference to an array of arrays, depending on whether you’re using one or several component roots. Optionally sets the value of the component root if you provide an argument, whose form is the same.

comp_root_array( )

Like comp_root( ), but in a list context always returns a list of arrays, one per component root. If there is only one root and its name is unspecified, it will be given the name MAIN. In a scalar context, returns the number of component roots.

glob_path(<pattern> )

Given a “glob"-style pattern, returns a list of paths of all components that match that pattern in the component root.

apache_request_to_comp_path(<Apache request object>)

Given an Apache request object, this method is expected to return a component path, or undef if the request cannot be translated to a component path.

ApacheHandler

The HTML::Mason::ApacheHandler class provides the necessary glue between the Mason Interpreter and the Apache web server’s mod_perl module. Its main task is to accept an incoming Apache request and invoke the Interpreter with the proper parameters for handling that request.

The ApacheHandler class makes the Apache request object available inside components as the global variable $r . This may be an object blessed into the Apache::Request class or the Apache class, depending on whether the Mason administrator has configured the ApacheHandler to use the mod_perl args_method.

ApacheHandler also turns $m, the Request object, into an HTML::Mason::Request::ApacheHandler object by subclassing HTML::Mason::Request.

new(<parameters...>)

Creates a new ApacheHandler object. See Appendix B for a listing of the parameters accepted.

interp([<interpreter>])

Returns the current Interpreter associated with this ApacheHandler. An optional argument sets the value to a new Interpreter.

handle_request($r)

Initiates a Mason request, processing any incoming arguments to the web server and calling the appropriate component.

handler($r)

A wrapper around handle_request( ) suitable for using as a mod_perl “handler.” You must enable PERL_METHOD_HANDLERS when compiling mod_perl in order to use this handler.

prepare_request($r)

Returns a new Mason Request object for the given Apache Request or an HTTP status code if an error was encountered.

apache_status_title([<string>])

Returns the title of the Mason status page generated by Apache::Status. An optional argument sets the title.

args_method( )

Returns the current args_method setting, which can be either mod_perl or CGI depending on whether you’re using Apache::Request or CGI.pm for HTTP argument processing.

decline_dirs([true or false])

Returns true or false, depending on whether requests for directories will be declined or accepted. An optional argument sets the value. If a request for a directory is accepted, it should usually be caught by using a dhandler mechanism, so Mason has a component to execute.

CGIHandler

The HTML::Mason::CGIHandler class is similar to ApacheHandler but runs under the CGI paradigm instead of the mod_perl paradigm. Its task is to accept an incoming CGI request and invoke the Mason Interpreter with the proper parameters for handling that request.

new(<parameters...>)

Creates a new CGIHandler object. See Appendix B for a listing of the parameters accepted.

handle_request( )

Initiates a Mason request, processing any incoming arguments to the web server and calling the appropriate component. The initial component will be the one specified in $ENV{PATH_INFO}.

handle_comp(<component>)

Like handle_request( ), but explicitly specifies the component as an argument, either as a component path or a component object.

handle_cgi_object(<CGI object>)

Also like handle_request( ), but takes component path from the given CGI object’s path_info method. Additionally, this CGI object is available to the called components.

CGIHandler also turns $r, normally the Apache request object, into an HTML::Mason::FakeApache object. It provides the following methods for compatibility with a mod_perl-based setup:

header_out(<header> => <value>)

Adds an outgoing header to the HTTP response.

content_type( )

Sets the content type of the response to the argument given. If you don’t set the content type, the type will be set to text/html by default.

Compiler

The Compiler is responsible for turning a hierarchical component structure, as fed to it by the Lexer, into a usable form. The default Compiler is HTML::Mason::Compiler::ToObject, which creates a Component object.

new(<parameters...>)

Creates a new Compiler object and returns it. Called by the Interpreter object. See Appendix B for a list of parameters accepted.

Object Properties

allow_globals([<variables...>])
allow_globals([undef])

Returns a list of variable names (including the initial $, @, or % type-identifying sigil) that have been declared as allowable globals within components or the number of such variables in a scalar context. The list of allowed globals can optionally be set by passing the variable names (again, including the initial sigils) as arguments. This replaces any previously set globals. To clear the list of allowed globals, pass an argument list containing the single element undef.

my @allowed = $compiler->allow_globals;      # Get list of globals
$compiler->allow_globals('$dbh','%session'); # Set list of globals
$compiler->allow_globals(undef);             # Clear list of globals
add_allowed_globals(<variables...>)

Adds one or more variable names (including the initial $, @, or % type-identifying sigil) to the list of globals allowed within components. Returns a list of variable names (again, including the initial sigils) in a list context or the number of such variables in a scalar context.

object_id( )

Returns a string identifier that uniquely identifies this compiler and its current settings. This identifier is used mainly to make sure that components compiled under a different compiler, or under the same compiler with different settings, are declared stale.

compile(comp_source => <string>, name => <string>)

Compiles a component from source text and returns the compiled component. The source text is passed in a comp_source parameter, and a unique identifier for this component is passed in a mandatory name parameter. The compiled component may take any of several forms, but the default HTML::Mason::Compiler::ToObject class returns a bunch of Perl code in a string.

Compilation Callbacks

These are methods called by the Lexer while processing a component source. You may wish to override some of these methods if you’re implementing your own custom Compiler class.

start_component( )

Called by the Lexer when it starts processing a component.

end_component( )

Called by the Lexer when it finishes processing a component.

start_block(block_type => <string>)

Called by the Lexer when it encounters an opening Mason block tag like <%perl> or <%args>. Its main purpose is to keep track of the nesting of different kinds of blocks within each other. The type of block ( init, once, etc.) is passed via the block_type parameter.

end_block(block_type => <string>)

Called by the Lexer when it encounters a closing Mason block tag like </%perl> or </%args>. Like start_block( ), its main purpose is to help maintain syntactic integrity.

*_block(block => <string>, [ block_type => <string> ])

Several compiler methods like doc_block( ) , text_block( ) , and raw_block( ) are called by the Lexer after start_block( ) when it encounters blocks of certain types. These methods actually do the work of putting the body of a block into the compiled data structure.

The methods that follow this pattern are init_block( ) , perl_block( ) , doc_block( ), text_block( ), and raw_block( ). The last method is called for all <%once>, <%cleanup>, <%filter>, <%init>, <%perl>, and <%shared> blocks.

text(text => <string>)

Inserts the text contained in a text parameter into the component for verbatim output.

This is called when the Lexer finds plain text in a component.

variable_declaration( type => <string>, name => <string>, default => <string> )

Inserts a variable declaration from the <%args> section into the component.

The type will be either $, @, or %, indicating a scalar, array, or hash. The name is the variable name without the leading sigil. The default is everything found after the first => on an <%args> block line and may include a comment.

key_value_pair(block_type => <string>, key => <string>, value => <string>)

Inserts a key/value pair from a <%flags> or <%attr> section into the component.

The block_type parameter will be either flags or attr .

start_named_block(block_type => <string>, name => <name>)

Analogous to start_block, earlier in this section, but starts a “named” block (<%method> or <%def>).

end_named_block( )

Called by the Lexer to end a “named” block.

substitution(substitution => <string>, escape => <string>)

Called by the Lexer when it encounters a substitution tag (<% ... %>).

The value of the escape parameter will be everything found after the pipe (|) in the substitution tag and may be more than one character such as nh .

component_call(call => <string>)

Called by the Lexer when it encounters a component call tag without embedded content (<& ... &>).

The call parameter contains the entire contents of the tag.

component_content_call(call => <string>)

Called by the Lexer when it encounters a component call tag with embedded content (<&| ... &>).

component_content_call_end( )

Called by the Lexer when it encounters an end tag for a component call with content (</&>). Note that there is no corresponding component_call_end( ) method for component calls without content, because these calls don’t have end tags.

perl_line(line => <string>)

Called by the Lexer when it encounters a %-line.

Lexer

The Mason Lexer has a very limited API, because it is mostly subservient to (and hidden by) the Compiler. The Compiler calls the Lexer’s new( ) and lex( ) methods, then the Lexer calls various Compiler methods to generate the component. The Lexer has more methods than are listed here, but they’re internal methods and should not be considered part of its formal API. The default Lexer class is HTML::Mason::Lexer.

new(<parameters...>)

Creates a new Lexer object and returns it. In the current version of Mason, the new( ) method doesn’t accept any parameters.

lex(name => <string>, compiler => <compiler>, comp_source => string)

Begins the process of lexing a component. The name parameter specifies a unique name for this component. For a file-based component, this is its full path relative to the component root. The compiler parameter supplies the compiler object to use when processing this component. The comp_source parameter supplies the source to process.

The lex( ) method has no return value. If it encounters an error during processing, it will throw an exception.

line_number( )

Returns the Lexer’s current line number in the component being processed.

name( ),

Returns the name of the component currently being processed (i.e., the value of the name parameter passed to the lex( ) method).

throw_syntax_error(<error>)

Throws an HTML::Mason::Exception::Syntax error with the given error message as well as additional information about the component source.

Get Embedding Perl in HTML with Mason now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.