Chapter 4: APIs
Mason is more than just a templating system. It provides a framework for translating requests into output.1 This framework has a number of class/object APIs worth knowing about. You certainly won't need to use most of these methods very often, but you will probably want to use at least some of them in many of your Mason-based projects. This chapter documents those APIs. For a more concise reference to these methods, see Appendix B.
Request Class and Object API
The request object in Mason represents the context of the current request process. For example, it knows where in the component wrapping chain it is, what arguments have been passed to various component calls, if you've been bad or good, and so on. It also allows you to change that context in various ways, such as by calling another component or aborting the request.
The request API provides access to some of the most frequently used Mason features, particularly those relating to component calls, autohandlers, and aborting in the middle of a request.
Recall, as first mentioned in Chapter 2, that the Mason request object is available in all components as $m
.
The
request class has only two class methods. The first, HTML::Mason::Request->new()
, is intended for use by other Mason objects and is not documented for
external use. If you want to make a new request object, use the make_subrequest()
method provided by the request object, which is covered as part of the
discussion of Mason's subrequest mechanism in Chapter 5.
The second class method, HTML::Mason::Request->instance()
, returns the current Mason request object. This is useful if you have code
outside of a Mason component that needs to access the request object. Inside components, you can just use $m
.
The request object's methods can be grouped together into several functional areas.
Constructor Parameters
parameters can be set when creating a new request object. You will most often set these by passing them to the ApacheHandler's constructor or by setting them in your httpd.conf file. You may occasionally want to set one of these parameters on the fly for the current request. Finally, you will create a new request object when you want to make a subrequest, and you may want to set these parameters then.
All of the following parameters are also available as get/set methods of the same name:
-
autoflush
This attribute is discussed in "Buffer-Related Methods", later in this chapter.
-
data_cache_defaults
This returns a hash reference containing default options for the Request object's
cache()
method. -
dhandler_name
This is the name used for dhandlers. This defaults to "dhandler."
-
error_format
This may be
brief
,text
,line
, orhtml
. These produce an error message with no trace, a multiline error with trace information, a single-line error with tab-separated fields (suitable for writing to a log), and a fancy HTML format.Each of these methods corresponds to a method in the
HTML::Mason::Exception
class, such asas_text()
oras_line()
. You can create your own method in theHTML::Mason::Exception
namespace, such asas_you_wish()
, in which case you could set this parameter to "you_wish." This method will receive a single argument, the exception object, and is expected to return a string containing the formatted error message.In a
mod_perl
or CGI environment, this defaults tohtml
format. Otherwise, the default istext
. -
error_mode
This may be either
fatal
oroutput
. In fatal mode, errors are thrown as exceptions. In output mode, the exception is converted to a text representation and sent to the same output stream as normal content.In a
mod_perl
or CGI environment, the default isoutput
, which means that errors go the client. In any other environment, the default isfatal
. If you set this tofatal
in a web environment, errors will end up in your web server's logs. If you wish to implement your own exception-handling mechanism around Mason, set this tofatal
and catch the exceptions yourself. -
max_recurse
This can be used to set the maximum stack size for component calls and subrequests. It defaults to 32, which is likely to be more than enough for any application. But if for some reason you need more, you can set this to a higher number.
-
out_method
This parameter indicates where output should be sent and must be a reference to either a scalar or a subroutine. If it is a scalar reference, output will be appended to this scalar. If it is a subroutine reference (often called a code reference in Perl parlance), this subroutine will be called with a list of arguments whenever output needs to be sent, which occurs after the output has passed through all of Mason's buffers.
The default
out_method
will print its arguments to STDOUT. In amod_perl
or CGI environment, this means that output gets sent to the client.
Calling Other Components
Besides the component call tag (<& &>
) discussed in Chapter 2, there are several other ways for one
component to call another:
-
comp(component, arguments)
This method is exactly like the
<&...&>
tag discussed in Chapter 2. It allows you to call another component, specified either by path or by supplying a component object as the first argument. Arguments are passed exactly as with the component call tag.The return value of this method is the return value of the component being called. Most components will not have an explicit return value and will return
undef
. Any output generated by the called component becomes part of the output of that particular request.As of Mason 1.10, a hash reference can be provided as an additional first argument to this method. The contents of this hash reference are used to modify the way the component call is processed. Right now, only one parameter --
store
-- is accepted for this hash reference.The value of the
store
key should be a reference to a scalar, into which Mason will place the output for the component. For example:$m->comp( { store => \$content }, 'Hello.comp', to => 'World' );
The output of Hello.comp would be available in the
$content
variable. This functionality is fundamentally the same as that provided by thescomp()
method except that it allows you to capture the component's return value in addition to its output. -
scomp(component, arguments)
This is exactly like the
comp()
method except that the called component's output is returned as a string instead of being sent to the output stream. This is analogous to the use ofsprintf()
instead ofprintf()
in C. Components called via this method go through all of the normal steps of component execution.If you have a component that generates output and has a return value and you want to capture that output in a scalar, you should use the
store
component call modifier. -
content
This method is relevant only inside a component called with content, a feature we saw briefly in Chapter 2 but will cover more completely in Chapter 5.
This method returns the block of content wrapped by the component call. This will make more sense once you've read "Calling Components with Content Blocks" in Chapter 5.
Aborting the Flow of Execution
Mason provides a way to abort the flow of execution during a request. Several request object methods relate to doing so and examining what happened afterward.
-
abort(optional argument)
Calling this method will immediately abort the execution of the current request.
If an argument is given to this method, this value will be available via the
aborted_value()
method after callingabort()
.Since this method is implemented internally via Perl's
die()
function, it may be caught by an eval block (eval {...}
). In this case, you may call theaborted()
method to distinguish this exception from one generated by something else in your code. The value of$@
will be an exception object of the classHTML::Mason::Exception::Abort
.In a web context, if you don't catch the abort call via an eval block, the return value will be used as the server status code. The following example takes advantage of that fact to deny access unless a user has authenticated himself to Apache:
<%init> use Apache::Constants; $m->abort(FORBIDDEN) unless $r->connection->user; </%init>
-
aborted
This method returns a boolean value indicating whether or not
abort()
has been called previously during the current request. -
aborted_value
When
aborted()
is true, this method returns whatever value was passed to theabort()
call.
If you are using eval blocks for exception handling in your components, it is
important to propagate exceptions generated from a call to abort()
. Here is one way do this:
eval { $m->call_next(%ARGS) }; if ($@) { if ($m->aborted) { # pass this up to a higher level die $@; } else { # something else that's bad happened $m->comp( 'exception_handler', exception => $@ ); } }
The Wrapping Chain
These are methods related to the wrapping chain, which was discussed in Chapter 3.
-
call_next(arguments)
When the currently executing component is part of a wrapping chain, this method will call the next component in the chain, passing it the current component's arguments and any arguments specified in the call to
call_next()
.If there is no next component to call, it will throw an exception.
-
fetch_next
This method returns the next component object in the wrapping chain. This is the same component that would be run upon calling
call_next()
. This object may then be passed to a component call via the<& &>
tag or thecomp()
method. -
fetch_next_all
This method returns an array of all of the components in the wrapping chain that have yet to be executed. They are returned in order based on their position in the wrapping chain.
Dhandler-Related Methods
Certain request object methods are specifically related to dhandlers:
-
decline
This method was discussed in detail in Chapter 3. Calling this method indicates that the current component does not wish to handle the request, in which case Mason will look for the next available dhandler to handle it.
-
dhandler_arg
This method was also discussed in Chapter 3. This method returns the remainder of the component path after stripping off the dhandler's directory. Given a call to /archives/2002/02/30/all and a dhandler component at /archives/dhandler,
dhandler_arg()
returns 2002/02/30/all.
Miscellaneous Methods
The request object also has some general-use methods:
-
file(filename)
Given a file path, Mason will look for this file and return its contents as a string.
If a relative path is given, Mason will prepend the path with the current component's directory if the component is file-based or the system's root directory otherwise.
-
comp_exists(component path)
Given a component path, this method returns true if this path would successfully resolve to a component when passed to
comp().
-
print(output)
This method takes a list of scalars, which will be sent as output. For example, the following two lines are identical:
% $m->print($output); <% $output %>
If you feel a need to call Perl's
print()
function from your Mason code, don't. Your code will be faster if you use$m->print()
instead, though the result will be the same in the end. -
interp
This returns the Interp object associated with the current request. Chapter 6 documents this object's API.
-
count
This method returns this request's number, which is unique for a given request and interpreter.
Introspection
The Mason request object provides numerous methods allowing introspection of the details of the current request. Some of these methods return one or more component objects, while others return information about the arguments passed to components.
These methods are useful if you are using autohandlers (particularly more than one) and you want to get some information about the components in a request.
Using some of these methods requires an understanding of autohandlers and the wrapping chain, a topic that was covered in Chapter 3.
-
base_comp
This method returns the base component for a request. Initially, the base component is the component that was called for a request. This may differ from the current component when you are in an autohandler.
The base component is the first component looked at when a component method is called in the form:
<& SELF:method &>
Methods are discussed in Chapter 5.
The base component is changed when you call another component during the context of that component's execution:
$m->comp( '/some/other/comp' );
In this case, the base component will now be the component /some/other/comp. This will be reset to the original base component after the call is finished.
If you pass a component object to a component call, Mason assumes that you know what you are doing and doesn't change the base component.
If your brain now feels like oatmeal after reading this, simply rest assured that the goal of all this is to make Mason just do the right thing and surprise you as little as possible.
But why would you use the
base_comp()
method, you ask? The primary reason for doing this is to get access to a component's attributes and methods.Let's say that I call a component called /people/faye_wong/bio.html and it is wrapped by both /people/faye_wong/autohandler and /people/autohandler. While in one of the autohandlers, I may wish to access the attributes of the component that was called.
The easiest way to do this is via the
base_comp()
method, like so:my $name = $m->base_comp->attr('name');
The
attr()
method starts looking for an attribute in the component on which it is called, then ascends the inheritance hierarchy from there. We want to start at the last component in the hierarchy -- the " child component" -- in order to give it a chance to override any attributes defined in its parents. -
request_args
This method returns the arguments passed to the originally requested component. In scalar context, it returns a hash reference. In list context, it returns a list.
-
callers(stack level)
This method is analogous to the Perl
caller()
function. It returns one or more component objects in the current component stack. When called without an argument, it simply returns the entire array of components in the stack up to, and including, the current component. The first element of the array will be the current component and the last will be the first component in the stack.If this method is called with an integer argument, then that number is used as an index number into the stack. Just as with Perl arrays, negative integers start at the end of the stack and count backward.
my @comps = $m->callers # all components $m->callers(0) # current component $m->callers(1) # component that called us $m->callers(-1) # first component executed
-
caller
This method is equivalent to
$m->callers(1)
. -
caller_args( stack level )
This method returns the arguments passed to the component on a given part of the stack. Unlike the
callers()
method, this method requires an integer argument to specify a stack index. When called in a list context, this method returns a list. In a scalar context, it returns a hash reference.If the arguments to the given component were not specified as key/value pairs (see "%ARGS Versus @_" in Chapter 2), you will need to assign the returned value to an array in order to avoid an error.
# arguments passed to current component my %args = $m->caller_args(0) # arguments passed to component that called us my $args_ref = $m->caller_args(1) # arguments passed to first component executed my @args = $m->caller_args(-1)
Using an index of -1 is equivalent to calling the
request_args()
method. -
request_comp
This method returns a component object representing the requested component. For example, if your wrapper chain looks like this:
/autohandler /tasks/autohandler /tasks/show_task.html
this method would return the component object representing /tasks/show_task.html.
Note that this is very similar to
base_comp()
. The difference between them is thatrequest_comp()
will always refer to /tasks/show_task.html for the entire duration of the request, whereasbase_comp()
may change when other components are called. -
current_comp
This method returns the component object that is currently being executed.
-
request_depth
This method tells you the depth of the current component, which is defined as the number of components in the component stack before the current component plus one. For the first component executed, this value is 1.
Buffer-Related Methods
The following methods all deal with Mason's
buffer objects. A typical request starts off with a single base buffer. For each component that is called in the component stack, another buffer will be added to the stack. In addition, filtering and other special Mason features will add and remove additional buffers.
The buffer objects have their own API, detailed later in this chapter, but you
will rarely need to use this unless you have a need to implement a subclass of
Mason's default buffer class, HTML::Mason::Buffer
.
The request API offers several methods for dealing with the buffer stack as a whole:
-
autoflush(boolean)
This method can be used to turn autoflushing on and off. When autoflushing is on, output is sent as soon as it is generated. Otherwise, it is buffered until all components have run.
By default, autoflushing is off.
Remember that if you turn autoflush on, the first piece of output generated by a component will end up being sent immediately. In a web context, this will prevent you from aborting execution later (to issue a redirect, for example).
Also, while autoflushing may give the impression of a snappier response because the first output arrives quicker, it is usually a bit slower overall than buffering all the output and sending it at once.
-
flush_buffer
This method flushes any output that the top buffer on the stack contains, sending it to the next buffer below it in the stack. Depending on what other buffers are below it, the flushing may continue through the entire stack, meaning output will be sent, or it may stop part of the way through because some buffers are set to ignore flushes.
If autoflush is on, this method is meaningless as no output is ever buffered.
Attempts to flush the buffers are ignored within the context of a call to
scomp()
or when output is being stored in a scalar reference, as with the{ store => \$out }
component call modifier for thecomp()
method.This method can be used to send output to the client more quickly in a web context:
Processing your request... % $m->flush_buffer; <% very_slow_function( ) %>
If you are running Mason under
mod_perl
, this method will also callrflush()
on the Apache object. -
clear_buffer
This method clears all buffered output in the buffer stack. This is useful if you generate some output and then need to discard it without outputting it. For obvious reasons, this method does nothing when autoflush is on.
Caching
One of the easiest ways to gain a quick performance boost for an application is to cache the results of operations that are slow, such as a complicated database query that cannot be optimized. Even when you can optimize some code, it might be simpler to just cache its result rather than optimize your code at the expense of increasing its complexity, thus making it less maintainable.
Caching can also be a big win in providing scalability when you have a bottleneck like an RDBMS. For example, if your web site traffic quadruples in one day, caching the results of some database queries can be the difference between serving pages and watching your database box grind to a bloody, overloaded death.
Because
caching is so useful, Mason has a simple caching system that you can use from
within your components. Mason's caching system is merely a thin wrapper
over DeWitt Clinton's excellent Cache::Cache
modules. These modules provide a number of caching backends such as file or shared memory caches with a simple, feature-rich API. All caches can be limited to a certain size using an LRU algorithm. In addition, it is possible to specify expiration times for stored data using a very flexible syntax.
For more information on Cache::Cache
, simply install it from
CPAN and type perldoc
Cache::Cache
on the command line. Also check out http://perl-cache.sourceforge.net/ for more information online.
-
cache(...)
This method returns the
Cache::Cache
object associated with this component, taking several options that allow you to control the parameters used to access the cache.Each component has its own cache, and it is not possible for a component to access another component's cache.
The most important parameter is
cache_class
. This can be either the full name of aCache::Cache
subclass, such asCache::FileCache
orCache::MemoryCache
, or you can simply leave off the initialCache::
part and use something likeFileCache
orMemoryCache
. The default isCache::FileCache
.All other parameters given to this option will simply be passed on to the
new()
method of the designatedCache::Cache
subclass. For example, if you are using theCache::FileCache
subclass, valid parameters would includenamespace
,default_expires_in
,auto_purge_interval
, andcache_root
. TheCache::Cache
andCache::FileCache
documentation contains more details on these and other parameters.Since Mason provides intelligent defaults for all of the needed parameters, it is possible to simply call the
cache()
method without any parameters at all. In this case, the return value will be a newCache::FileCache
object, which stores data under thedata_dir
specified by the Interp object. Each component will have an entirely unique cache object and storage, so two components can store data using the same keys without worrying about conflicts.Here is a typical cache example:
<%init> my $cache = $m->cache; my $data; unless ($data = $cache->get('complex_data')) { $data = complex_calculation( ); $cache->set('complex_data' => $data); } </%init>
If your data calculation depends on an incoming parameter, you can simply use that as your key (or part of the key):
<%args> $name </%args> <%init> my $cache = $m->cache; my $data; unless ($data = $cache->get("complex_data_$name")) { $data = complex_calculation($name); $cache->set("complex_data_$name" => $data); } </%init>
To set an expiration time for a piece of cached data, simply pass that as the third argument to
set()
:$m->cache->set("complex_data_$name" => $data, '3h'); # expires in 3 hours
To iterate through all the keys currently in your cache object, you can use the cache's
get_keys()
method.% foreach my $key ($m->cache->get_keys) { <% $key %> = <% $m->cache->get($key) %> % }
Mason reserves all keys beginning with
_ _mason
for its own internal use.The
Cache::Cache
API also includes methods that allow you to remove cached data, examine cache metadata such as when a piece of data was added or last accessed, and much more. See theCache::Cache
documentation for more details. -
cache_self(...)
This method is used when a component wants to cache its entire output and/or its return value. This is one of Mason's greatest features -- it allows you to design a site in a way that makes sense for you as a developer, then go back and sprinkle in a few
cache_self()
calls if performance is too slow.The
cache_self()
method takes all of the optional arguments that can be passed tocache()
, as well as two others, both of which are also optional:-
key
An optional key used to identify the cached data, as would be given to the cache object's
get()
andset()
methods. This identifies a unique set of cached data and allows you to store multiple versions of the component's output. -
expire_in
An expiration time as would be given to the
$cache->set()
method, such as5m
, meaning five minutes. The default is for cached data to last until the cache is intentionally wiped out.
The idiom for using this method looks like this:
<%init> return if $m->cache_self; ... # rest of init and output generation </%init>
The first time this component is called, its output will be generated normally and then stored in the cache. In the future, all calls to this component will use this cached output.
Of course, we may need to generate different output depending on what parameters are given as input. In this case, we do something like this:
<%args> $name </%args> <%init> return if $m->cache_self( key => $name ); ... # rest of init and output generation </%init>
For every different value of
$name
, the component will be rerun and its output will be cached.If your component has a return value that you would like to cache, the
cache_self()
idiom looks like this:<%init> my @retval = $m->cache_self; return @retval if pop @retval; </%init>
We need to
pop @retval
because Mason must append a true value to the end of the returned list, in order to ensure that the return value ofcache_self()
is always true when it is returning cached output. This is important because the cached return value could simply be an empty list,()
, which evaluates to false, in which case the caching would be useless because the return value ofcache_self()
would always be false, even when it was returning a cached value! Yes, it's a hack, but we think it's better than simply having this method not work for a return value that is an empty list. -
Subrequests
Subrequests are request objects that inherit all their settable properties from their parent. The main difference between calling a component with a subrequest versus using a regular component call is that subrequests will invoke the autohandler and dhandler mechanisms, whereas a regular component call will execute only the called component. Subrequests are covered in a more detail in Chapter 5.
-
make_subrequest(comp => component, args => [ ... ], ...)
This method creates a new subrequest object, which you can then execute via its
exec()
method. This gives you a chance to override the parent object's properties by passing in arguments to this method. -
subexec(comp, args)
This combines the
make_subrequest()
method and the subrequest'sexec()
method in one step. Any argument list given tosubexec()
will become the argument list for the called component. This doesn't give you a chance to set properties of the request, however. For that, you'll need to use the full two-step approach of callingmake_subrequest()
and thenexec()
on the returned object. -
is_subrequest
This method returns a boolean value indicating whether the given object is a subrequest.
-
parent_request
Calling this method returns the parent request object for a subrequest. If called on the top-level request object, it just returns
undef
.
Methods Available Only When Using ApacheHandler
When you are using Mason under mod_perl
with the HTML::Mason::ApacheHandler
class, which is covered in Chapter 7, the Request object will contain several additional methods.
-
ah
This method returns the current
HTML::Mason::ApacheHandler
object for this request. -
apache_req
This method returns the current Apache object for the request. This object is also available in all components as the variable
$r
.If you chose to use
Apache::Request
to handle incoming parameters by settingargs_method
tomod_perl
, this object will be anApache::Request
object; otherwise, it will be anApache
object.Incoming parameter handling is covered in Chapter 7.
Methods Available When Using ApacheHandler or CGIHandler
Two additional request methods are available when using the HTML::Mason::ApacheHandler
or HTML::Mason::CGIHandler
classes. The latter class is covered in Chapter 9.
-
cgi_object
This method is always available when using
HTML::Mason::CGIHandler
.If you are using
HTML::Mason::ApacheHandler
, this is available only if you chose to use theCGI.pm
module to handle incoming request parameters.This method will return the
CGI.pm
object that was used to handle incoming parameters. -
redirect(url)
Given a URL, this generates a proper HTTP redirect, which is then sent immediately to the client. This will not work if any output has been previously sent, which may be the case if
flush_buffer()
has been called or if the request is in autoflush mode.
Getting in Close with Buffers
Underneath the hood of the request object, output is handled via
buffer objects, which by default are of the HTML::Mason::Buffer
class.
The request object maintains a buffer stack. Output goes to the top buffer on the stack, which can then manipulate it and pass it on to the next buffer in the stack, which can in turn do the same, and so on.
Buffers are also used to implement features like the request's scomp()
method.
So why would you want to play with buffers? Chances are you won't want to simply add more
plain old HTML::Mason::Buffer
objects to the stack. That wouldn't achieve much.
But if you were to create a custom buffer subclass, you might want to selectively stick one onto the stack. For example, if you made a buffer that traced the source of all output it received, you might want to put it on the stack only for certain parts of your site during debugging. Just be sure to remove any buffers you add, or Mason may get confused and your output may never get sent.
The other buffer-related methods are potentially useful for introspection and debugging:
-
top_buffer
Returns the current top-level buffer object for the request. This is the buffer to which output is currently being sent.
-
buffer_stack
Returns all the buffers on the stack, starting from the top buffer and ending with the bottom buffer, which is the one at the bottom of the stack.
-
push_buffer_stack(Buffer object)
Pushes a new buffer onto the top of the stack. Mason pushes new buffers onto the stack when calling new components.
-
pop_buffer_stack
Pops the top buffer off the stack and returns it. Mason pops a buffer each time a component finishes executing.
Component Object API
Objects that you will deal with in this class actually fall into three
categories. The majority will be objects of the HTML::Mason::Component::FileBased
class, which is used for components generated from component source files. The
next most common will be HTML::Mason::Component::Subcomponent
objects, which represent subcomponents and methods. Finally, anonymous
components created via the HTML::Mason::Interp->make_component()
method (covered in Chapter 5 and Chapter 6) will simply be of the HTML::Mason::Component
class.
For the most part, these objects all share the same interface.
Component objects are returned from a number of Request object methods as well
as the interpreter object's make_component()
method.
These first methods are the ones you most likely want to use:
-
attr(name)
Looks for the specified attribute in the component and its parents, returning the first value found. If the attribute is not found, this method throws an exception. Attributes are declared in
<%attr>
blocks, as covered in "<%flags> and <%attr> blocks" in Chapter 2. -
attr_if_exists(name)
Works just like the
attr()
method except that it simply returnsundef
if the specified attribute does not exist.Of course, this makes it impossible to distinguish between an attribute with
undef
as its value and an attribute that is not found. To make that distinction, use theattr()
method and wrap it in aneval {}
block, or use this method in conjunction with theattr_exists()
method. -
attr_exists(name)
Returns true if the specified attribute exists in the component or its parents.
-
call_method(name, arguments)
Calls the specified method with the given arguments. If the method is not present in the component or any of its parents, an exception is thrown.
-
scall_method(name, arguments)
This is analogous to the
scomp()
method for the Request object. This method calls the named method with the given arguments and returns the output as a string. If the method is not present in the component or any of its parents, an exception is thrown. -
method_exists(name)
Returns true if the specified method exists in the component or its parents.
Much of the component API is interesting only for introspection, though we're sure creative developers can think of ways to work strange magic with this API.
-
comp_id
Returns a unique ID for this component. This ID may be in the form of a component path, though this is not guaranteed.
-
load_time
Returns the Unix epoch time when this object was created.
-
declared_args
Returns a hash reference containing an entry for each argument declared in the component's
<%args>
section. These keys include the variable prefix, so they are strings like$foo
or%bar
. Each key's value is itself a hash reference, which contains a single key,default
, the value of which is the string given as the argument's default value, orundef
if no default was given.For example, the following
<%args>
section:<%args> $foo @bar => (1, 2, 3) %baz => ( ) # an empty hash $undefined => undef </%args>
would cause the following to be returned from the
declared_args()
method:{ '$foo' => { default => undef }, '@bar' => { default => ' (1, 2, 3)' }, '%baz' => { default => ' ( ) # an empty hash' }, '$undefined' => { default => ' undef' } }
Note the difference between an argument with no default value and an argument with a default value of
undef
. Also, as you can see, the default value for each argument is returned as a string, not a data structure. This is because Mason does not actually parse these values as Perl does, but rather simply drops them into the code it generates in one piece. -
dir_path
Returns the component's notion of the current directory, relative to the component root. For file-based components, this is the full component path minus the filename. For subcomponents and methods, this will be the same as its parent component. For anonymous components, this will be
undef
.This path is like a URL path and always uses forward slashes (/) as separators.
To get the filesystem path and filename for file-based components, see the
source_dir()
andsource_file()
methods. -
flag(name)
Returns the value of the specified flag. Flags are declared in
<%flags>
blocks, as covered in "<%flags> and <%attr> blocks" in Chapter 2. -
is_subcomp
Returns true if the specified component is a subcomponent or a method.
-
is_file_based
Returns true if the given component is file-based.
-
name
Returns the name of the component. For file-based components, this is the component filename without any path information. For subcomponents and methods, it is the name given in the
<%def>
or<%method>
tag. For anonymous components, this method returns the same value ascomp_id()
. -
owner
For subcomponents and methods, returns the component in which the component was defined.
-
parent
Returns the parent component object, if one exists. The way a parent component is determined was discussed in Chapter 3.
-
path
Returns the component path for file-based components. This path starts from the component root, not the filesystem root. In other words, this is an absolute path that could be used to call this component from another component. For a subcomponent object, this returns a string containing its parent object's path and its own name, separated by a c olon (:).
As with
dir_path(),
the path returned here is a URL-style path and uses the forward slash (/) as its separator. -
subcomps
With no arguments, returns a hash reference containing all the subcomponents defined in the component. The keys of this hash reference are component names, while the values are the component objects themselves.
If an argument is given, it returns the subcomponent of that particular name, or
undef
if there is no such subcomponent. -
methods
Operates exactly like the
subcomps()
method but for methods instead of subcomponents. -
title
Returns a printable string identifying this component. It is intended to uniquely identify a component within a given interpreter although this is not 100% guaranteed.
For file-based components, this is the component's path. If you have multiple component roots, this path will also be supplemented by a string indicating which component root the component was found in.
For subcomponents, this is its owner's title plus its own name, as returned by the
name()
method.
For anonymous components, this is the same as
comp_id()
.
Methods for File-based Components
A few additional methods are available only for file-based components.
-
source_file
Returns the full absolute path to the file that contains the original component source. This is given in the native dialect of the filesystem, so its directory separators will be
/
on Unix, : on Mac OS, and who knows what on VMS. -
source_dir
Returns the full path to the source component's directory on the filesystem. As with
source_file()
, the path is given in the native dialect of the filesystem. -
object_file
Returns the object filename for the component if the component is file-based, otherwise
undef
.The object file is the file that contains the code Mason generates from the component's source file.
Buffers
Playing with buffers is not for the everyday user but may be useful to you during debugging. Buffer objects have only a few methods:
-
output
For buffers that store output in a scalar, this method returns the output they have stored so far. If the buffer is a filtering buffer, the output will be filtered before it is returned.
-
flush
This forces the buffer to pass its output on to its parents, if it has any. Buffers can be set to ignore flushes, in which case this method does nothing.
-
receive(output, ...)
This method is used to pass output to the buffer. It takes an array of scalars, each of which is considered a piece of output.
-
clear
This method clears any stored output that the buffer may contain.
Footnotes
1. You may or may not choose to call this an application server. -- Return.
These HTML pages were created by running this script against the pseudo-POD source.