{
    "mode": "perldoc",
    "parameter": "HTML::Mason::Request",
    "section": "",
    "url": "https://www.chedong.com/phpMan.php/perldoc/HTML%3A%3AMason%3A%3ARequest/json",
    "generated": "2026-09-17T17:28:27Z",
    "synopsis": "$m->abort (...)\n$m->comp (...)\netc.",
    "sections": {
        "NAME": {
            "content": "HTML::Mason::Request - Mason Request Class\n",
            "subsections": []
        },
        "SYNOPSIS": {
            "content": "$m->abort (...)\n$m->comp (...)\netc.\n",
            "subsections": []
        },
        "DESCRIPTION": {
            "content": "The Request API is your gateway to all Mason features not provided by syntactic tags. Mason\ncreates a new Request object for every web request. Inside a component you access the current\nrequest object via the global $m. Outside of a component, you can use the class method\n\"instance\".\n",
            "subsections": []
        },
        "COMPONENT PATHS": {
            "content": "The methods Request->comp, Request->compexists, and Request->fetchcomp take a component path\nargument. Component paths are like URL paths, and always use a forward slash (/) as the\nseparator, regardless of what your operating system uses.\n\n*   If the path is absolute (starting with a '/'), then the component is found relative to the\ncomponent root.\n\n*   If the path is relative (no leading '/'), then the component is found relative to the\ncurrent component directory.\n\n*   If the path matches both a subcomponent and file-based component, the subcomponent takes\nprecedence.\n\nPARAMETERS TO THE new() CONSTRUCTOR\nautoflush\nTrue or false, default is false. Indicates whether to flush the output buffer\n(\"$m->flushbuffer\") after every string is output. Turn on autoflush if you need to send\npartial output to the client, for example in a progress meter.\n\nAs of Mason 1.3, autoflush will only work if enableautoflush has been set. Components can\nbe compiled more efficiently if they don't have to check for autoflush. Before using\nautoflush you might consider whether a few manual \"$m->flushbuffer\" calls would work nearly\nas well.\n\ndatacacheapi\nThe \"$m->cache\" API to use:\n\n*   '1.1', the default, indicates a \"Cache::Cache\" based API.\n\n*   'chi' indicates a \"CHI\" based API.\n\n*   '1.0' indicates the custom cache API used in Mason 1.0x and earlier. This compatibility\nlayer is provided as a convenience for users upgrading from older versions of Mason, but\nwill not be supported indefinitely.\n\ndatacachedefaults\nA hash reference of default options to use for the \"$m->cache\" command. For example, to use\nCache::Cache's \"MemoryCache\" implementation by default:\n\ndatacachedefaults => {cacheclass => 'MemoryCache'}\n\nTo use the CHI \"FastMmap\" driver by default:\n\ndatacacheapi      => 'CHI',\ndatacachedefaults => {driver => 'FastMmap'},\n\nThese settings are overridden by options given to particular \"$m->cache\" calls.\n\ndhandlername\nFile name used for dhandlers. Default is \"dhandler\". If this is set to an empty string (\"\")\nthen dhandlers are turned off entirely.\n\nerrorformat\nIndicates how errors are formatted. The built-in choices are\n\n*   *brief* - just the error message with no trace information\n\n*   *text* - a multi-line text format\n\n*   *line* - a single-line text format, with different pieces of information separated by\ntabs (useful for log files)\n\n*   *html* - a fancy html format\n\nThe default format under Apache and CGI is either *line* or *html* depending on whether the\nerror mode is *fatal* or *output*, respectively. The default for standalone mode is *text*.\n\nThe formats correspond to \"HTML::Mason::Exception\" methods named as*format*. You can define\nyour own format by creating an appropriately named method; for example, to define an \"xml\"\nformat, create a method \"HTML::Mason::Exception::asxml\" patterned after one of the built-in\nmethods.\n\nerrormode\nIndicates how errors are returned to the caller. The choices are *fatal*, meaning die with\nthe error, and *output*, meaning output the error just like regular output.\n\nThe default under Apache and CGI is *output*, causing the error to be displayed in the\nbrowser. The default for standalone mode is *fatal*.\n\ncomponenterrorhandler\nA code reference used to handle errors thrown during component compilation or runtime. By\ndefault, this is a subroutine that turns non-exception object errors in components into\nexceptions. If this parameter is set to a false value, these errors are simply rethrown\nas-is.\n\nTurning exceptions into objects can be expensive, since this will cause the generation of a\nstack trace for each error. If you are using strings or unblessed references as exceptions\nin your code, you may want to turn this off as a performance boost.\n\nmaxrecurse\nThe maximum recursion depth for the component stack, for the request stack, and for the\ninheritance stack. An error is signalled if the maximum is exceeded. Default is 32.\n\noutmethod\nIndicates where to send output. If outmethod is a reference to a scalar, output is appended\nto the scalar. If outmethod is a reference to a subroutine, the subroutine is called with\neach output string. For example, to send output to a file called \"mason.out\":\n\nmy $fh = new IO::File \">mason.out\";\n...\noutmethod => sub { $fh->print($[0]) }\n\nBy default, outmethod prints to standard output. Under Apache, standard output is\nredirected to \"$r->print\".\n\nplugins\nAn array of plugins that will be called at various stages of request processing. Please see\nHTML::Mason::Plugin for details.\n",
            "subsections": []
        },
        "ACCESSOR METHODS": {
            "content": "All of the above properties have standard accessor methods of the same name. In general, no\narguments retrieves the value, and one argument sets and returns the value. For example:\n\nmy $maxrecurselevel = $m->maxrecurse;\n$m->autoflush(1);\n",
            "subsections": []
        },
        "OTHER METHODS": {
            "content": "abort ([return value])\nEnds the current request, finishing the page without returning through components. The\noptional argument specifies the return value from \"Interp::exec\"; in a web environment, this\nultimately becomes the HTTP status code.\n\n\"abort\" is implemented by throwing an HTML::Mason::Exception::Abort object and can thus be\ncaught by eval(). The \"aborted\" method is a shortcut for determining whether a caught error\nwas generated by \"abort\".\n\nIf \"abort\" is called from a component that has a \"<%filter>\", than any output generated up\nto that point is filtered, *unless* \"abort\" is called from a \"<%shared>\" block.\n\nclearandabort ([return value])\nThis method is syntactic sugar for calling clearbuffer() and then abort(). If you are\naborting the request because of an error, you will often want to clear the buffer first so\nthat any output generated up to that point is not sent to the client.\n\naborted ([$err])\nReturns true or undef indicating whether the specified $err was generated by \"abort\". If no\n$err was passed, uses $@.\n\nIn this code, we catch and process fatal errors while letting \"abort\" exceptions pass\nthrough:\n\neval { codethatmayfailorabort() };\nif ($@) {\ndie $@ if $m->aborted;\n\n# handle fatal errors...\n\n$@ can lose its value quickly, so if you are planning to call $m->aborted more than a few\nlines after the eval, you should save $@ to a temporary variable.\n\nbasecomp\nReturns the current base component.\n\nHere are the rules that determine basecomp as you move from component to component.\n\n*   At the beginning of a request, the base component is initialized to the requested\ncomponent (\"$m->requestcomp()\").\n\n*   When you call a regular component via a path, the base component changes to the called\ncomponent.\n\n*   When you call a component method via a path (/foo/bar:baz), the base component changes\nto the method's owner.\n\n*   The base component does not change when:\n\n*   a component call is made to a component object\n\n*   a component call is made to SELF:x or PARENT:x or REQUEST:x\n\n*   a component call is made to a subcomponent (<%def>)\n\nThis may return nothing if the base component is not yet known, for example inside a\nplugin's startrequesthook() method, where we have created a request but it does not yet\nknow anything about the component being called.\n\ncache\n\"$m->cache\" returns a new cache object with a namespace specific to this component. The\nparameters to and return value from \"$m->cache\" differ depending on which datacacheapi you\nare using.\n\nIf datacacheapi = 1.1 (default)\n*cacheclass* specifies the class of cache object to create. It defaults to \"FileCache\"\nin most cases, or \"MemoryCache\" if the interpreter has no data directory, and must be a\nbackend subclass of \"Cache::Cache\". The prefix \"Cache::\" need not be included. See the\n\"Cache::Cache\" package for a full list of backend subclasses.\n\nBeyond that, *cacheoptions* may include any valid options to the new() method of the\ncache class. e.g. for \"FileCache\", valid options include \"defaultexpiresin\" and\n\"cachedepth\".\n\nSee HTML::Mason::Cache::BaseCache for information about the object returned from\n\"$m->cache\".\n\nIf datacacheapi = CHI\n*chirootclass* specifies the factory class that will be called to create cache\nobjects. The default is 'CHI'.\n\n*driver* specifies the driver to use, for example \"Memory\" or \"FastMmap\". The default is\n\"File\" in most cases, or \"Memory\" if the interpreter has no data directory.\n\nBeyond that, *cacheoptions* may include any valid options to the new() method of the\ndriver. e.g. for the \"File\" driver, valid options include \"expiresin\" and \"depth\".\n\ncacheself ([expiresin => '...'], [key => '...'], [getoptions], [cacheoptions])\n\"$m->cacheself\" caches the entire output and return result of a component.\n\n\"cacheself\" either returns undef, or a list containing the return value of the component\nfollowed by '1'. You should return immediately upon getting the latter result, as this\nindicates that you are inside the second invocation of the component.\n\n\"cacheself\" takes any of parameters to \"$m->cache\" (e.g. *cachedepth*), any of the\noptional parameters to \"$cache->get\" (*expireif*, *busylock*), and two additional options:\n\n*   *expirein* or *expiresin*: Indicates when the cache expires - it is passed as the\nthird argument to \"$cache->set\". e.g. '10 sec', '5 min', '2 hours'.\n\n*   *key*: An identifier used to uniquely identify the cache results - it is passed as the\nfirst argument to \"$cache->get\" and \"$cache->set\". The default key is\n'masoncacheself'.\n\nTo cache the component's output:\n\n<%init>\nreturn if $m->cacheself(expirein => '10 sec'[, key => 'fookey']);\n... <rest of init> ...\n</%init>\n\nTo cache the component's scalar return value:\n\n<%init>\nmy ($result, $cached) = $m->cacheself(expirein => '5 min'[, key => 'fookey']);\n\nreturn $result if $cached;\n... <rest of init> ...\n</%init>\n\nTo cache the component's list return value:\n\n<%init>\nmy (@retval) = $m->cacheself(expirein => '3 hours'[, key => 'fookey']);\n\nreturn @retval if pop @retval;\n... <rest of init> ...\n</%init>\n\nWe call \"pop\" on @retval to remove the mandatory '1' at the end of the list.\n\nIf a component has a \"<%filter>\" block, then the *filtered* output is cached.\n\nNote: users upgrading from 1.0x and earlier can continue to use the old \"$m->cacheself\" API\nby setting datacacheapi to '1.0'. This support will be removed at a later date.\n\nSee the the DATA CACHING section of the developer's manual section for more details on how\nto exercise finer control over caching.\n\ncallerargs\nReturns the arguments passed by the component at the specified stack level. Use a positive\nargument to count from the current component and a negative argument to count from the\ncomponent at the bottom of the stack. e.g.\n\n$m->callerargs(0)   # arguments passed to current component\n$m->callerargs(1)   # arguments passed to component that called us\n$m->callerargs(-1)  # arguments passed to first component executed\n\nWhen called in scalar context, a hash reference is returned. When called in list context, a\nlist of arguments (which may be assigned to a hash) is returned. Returns undef or an empty\nlist, depending on context, if the specified stack level does not exist.\n\ncallers\nWith no arguments, returns the current component stack as a list of component objects,\nstarting with the current component and ending with the top-level component. With one\nnumeric argument, returns the component object at that index in the list. Use a positive\nargument to count from the current component and a negative argument to count from the\ncomponent at the bottom of the stack. e.g.\n\nmy @comps = $m->callers   # all components\n$m->callers(0)            # current component\n$m->callers(1)            # component that called us\n$m->callers(-1)           # first component executed\n\nReturns undef or an empty list, depending on context, if the specified stack level does not\nexist.\n\ncaller\nA synonym for \"$m->callers(1)\", i.e. the component that called the currently executing\ncomponent.\n\ncallnext ([args...])\nCalls the next component in the content wrapping chain; usually called from an autohandler.\nWith no arguments, the original arguments are passed to the component. Any arguments\nspecified here serve to augment and override (in case of conflict) the original arguments.\nWorks like \"$m->comp\" in terms of return value and scalar/list context. See the autohandlers\nsection of the developer's manual for examples.\n\ncallself (output, return, error, tag)\nThis method allows a component to call itself so that it can filter both its output and\nreturn values. It is fairly advanced; for most purposes the \"<%filter>\" tag will be\nsufficient and simpler.\n\n\"$m->callself\" takes four arguments, all of them optional.\n\noutput - scalar reference that will be populated with the component output.\nreturn - scalar reference that will be populated with the component return value.\nerror - scalar reference that will be populated with the error thrown by the component, if\nany. If this parameter is not defined, then callself will not catch errors.\ntag - a name for this callself invocation; can almost always be omitted.\n\n\"$m->callself\" acts like a fork() in the sense that it will return twice with different\nvalues. When it returns 0, you allow control to pass through to the rest of your component.\nWhen it returns 1, that means the component has finished and you can examine the output,\nreturn value and error. (Don't worry, it doesn't really do a fork! See next section for\nexplanation.)\n\nThe following examples would generally appear at the top of a \"<%init>\" section. Here is a\nno-op \"$m->callself\" that leaves the output and return value untouched:\n\n<%init>\nmy ($output, $retval);\nif ($m->callself(\\$output, \\$retval)) {\n$m->print($output);\nreturn $retval;\n}\n...\n\nHere is a simple output filter that makes the output all uppercase. Note that we ignore both\nthe original and the final return value.\n\n<%init>\nmy ($output, $error);\nif ($m->callself(\\$output, undef)) {\n$m->print(uc $output);\nreturn;\n}\n...\n\nHere is a piece of code that traps all errors occurring anywhere in a component or its\nchildren, e.g. for the purpose of handling application-specific exceptions. This is\ndifficult to do with a manual \"eval\" because it would have to span multiple code sections\nand the main component body.\n\n<%init>\nmy ($output, undef, $error);\nif ($m->callself(\\$output, undef, \\$error)) {\nif ($error) {\n# check $error and do something with it\n}\n$m->print($output);\nreturn;\n}\n...\n\nclearbuffer\nClears the Mason output buffer. Any output sent before this line is discarded. Useful for\nhandling error conditions that can only be detected in the middle of a request.\n\nclearbuffer is, of course, thwarted by \"flushbuffer\".\n\ncomp (comp, args...)\nCalls the component designated by *comp* with the specified option/value pairs. *comp* may\nbe a component path or a component object.\n\nComponents work exactly like Perl subroutines in terms of return values and context. A\ncomponent can return any type of value, which is then returned from the \"$m->comp\" call.\n\nThe <& &> tag provides a convenient shortcut for \"$m->comp\".\n\nAs of 1.10, component calls can accept an initial hash reference of *modifiers*. The only\ncurrently supported modifier is \"store\", which stores the component's output in a scalar\nreference. For example:\n\nmy $buf;\nmy $return = $m->comp( { store => \\$buf }, '/some/comp', type => 'big' );\n\nThis mostly duplicates the behavior of *scomp*, but can be useful in rare cases where you\nneed to capture both a component's output and return value.\n\nThis modifier can be used with the <& &> tag as well, for example:\n\n<& { store => \\$buf }, '/some/comp', size => 'medium' &>\n\ncompexists (comppath)\nReturns 1 if *comppath* is the path of an existing component, 0 otherwise. *comppath* may\nbe any path accepted by comp or fetchcomp, including method or subcomponent paths.\n\nDepending on implementation, <compexists> may try to load the component referred to by the\npath, and may throw an error if the component contains a syntax error.\n\ncontent\nEvaluates the content (passed between <&| comp &> and </&> tags) of the current component,\nand returns the resulting text.\n\nReturns undef if there is no content.\n\nhascontent\nReturns true if the component was called with content (i.e. with <&| comp &> and </&> tags\ninstead of a single <& comp &> tag). This is generally better than checking the defined'ness\nof \"$m->content\" because it will not try to evaluate the content.\n\ncount\nReturns the number of this request, which is unique for a given request and interpreter.\n\ncurrentargs\nReturns the arguments passed to the current component. When called in scalar context, a hash\nreference is returned. When called in list context, a list of arguments (which may be\nassigned to a hash) is returned.\n\ncurrentcomp\nReturns the current component object.\n\ndecline\nUsed from a top-level component or dhandler, this method clears the output buffer, aborts\nthe current request and restarts with the next applicable dhandler up the tree. If no\ndhandler is available, a not-found error occurs.\n\nThis method bears no relation to the Apache DECLINED status except in name.\n\ndeclined ([$err])\nReturns true or undef indicating whether the specified $err was generated by \"decline\". If\nno $err was passed, uses $@.\n\ndepth\nReturns the current size of the component stack. The lowest possible value is 1, which\nindicates we are in the top-level component.\n\ndhandlerarg\nIf the request has been handled by a dhandler, this method returns the remainder of the URI\nor \"Interp::exec\" path when the dhandler directory is removed. Otherwise returns undef.\n\n\"dhandlerarg\" may be called from any component in the request, not just the dhandler.\n\nexec (comp, args...)\nStarts the request by executing the top-level component and arguments. This is normally\ncalled for you on the main request, but you can use it to execute subrequests.\n\nA request can only be executed once; e.g. it is an error to call this recursively on the\nsame request.\n\nfetchcomp (comppath)\nGiven a *comppath*, returns the corresponding component object or undef if no such\ncomponent exists.\n\nfetchnext\nReturns the next component in the content wrapping chain, or undef if there is no next\ncomponent. Usually called from an autohandler. See the autohandlers section of the\ndeveloper's manual for usage and examples.\n\nfetchnextall\nReturns a list of the remaining components in the content wrapping chain. Usually called\nfrom an autohandler. See the autohandlers section of the developer's manual for usage and\nexamples.\n\nfile (filename)\nReturns the contents of *filename* as a string. If *filename* is a relative path, Mason\nprepends the current component directory.\n\nflushbuffer\nFlushes the Mason output buffer. Under modperl, also sends HTTP headers if they haven't\nbeen sent and calls \"$r->rflush\" to flush the Apache buffer. Flushing the initial bytes of\noutput can make your servers appear more responsive.\n\nAttempts to flush the buffers are ignored within the context of a call to \"$m->scomp\" or\nwhen output is being stored in a scalar reference, as with the \" { store => \\$out } \"\ncomponent call modifier.\n\n\"<%filter>\" blocks will process the output whenever the buffers are flushed. If \"autoflush\"\nis on, your data may be filtered in small pieces.\n\ninstance\nThis class method returns the \"HTML::Mason::Request\" currently in use. If called when no\nMason request is active it will return \"undef\".\n\nIf called inside a subrequest, it returns the subrequest object.\n\ninterp\nReturns the Interp object associated with this request.\n\nmakesubrequest (comp => path, args => arrayref, other parameters)\nThis method creates a new Request object which inherits its parent's settable properties,\nsuch as autoflush and outmethod. These values may be overridden by passing parameters to\nthis method.\n\nThe \"comp\" parameter is required, while all other parameters are optional. It may be\nspecified as an absolute path or as a path relative to the current component.\n\nSee the subrequests section of the developer's manual for more information about\nsubrequests.\n\nlog Returns a \"Log::Any\" logger with a log category specific to the current component. The\ncategory for a component \"/foo/bar\" would be \"HTML::Mason::Component::foo::bar\".\n\nnotes (key, value)\nThe notes() method provides a place to store application data, giving developers a way to\nshare data among multiple components. Any data stored here persists for the duration of the\nrequest, i.e. the same lifetime as the Request object.\n\nConceptually, notes() contains a hash of key-value pairs. \"notes($key, $value)\" stores a new\nentry in this hash. notes($key) returns a previously stored value. notes() without any\narguments returns a reference to the entire hash of key-value pairs.\n\nnotes() is similar to the modperl method \"$r->pnotes()\". The main differences are that this\nnotes() can be used in a non-modperl environment, and that its lifetime is tied to the\n*Mason* request object, not the *Apache* request object. In particular, a Mason subrequest\nhas its own notes() structure, but would access the same \"$r->pnotes()\" structure.\n\nout (string)\nA synonym for \"$m->print\".\n\nprint (string)\nPrint the given *string*. Rarely needed, since normally all text is just placed in the\ncomponent body and output implicitly. \"$m->print\" is useful if you need to output something\nin the middle of a Perl block.\n\nIn 1.1 and on, \"print\" and \"$r->print\" are remapped to \"$m->print\", so they may be used\ninterchangeably. Before 1.1, one should only use \"$m->print\".\n\nrequestargs\nReturns the arguments originally passed to the top level component (see requestcomp for\ndefinition). When called in scalar context, a hash reference is returned. When called in\nlist context, a list of arguments (which may be assigned to a hash) is returned.\n\nrequestcomp\nReturns the component originally called in the request. Without autohandlers, this is the\nsame as the first component executed. With autohandlers, this is the component at the end of\nthe \"$m->callnext\" chain.\n\nrequestdepth\nReturns the current size of the request/subrequest stack. The lowest possible value is 1,\nwhich indicates we are in the top-level request. A value of 2 indicates we are inside a\nsubrequest of the top-level request, and so on.\n\nscomp (comp, args...)\nLike comp, but returns the component output as a string instead of printing it. (Think\nsprintf versus printf.) The component's return value is discarded.\n\nsubexec (comp, args...)\nThis method creates a new subrequest with the specified top-level component and arguments,\nand executes it. This is most often used to perform an \"internal redirect\" to a new\ncomponent such that autohandlers and dhandlers take effect.\n\ntime\nReturns the interpreter's notion of the current time (deprecated).\n",
            "subsections": []
        },
        "APACHE-ONLY METHODS": {
            "content": "These additional methods are available when running Mason with modperl and the ApacheHandler.\n\nah  Returns the ApacheHandler object associated with this request.\n\napachereq\nReturns the Apache request object. This is also available in the global $r.\n\nautosendheaders\nTrue or false, default is true. Indicates whether Mason should automatically send HTTP\nheaders before sending content back to the client. If you set to false, you should call\n\"$r->sendhttpheader\" manually.\n\nSee the sending HTTP headers section of the developer's manual for more details about the\nautomatic header feature.\n\nNOTE: This parameter has no effect under modperl-2, since calling \"$r->sendhttpheader\" is\nno longer needed.\n",
            "subsections": []
        },
        "CGI-ONLY METHODS": {
            "content": "This additional method is available when running Mason with the CGIHandler module.\n\ncgirequest\nReturns the Apache request emulation object, which is available as $r inside components.\n\nSee the CGIHandler docs for more details.\n",
            "subsections": []
        },
        "APACHE- OR CGI-ONLY METHODS": {
            "content": "This method is available when Mason is running under either the ApacheHandler or CGIHandler\nmodules.\n\ncgiobject\nReturns the CGI object used to parse any CGI parameters submitted to the component, assuming\nthat you have not changed the default value of the ApacheHandler argsmethod parameter. If\nyou are using the 'modperl' args method, then calling this method is a fatal error. See the\nApacheHandler and CGIHandler documentation for more details.\n\nredirect ($url, [$status])\nGiven a url, this generates a proper HTTP redirect for that URL. It uses\n\"$m->clearandabort\" to clear out any previous output, and abort the request. By default,\nthe status code used is 302, but this can be overridden by the user.\n\nSince this is implemented using \"$m->abort\", it will be trapped by an \" eval {} \" block. If\nyou are using an \" eval {} \" block in your code to trap errors, you need to make sure to\nrethrow these exceptions, like this:\n\neval {\n...\n};\n\ndie $@ if $m->aborted;\n\n# handle other exceptions\n",
            "subsections": []
        }
    },
    "summary": "HTML::Mason::Request - Mason Request Class",
    "flags": [],
    "examples": [],
    "see_also": []
}