{
    "content": [
        {
            "type": "text",
            "text": "# CGI::Application (perldoc)\n\n## NAME\n\nCGI::Application - Framework for building reusable web-applications\n\n## SYNOPSIS\n\n# In \"WebApp.pm\"...\npackage WebApp;\nuse base 'CGI::Application';\n# ( setup() can even be skipped for common cases. See docs below. )\nsub setup {\nmy $self = shift;\n$self->startmode('mode1');\n$self->modeparam('rm');\n$self->runmodes(\n'mode1' => 'dostuff',\n'mode2' => 'domorestuff',\n'mode3' => 'dosomethingelse'\n);\n}\nsub dostuff { ... }\nsub domorestuff { ... }\nsub dosomethingelse { ... }\n1;\n### In \"webapp.cgi\"...\nuse WebApp;\nmy $webapp = WebApp->new();\n$webapp->run();\n### Or, in a PSGI file, webapp.psgi\nuse WebApp;\nWebApp->psgiapp();\n\n## DESCRIPTION\n\nIt is intended that your Application Module will be implemented as a sub-class of\nCGI::Application. This is done simply as follows:\n\n## Sections\n\n- **NAME**\n- **SYNOPSIS**\n- **INTRODUCTION**\n- **USAGE EXAMPLE**\n- **ABSTRACT**\n- **DESCRIPTION** (14 subsections)\n- **PLUG-INS** (4 subsections)\n- **COMMUNITY**\n- **SEE ALSO**\n- **MORE READING**\n- **AUTHOR**\n- **CREDITS**\n- **LICENSE**\n\nUse structuredContent.sections for detailed options, examples, and full documentation.\n"
        }
    ],
    "structuredContent": {
        "command": "CGI::Application",
        "section": "",
        "mode": "perldoc",
        "summary": "CGI::Application - Framework for building reusable web-applications",
        "synopsis": "# In \"WebApp.pm\"...\npackage WebApp;\nuse base 'CGI::Application';\n# ( setup() can even be skipped for common cases. See docs below. )\nsub setup {\nmy $self = shift;\n$self->startmode('mode1');\n$self->modeparam('rm');\n$self->runmodes(\n'mode1' => 'dostuff',\n'mode2' => 'domorestuff',\n'mode3' => 'dosomethingelse'\n);\n}\nsub dostuff { ... }\nsub domorestuff { ... }\nsub dosomethingelse { ... }\n1;\n### In \"webapp.cgi\"...\nuse WebApp;\nmy $webapp = WebApp->new();\n$webapp->run();\n### Or, in a PSGI file, webapp.psgi\nuse WebApp;\nWebApp->psgiapp();",
        "tldr_summary": null,
        "tldr_examples": [],
        "tldr_source": null,
        "flags": [],
        "examples": [],
        "see_also": [],
        "section_outline": [
            {
                "name": "NAME",
                "lines": 2,
                "subsections": []
            },
            {
                "name": "SYNOPSIS",
                "lines": 30,
                "subsections": []
            },
            {
                "name": "INTRODUCTION",
                "lines": 16,
                "subsections": []
            },
            {
                "name": "USAGE EXAMPLE",
                "lines": 139,
                "subsections": []
            },
            {
                "name": "ABSTRACT",
                "lines": 23,
                "subsections": []
            },
            {
                "name": "DESCRIPTION",
                "lines": 17,
                "subsections": [
                    {
                        "name": "Instance Script Methods",
                        "lines": 59
                    },
                    {
                        "name": "start_mode",
                        "lines": 58
                    },
                    {
                        "name": "Additional PSGI Return Values",
                        "lines": 27
                    },
                    {
                        "name": "Methods to possibly override",
                        "lines": 45
                    },
                    {
                        "name": "teardown",
                        "lines": 131
                    },
                    {
                        "name": "Essential Application Methods",
                        "lines": 20
                    },
                    {
                        "name": "load_tmpl",
                        "lines": 8
                    },
                    {
                        "name": "path",
                        "lines": 265
                    },
                    {
                        "name": "More Application Methods",
                        "lines": 50
                    },
                    {
                        "name": "setup",
                        "lines": 186
                    },
                    {
                        "name": "mode_param",
                        "lines": 8
                    },
                    {
                        "name": "Dispatching Clean URIs to run modes",
                        "lines": 12
                    },
                    {
                        "name": "Offline website development",
                        "lines": 4
                    },
                    {
                        "name": "Automated Testing",
                        "lines": 14
                    }
                ]
            },
            {
                "name": "PLUG-INS",
                "lines": 3,
                "subsections": [
                    {
                        "name": "Recommended Plug-ins",
                        "lines": 21
                    },
                    {
                        "name": "More plug-ins",
                        "lines": 31
                    },
                    {
                        "name": "Writing Plug-ins",
                        "lines": 12
                    },
                    {
                        "name": "Writing Advanced Plug-ins - Using callbacks",
                        "lines": 160
                    }
                ]
            },
            {
                "name": "COMMUNITY",
                "lines": 22,
                "subsections": []
            },
            {
                "name": "SEE ALSO",
                "lines": 7,
                "subsections": []
            },
            {
                "name": "MORE READING",
                "lines": 12,
                "subsections": []
            },
            {
                "name": "AUTHOR",
                "lines": 6,
                "subsections": []
            },
            {
                "name": "CREDITS",
                "lines": 17,
                "subsections": []
            },
            {
                "name": "LICENSE",
                "lines": 24,
                "subsections": []
            }
        ],
        "sections": {
            "NAME": {
                "content": "CGI::Application - Framework for building reusable web-applications\n",
                "subsections": []
            },
            "SYNOPSIS": {
                "content": "# In \"WebApp.pm\"...\npackage WebApp;\nuse base 'CGI::Application';\n\n# ( setup() can even be skipped for common cases. See docs below. )\nsub setup {\nmy $self = shift;\n$self->startmode('mode1');\n$self->modeparam('rm');\n$self->runmodes(\n'mode1' => 'dostuff',\n'mode2' => 'domorestuff',\n'mode3' => 'dosomethingelse'\n);\n}\nsub dostuff { ... }\nsub domorestuff { ... }\nsub dosomethingelse { ... }\n1;\n\n\n### In \"webapp.cgi\"...\nuse WebApp;\nmy $webapp = WebApp->new();\n$webapp->run();\n\n### Or, in a PSGI file, webapp.psgi\nuse WebApp;\nWebApp->psgiapp();\n",
                "subsections": []
            },
            "INTRODUCTION": {
                "content": "CGI::Application makes it easier to create sophisticated, high-performance, reusable web-based\napplications. CGI::Application helps makes your web applications easier to design, write, and\nevolve.\n\nCGI::Application judiciously avoids employing technologies and techniques which would bind a\ndeveloper to any one set of tools, operating system or web server.\n\nIt is lightweight in terms of memory usage, making it suitable for common CGI environments, and\na high performance choice in persistent environments like FastCGI or modperl.\n\nBy adding PLUG-INS as your needs grow, you can add advanced and complex features when you need\nthem.\n\nFirst released in 2000 and used and expanded by a number of professional website developers,\nCGI::Application is a stable, reliable choice.\n",
                "subsections": []
            },
            "USAGE EXAMPLE": {
                "content": "Imagine you have to write an application to search through a database of widgets. Your\napplication has three screens:\n\n1. Search form\n2. List of results\n3. Detail of a single record\n\nTo write this application using CGI::Application you will create two files:\n\n1. WidgetView.pm -- Your \"Application Module\"\n2. widgetview.cgi -- Your \"Instance Script\"\n\nThe Application Module contains all the code specific to your application functionality, and it\nexists outside of your web server's document root, somewhere in the Perl library search path.\n\nThe Instance Script is what is actually called by your web server. It is a very small, simple\nfile which simply creates an instance of your application and calls an inherited method, run().\nFollowing is the entirety of \"widgetview.cgi\":\n\n#!/usr/bin/perl -w\nuse WidgetView;\nmy $webapp = WidgetView->new();\n$webapp->run();\n\nAs you can see, widgetview.cgi simply \"uses\" your Application module (which implements a Perl\npackage called \"WidgetView\"). Your Application Module, \"WidgetView.pm\", is somewhat more\nlengthy:\n\npackage WidgetView;\nuse base 'CGI::Application';\nuse strict;\n\n# Needed for our database connection\nuse CGI::Application::Plugin::DBH;\n\nsub setup {\nmy $self = shift;\n$self->startmode('mode1');\n$self->runmodes(\n'mode1' => 'showform',\n'mode2' => 'showlist',\n'mode3' => 'showdetail'\n);\n\n# Connect to DBI database, with the same args as DBI->connect();\n$self->dbhconfig();\n}\n\nsub teardown {\nmy $self = shift;\n\n# Disconnect when we're done, (Although DBI usually does this automatically)\n$self->dbh->disconnect();\n}\n\nsub showform {\nmy $self = shift;\n\n# Get CGI query object\nmy $q = $self->query();\n\nmy $output = '';\n$output .= $q->starthtml(-title => 'Widget Search Form');\n$output .= $q->startform();\n$output .= $q->textfield(-name => 'widgetcode');\n$output .= $q->hidden(-name => 'rm', -value => 'mode2');\n$output .= $q->submit();\n$output .= $q->endform();\n$output .= $q->endhtml();\n\nreturn $output;\n}\n\nsub showlist {\nmy $self = shift;\n\n# Get our database connection\nmy $dbh = $self->dbh();\n\n# Get CGI query object\nmy $q = $self->query();\nmy $widgetcode = $q->param(\"widgetcode\");\n\nmy $output = '';\n$output .= $q->starthtml(-title => 'List of Matching Widgets');\n\n## Do a bunch of stuff to select \"widgets\" from a DBI-connected\n## database which match the user-supplied value of \"widgetcode\"\n## which has been supplied from the previous HTML form via a\n## CGI.pm query object.\n##\n## Each row will contain a link to a \"Widget Detail\" which\n## provides an anchor tag, as follows:\n##\n##   \"widgetview.cgi?rm=mode3&widgetid=XXX\"\n##\n##  ...Where \"XXX\" is a unique value referencing the ID of\n## the particular \"widget\" upon which the user has clicked.\n\n$output .= $q->endhtml();\n\nreturn $output;\n}\n\nsub showdetail {\nmy $self = shift;\n\n# Get our database connection\nmy $dbh = $self->dbh();\n\n# Get CGI query object\nmy $q = $self->query();\nmy $widgetid = $q->param(\"widgetid\");\n\nmy $output = '';\n$output .= $q->starthtml(-title => 'Widget Detail');\n\n## Do a bunch of things to select all the properties of\n## the particular \"widget\" upon which the user has\n## clicked.  The key id value of this widget is provided\n## via the \"widgetid\" property, accessed via the CGI.pm\n## query object.\n\n$output .= $q->endhtml();\n\nreturn $output;\n}\n\n1;  # Perl requires this at the end of all modules\n\nCGI::Application takes care of implementing the new() and the run() methods. Notice that at no\npoint do you call print() to send any output to STDOUT. Instead, all output is returned as a\nscalar.\n\nCGI::Application's most significant contribution is in managing the application state. Notice\nthat all which is needed to push the application forward is to set the value of a HTML form\nparameter 'rm' to the value of the \"run mode\" you wish to handle the form submission. This is\nthe key to CGI::Application.\n",
                "subsections": []
            },
            "ABSTRACT": {
                "content": "The guiding philosophy behind CGI::Application is that a web-based application can be organized\ninto a specific set of \"Run Modes.\" Each Run Mode is roughly analogous to a single screen (a\nform, some output, etc.). All the Run Modes are managed by a single \"Application Module\" which\nis a Perl module. In your web server's document space there is an \"Instance Script\" which is\ncalled by the web server as a CGI (or an Apache::Registry script if you're using Apache +\nmodperl).\n\nThis methodology is an inversion of the \"Embedded\" philosophy (ASP, JSP, EmbPerl, Mason, etc.)\nin which there are \"pages\" for each state of the application, and the page drives functionality.\nIn CGI::Application, form follows function -- the Application Module drives pages, and the code\nfor a single application is in one place; not spread out over multiple \"pages\". If you feel that\nEmbedded architectures are confusing, unorganized, difficult to design and difficult to manage,\nCGI::Application is the methodology for you!\n\nApache is NOT a requirement for CGI::Application. Web applications based on CGI::Application\nwill run equally well on NT/IIS or any other CGI-compatible environment. CGI::Application-based\nprojects are, however, ripe for use on Apache/modperl servers, as they naturally encourage Good\nProgramming Practices and will often work in persistent environments without modification.\n\nFor more information on using CGI::Application with modperl, please see our website at\nhttp://www.cgi-app.org/, as well as CGI::Application::Plugin::Apache, which integrates with\nApache::Request.\n",
                "subsections": []
            },
            "DESCRIPTION": {
                "content": "It is intended that your Application Module will be implemented as a sub-class of\nCGI::Application. This is done simply as follows:\n\npackage My::App;\nuse base 'CGI::Application';\n\nNotation and Conventions\n\nFor the purpose of this document, we will refer to the following conventions:\n\nWebApp.pm   The Perl module which implements your Application Module class.\nWebApp      Your Application Module class; a sub-class of CGI::Application.\nwebapp.cgi  The Instance Script which implements your Application Module.\n$webapp     An instance (object) of your Application Module class.\n$c          Same as $webapp, used in instance methods to pass around the\ncurrent object. (Sometimes referred as \"$self\" in other code)\n",
                "subsections": [
                    {
                        "name": "Instance Script Methods",
                        "content": "By inheriting from CGI::Application you have access to a number of built-in methods. The\nfollowing are those which are expected to be called from your Instance Script.\n\nnew()\nThe new() method is the constructor for a CGI::Application. It returns a blessed reference to\nyour Application Module package (class). Optionally, new() may take a set of parameters as key\n=> value pairs:\n\nmy $webapp = WebApp->new(\nTMPLPATH => 'App/',\nPARAMS => {\n'customthing1' => 'some val',\n'anothercustomthing' => [qw/123 456/]\n}\n);\n\nThis method may take some specific parameters:\n\nTMPLPATH - This optional parameter defines a path to a directory of templates. This is used by\nthe loadtmpl() method (specified below), and may also be used for the same purpose by other\ntemplate plugins. This run-time parameter allows you to further encapsulate instantiating\ntemplates, providing potential for more re-usability. It can be either a scalar or an array\nreference of multiple paths.\n\nQUERY - This optional parameter allows you to specify an already-created CGI.pm query object.\nUnder normal use, CGI::Application will instantiate its own CGI.pm query object. Under certain\nconditions, it might be useful to be able to use one which has already been created.\n\nPARAMS - This parameter, if used, allows you to set a number of custom parameters at run-time.\nBy passing in different values in different instance scripts which use the same application\nmodule you can achieve a higher level of re-usability. For instance, imagine an application\nmodule, \"Mailform.pm\". The application takes the contents of a HTML form and emails it to a\nspecified recipient. You could have multiple instance scripts throughout your site which all use\nthis \"Mailform.pm\" module, but which set different recipients or different forms.\n\nOne common use of instance scripts is to provide a path to a config file. This design allows you\nto define project wide configuration objects used by many several instance scripts. There are\nseveral plugins which simplify the syntax for this and provide lazy loading. Here's an example\nusing CGI::Application::Plugin::ConfigAuto, which uses Config::Auto to support many\nconfiguration file formats.\n\nmy $app = WebApp->new(PARAMS => { cfgfile => 'config.pl' });\n\n# Later in your app:\nmy %cfg = $self->cfg()\n# or ... $self->cfg('HTMLROOTDIR');\n\nSee the list of plugins below for more config file integration solutions.\n\nrun()\nThe run() method is called upon your Application Module object, from your Instance Script. When\ncalled, it executes the functionality in your Application Module.\n\nmy $webapp = WebApp->new();\n$webapp->run();\n\nThis method first determines the application state by looking at the value of the CGI parameter\nspecified by modeparam() (defaults to 'rm' for \"Run Mode\"), which is expected to contain the\nname of the mode of operation. If not specified, the state defaults to the value of"
                    },
                    {
                        "name": "start_mode",
                        "content": "Once the mode has been determined, run() looks at the dispatch table stored in runmodes() and\nfinds the function pointer which is keyed from the mode name. If found, the function is called\nand the data returned is print()'ed to STDOUT and to the browser. If the specified mode is not\nfound in the runmodes() table, run() will croak().\n\nPSGI support\nCGI::Application offers native PSGI support. The default query object for this is CGI::PSGI,\nwhich simply wrappers CGI.pm to provide PSGI support to it.\n\npsgiapp()\n$psgicoderef = WebApp->psgiapp({ ... args to new() ... });\n\nThe simplest way to create and return a PSGI-compatible coderef. Pass in arguments to a hashref\njust as would to new. This returns a PSGI-compatible coderef, using CGI:::PSGI as the query\nobject. To use a different query object, construct your own object using \"runaspsgi()\", as\nshown below.\n\nIt's possible that we'll change from CGI::PSGI to a different-but-compatible query object for\nPSGI support in the future, perhaps if CGI.pm adds native PSGI support.\n\nrunaspsgi()\nmy $psgiaref = $webapp->runaspsgi;\n\nJust like \"run\", but prints no output and returns the data structure required by the PSGI\nspecification. Use this if you want to run the application on top of a PSGI-compatible handler,\nsuch as Plack provides.\n\nIf you are just getting started, just use \"run()\". It's easy to switch to using \"runaspsgi\"\nlater.\n\nWhy use \"runaspsgi()\"? There are already solutions to run CGI::Application-based projects on\nseveral web servers with dozens of plugins. Running as a PSGI-compatible application provides\nthe ability to run on additional PSGI-compatible servers, as well as providing access to all of\nthe \"Middleware\" solutions available through the Plack project.\n\nThe structure returned is an arrayref, containing the status code, an arrayref of header\nkey/values and an arrayref containing the body.\n\n[ 200, [ 'Content-Type' => 'text/html' ], [ $body ] ]\n\nBy default the body is a single scalar, but plugins may modify this to return other value PSGI\nvalues. See \"The Response\" in PSGI for details about the response format.\n\nNote that calling \"runaspsgi\" only handles the *output* portion of the PSGI spec. to handle\nthe input, you need to use a CGI.pm-like query object that is PSGI-compliant, such as CGI::PSGI.\nThis query object must provide psgiheader and psgiredirect methods.\n\nThe final result might look like this:\n\nuse WebApp;\nuse CGI::PSGI;\n\nmy $handler = sub {\nmy $env = shift;\nmy $webapp = WebApp->new({ QUERY => CGI::PSGI->new($env) });\n$webapp->runaspsgi;\n};\n"
                    },
                    {
                        "name": "Additional PSGI Return Values",
                        "content": "The PSGI Specification allows for returning a file handle or a subroutine reference instead of\nbyte strings. In PSGI mode this is supported directly by CGI::Application. Have your run mode\nreturn a file handle or compatible subref as follows:\n\nsub returningafilehandle {\nmy $self = shift;\n\n$self->headerprops(-type => 'text/plain');\n\nopen my $fh, \"<\", 'testfile.txt' or die \"OOPS! $!\";\n\nreturn $fh;\n}\n\nsub returningasubref {\nmy $self = shift;\n\n$self->headerprops(-type => 'text/plain');\nreturn sub {\nmy $writer = shift;\nforeach my $i (1..10) {\n#sleep 1;\n$writer->write(\"check $i: \" . time . \"\\n\");\n}\n};\n}\n"
                    },
                    {
                        "name": "Methods to possibly override",
                        "content": "CGI::Application implements some methods which are expected to be overridden by implementing\nthem in your sub-class module. These methods are as follows:\n\nsetup()\nThis method is called by the inherited new() constructor method. The setup() method should be\nused to define the following property/methods:\n\nmodeparam() - set the name of the run mode CGI param.\nstartmode() - text scalar containing the default run mode.\nerrormode() - text scalar containing the error mode.\nrunmodes() - hash table containing mode => function mappings.\ntmplpath() - text scalar or array reference containing path(s) to template files.\n\nYour setup() method may call any of the instance methods of your application. This function is a\ngood place to define properties specific to your application via the $webapp->param() method.\n\nYour setup() method might be implemented something like this:\n\nsub setup {\nmy $self = shift;\n$self->tmplpath('/path/to/my/templates/');\n$self->startmode('putform');\n$self->errormode('myerrorrm');\n$self->runmodes({\n'putform'  => 'myputformfunc',\n'postdata' => 'mydatafunc'\n});\n$self->param('myprop1');\n$self->param('myprop2', 'prop2value');\n$self->param('myprop3', ['p3v1', 'p3v2', 'p3v3']);\n}\n\nHowever, often times all that needs to be in setup() is defining your run modes and your start\nmode. CGI::Application::Plugin::AutoRunmode allows you to do this with a simple syntax, using\nrun mode attributes:\n\nuse CGI::Application::Plugin::AutoRunmode;\n\nsub showfirst : StartRunmode { ... };\nsub donext : Runmode { ... }\n\nteardown()\nIf implemented, this method is called automatically after your application runs. It can be used\nto clean up after your operations. A typical use of the teardown() function is to disconnect a\ndatabase connection which was established in the setup() function. You could also use the"
                    },
                    {
                        "name": "teardown",
                        "content": "cgiappinit()\nIf implemented, this method is called automatically right before the setup() method is called.\nThis method provides an optional initialization hook, which improves the object-oriented\ncharacteristics of CGI::Application. The cgiappinit() method receives, as its parameters, all\nthe arguments which were sent to the new() method.\n\nAn example of the benefits provided by utilizing this hook is creating a custom \"application\nsuper-class\" from which all your web applications would inherit, instead of CGI::Application.\n\nConsider the following:\n\n# In MySuperclass.pm:\npackage MySuperclass;\nuse base 'CGI::Application';\nsub cgiappinit {\nmy $self = shift;\n# Perform some project-specific init behavior\n# such as to load settings from a database or file.\n}\n\n\n# In MyApplication.pm:\npackage MyApplication;\nuse base 'MySuperclass';\nsub setup { ... }\nsub teardown { ... }\n# The rest of your CGI::Application-based follows...\n\nBy using CGI::Application and the cgiappinit() method as illustrated, a suite of applications\ncould be designed to share certain characteristics. This has the potential for much cleaner code\nbuilt on object-oriented inheritance.\n\ncgiappprerun()\nIf implemented, this method is called automatically right before the selected run mode method is\ncalled. This method provides an optional pre-runmode hook, which permits functionality to be\nadded at the point right before the run mode method is called. To further leverage this hook,\nthe value of the run mode is passed into cgiappprerun().\n\nAnother benefit provided by utilizing this hook is creating a custom \"application super-class\"\nfrom which all your web applications would inherit, instead of CGI::Application.\n\nConsider the following:\n\n# In MySuperclass.pm:\npackage MySuperclass;\nuse base 'CGI::Application';\nsub cgiappprerun {\nmy $self = shift;\n# Perform some project-specific init behavior\n# such as to implement run mode specific\n# authorization functions.\n}\n\n\n# In MyApplication.pm:\npackage MyApplication;\nuse base 'MySuperclass';\nsub setup { ... }\nsub teardown { ... }\n# The rest of your CGI::Application-based follows...\n\nBy using CGI::Application and the cgiappprerun() method as illustrated, a suite of applications\ncould be designed to share certain characteristics. This has the potential for much cleaner code\nbuilt on object-oriented inheritance.\n\nIt is also possible, within your cgiappprerun() method, to change the run mode of your\napplication. This can be done via the prerunmode() method, which is discussed elsewhere in this\nPOD.\n\ncgiapppostrun()\nIf implemented, this hook will be called after the run mode method has returned its output, but\nbefore HTTP headers are generated. This will give you an opportunity to modify the body and\nheaders before they are returned to the web browser.\n\nA typical use for this hook is pipelining the output of a CGI-Application through a series of\n\"filter\" processors. For example:\n\n* You want to enclose the output of all your CGI-Applications in\nan HTML table in a larger page.\n\n* Your run modes return structured data (such as XML), which you\nwant to transform using a standard mechanism (such as XSLT).\n\n* You want to post-process CGI-App output through another system,\nsuch as HTML::Mason.\n\n* You want to modify HTTP headers in a particular way across all\nrun modes, based on particular criteria.\n\nThe cgiapppostrun() hook receives a reference to the output from your run mode method, in\naddition to the CGI-App object. A typical cgiapppostrun() method might be implemented as\nfollows:\n\nsub cgiapppostrun {\nmy $self = shift;\nmy $outputref = shift;\n\n# Enclose output HTML table\nmy $newoutput = \"<table border=1>\";\n$newoutput .= \"<tr><td> Hello, World! </td></tr>\";\n$newoutput .= \"<tr><td>\". $$outputref .\"</td></tr>\";\n$newoutput .= \"</table>\";\n\n# Replace old output with new output\n$$outputref = $newoutput;\n}\n\nObviously, with access to the CGI-App object you have full access to use all the methods\nnormally available in a run mode. You could, for example, use \"loadtmpl()\" to replace the\nstatic HTML in this example with HTML::Template. You could change the HTTP headers (via\n\"headertype()\" and \"headerprops()\" methods) to set up a redirect. You could also use the\nobjects properties to apply changes only under certain circumstance, such as a in only certain\nrun modes, and when a \"param()\" is a particular value.\n\ncgiappgetquery()\nmy $q = $webapp->cgiappgetquery;\n\nOverride this method to retrieve the query object if you wish to use a different query interface\ninstead of CGI.pm.\n\nCGI.pm is only loaded if it is used on a given request.\n\nIf you can use an alternative to CGI.pm, it needs to have some compatibility with the CGI.pm\nAPI. For normal use, just having a compatible \"param\" method should be sufficient.\n\nIf you use the \"pathinfo\" option to the modeparam() method, then we will call the\n\"pathinfo()\" method on the query object.\n\nIf you use the \"Dump\" method in CGI::Application, we will call the \"Dump\" and \"escapeHTML\"\nmethods on the query object.\n"
                    },
                    {
                        "name": "Essential Application Methods",
                        "content": "The following methods are inherited from CGI::Application, and are available to be called by\nyour application within your Application Module. They are called essential because you will use\nall are most of them to get any application up and running. These functions are listed in\nalphabetical order.\n\nloadtmpl()\nmy $tmplobj = $webapp->loadtmpl;\nmy $tmplobj = $webapp->loadtmpl('some.html');\nmy $tmplobj = $webapp->loadtmpl( \\$templatecontent );\nmy $tmplobj = $webapp->loadtmpl( FILEHANDLE );\n\nThis method takes the name of a template file, a reference to template data or a FILEHANDLE and\nreturns an HTML::Template object. If the filename is undefined or missing, CGI::Application will\ndefault to trying to use the current run mode name, plus the extension \".html\".\n\nIf you use the default template naming system, you should also use\nCGI::Application::Plugin::Forward, which simply helps to keep the current name accurate when you\npass control from one run mode to another.\n\n( For integration with other template systems and automated template names, see \"Alternatives to"
                    },
                    {
                        "name": "load_tmpl",
                        "content": "When you pass in a filename, the HTML::Template->newfile() constructor is used for create the\nobject. When you pass in a reference to the template content, the\nHTML::Template->newscalarref() constructor is used and when you pass in a filehandle, the\nHTML::Template->newfilehandle() constructor is used.\n\nRefer to HTML::Template for specific usage of HTML::Template.\n\nIf tmplpath() has been specified, loadtmpl() will set the HTML::Template \"path\" option to the"
                    },
                    {
                        "name": "path",
                        "content": "The loadtmpl() method will pass any extra parameters sent to it directly to\nHTML::Template->newfile() (or newscalarref() or newfilehandle()). This will allow the\nHTML::Template object to be further customized:\n\nmy $tmplobj = $webapp->loadtmpl('someother.html',\ndieonbadparams => 0,\ncache => 1\n);\n\nNote that if you want to pass extra arguments but use the default template name, you still need\nto provide a name of \"undef\":\n\nmy $tmplobj = $webapp->loadtmpl(undef,\ndieonbadparams => 0,\ncache => 1\n);\n\nAlternatives to loadtmpl()\n\nIf your application requires more specialized behavior than this, you can always replace it by\noverriding loadtmpl() by implementing your own loadtmpl() in your CGI::Application sub-class\napplication module.\n\nFirst, you may want to check out the template related plugins.\n\nCGI::Application::Plugin::TT focuses just on Template Toolkit integration, and features\npre-and-post features, singleton support and more.\n\nCGI::Application::Plugin::Stream can help if you want to return a stream and not a file. It\nfeatures a simple syntax and MIME-type detection.\n\nspecifying the template class with htmltmplclass()\n\nYou may specify an API-compatible alternative to HTML::Template by setting a new\n\"htmltmplclass()\":\n\n$self->htmltmplclass('HTML::Template::Dumper');\n\nThe default is \"HTML::Template\". The alternate class should provide at least the following parts\nof the HTML::Template API:\n\n$t = $class->new( scalarref => ... );  # If you use scalarref templates\n$t = $class->new( filehandle => ... ); # If you use filehandle templates\n$t = $class->new( filename => ... );\n$t->param(...);\n\nHere's an example case allowing you to precisely test what's sent to your templates:\n\n$ENV{CGIAPPRETURNONLY} = 1;\nmy $webapp = WebApp->new;\n$webapp->htmltmplclass('HTML::Template::Dumper');\nmy $outstr = $webapp->run;\nmy $tmplhref = eval \"$outstr\";\n\n# Now Precisely test what would be set to the template\nis ($tmplhref->{petname}, 'Daisy', \"Daisy is sent template\");\n\nThis is a powerful technique because HTML::Template::Dumper loads and considers the template\nfile that would actually be used. If the 'petname' token was missing in the template, the above\ntest would fail. So, you are testing both your code and your templates in a much more precise\nway than using simple regular expressions to see if the string \"Daisy\" appeared somewhere on the\npage.\n\nThe loadtmpl() callback\n\nPlugin authors will be interested to know that you can register a callback that will be executed\njust before loadtmpl() returns:\n\n$self->addcallback('loadtmpl',\\&yourmethod);\n\nWhen \"yourmethod()\" is executed, it will be passed three arguments:\n\n1. A hash reference of the extra params passed into C<loadtmpl>\n2. Followed by a hash reference to template parameters.\nWith both of these, you can modify them by reference to affect\nvalues that are actually passed to the new() and param() methods of the\ntemplate object.\n3. The name of the template file.\n\nHere's an example stub for a loadtmpl() callback:\n\nsub myloadtmplcallback {\nmy ($c, $htparams, $tmplparams, $tmplfile) = @\n# modify $htparams or $tmplparams by reference...\n}\n\nparam()\n$webapp->param('pname', $somevalue);\n\nThe param() method provides a facility through which you may set application instance properties\nwhich are accessible throughout your application.\n\nThe param() method may be used in two basic ways. First, you may use it to get or set the value\nof a parameter:\n\n$webapp->param('scalarparam', '123');\nmy $scalarparamvalues = $webapp->param('someparam');\n\nSecond, when called in the context of an array, with no parameter name specified, param()\nreturns an array containing all the parameters which currently exist:\n\nmy @allparams = $webapp->param();\n\nThe param() method also allows you to set a bunch of parameters at once by passing in a hash (or\nhashref):\n\n$webapp->param(\n'key1' => 'val1',\n'key2' => 'val2',\n'key3' => 'val3',\n);\n\nThe param() method enables a very valuable system for customizing your applications on a\nper-instance basis. One Application Module might be instantiated by different Instance Scripts.\nEach Instance Script might set different values for a set of parameters. This allows similar\napplications to share a common code-base, but behave differently. For example, imagine a mail\nform application with a single Application Module, but multiple Instance Scripts. Each Instance\nScript might specify a different recipient. Another example would be a web bulletin boards\nsystem. There could be multiple boards, each with a different topic and set of administrators.\n\nThe new() method provides a shortcut for specifying a number of run-time parameters at once.\nInternally, CGI::Application calls the param() method to set these properties. The param()\nmethod is a powerful tool for greatly increasing your application's re-usability.\n\nquery()\nmy $q = $webapp->query();\nmy $remoteuser = $q->remoteuser();\n\nThis method retrieves the CGI.pm query object which has been created by instantiating your\nApplication Module. For details on usage of this query object, refer to CGI. CGI::Application is\nbuilt on the CGI module. Generally speaking, you will want to become very familiar with CGI.pm,\nas you will use the query object whenever you want to interact with form data.\n\nWhen the new() method is called, a CGI query object is automatically created. If, for some\nreason, you want to use your own CGI query object, the new() method supports passing in your\nexisting query object on construction using the QUERY attribute.\n\nThere are a few rare situations where you want your own query object to be used after your\nApplication Module has already been constructed. In that case you can pass it to c<query()> like\nthis:\n\n$webapp->query($newqueryobject);\nmy $q = $webapp->query(); # now uses $newqueryobject\n\nrunmodes()\n# The common usage: an arrayref of run mode names that exactly match subroutine names\n$webapp->runmodes([qw/\nformdisplay\nformprocess\n/]);\n\n# With a hashref, use a different name or a code ref\n$webapp->runmodes(\n'mode1' => 'somesubbyname',\n'mode2' => \\&someothersubbyref\n);\n\nThis accessor/mutator specifies the dispatch table for the application states, using the syntax\nexamples above. It returns the dispatch table as a hash.\n\nThe runmodes() method may be called more than once. Additional values passed into runmodes()\nwill be added to the run modes table. In the case that an existing run mode is re-defined, the\nnew value will override the existing value. This behavior might be useful for applications which\nare created via inheritance from another application, or some advanced application which\nmodifies its own capabilities based on user input.\n\nThe run() method uses the data in this table to send the application to the correct function as\ndetermined by reading the CGI parameter specified by modeparam() (defaults to 'rm' for \"Run\nMode\"). These functions are referred to as \"run mode methods\".\n\nThe hash table set by this method is expected to contain the mode name as a key. The value\nshould be either a hard reference (a subref) to the run mode method which you want to be called\nwhen the application enters the specified run mode, or the name of the run mode method to be\ncalled:\n\n'modenamebyref'  => \\&modefunction\n'modenamebyname' => 'modefunction'\n\nThe run mode method specified is expected to return a block of text (e.g.: HTML) which will\neventually be sent back to the web browser. The run mode method may return its block of text as\na scalar or a scalar-ref.\n\nAn advantage of specifying your run mode methods by name instead of by reference is that you can\nmore easily create derivative applications using inheritance. For instance, if you have a new\napplication which is exactly the same as an existing application with the exception of one run\nmode, you could simply inherit from that other application and override the run mode method\nwhich is different. If you specified your run mode method by reference, your child class would\nstill use the function from the parent class.\n\nAn advantage of specifying your run mode methods by reference instead of by name is performance.\nDereferencing a subref is faster than eval()-ing a code block. If run-time performance is a\ncritical issue, specify your run mode methods by reference and not by name. The speed\ndifferences are generally small, however, so specifying by name is preferred.\n\nSpecifying the run modes by array reference:\n\n$webapp->runmodes([ 'mode1', 'mode2', 'mode3' ]);\n\nThis is the same as using a hash, with keys equal to values\n\n$webapp->runmodes(\n'mode1' => 'mode1',\n'mode2' => 'mode2',\n'mode3' => 'mode3'\n);\n\nOften, it makes good organizational sense to have your run modes map to methods of the same\nname. The array-ref interface provides a shortcut to that behavior while reducing verbosity of\nyour code.\n\nNote that another importance of specifying your run modes in either a hash or array-ref is to\nassure that only those Perl methods which are specifically designated may be called via your\napplication. Application environments which don't specify allowed methods and disallow all\nothers are insecure, potentially opening the door to allowing execution of arbitrary code.\nCGI::Application maintains a strict \"default-deny\" stance on all method invocation, thereby\nallowing secure applications to be built upon it.\n\nIMPORTANT NOTE ABOUT RUN MODE METHODS\n\nYour application should *NEVER* print() to STDOUT. Using print() to send output to STDOUT\n(including HTTP headers) is exclusively the domain of the inherited run() method. Breaking this\nrule is a common source of errors. If your program is erroneously sending content before your\nHTTP header, you are probably breaking this rule.\n\nTHE RUN MODE OF LAST RESORT: \"AUTOLOAD\"\n\nIf CGI::Application is asked to go to a run mode which doesn't exist it will usually croak()\nwith errors. If this is not your desired behavior, it is possible to catch this exception by\nimplementing a run mode with the reserved name \"AUTOLOAD\":\n\n$self->runmodes(\n\"AUTOLOAD\" => \\&catchmyexception\n);\n\nBefore CGI::Application calls croak() it will check for the existence of a run mode called\n\"AUTOLOAD\". If specified, this run mode will in invoked just like a regular run mode, with one\nexception: It will receive, as an argument, the name of the run mode which invoked it:\n\nsub catchmyexception {\nmy $self = shift;\nmy $intendedrunmode = shift;\n\nmy $output = \"Looking for '$intendedrunmode', but found 'AUTOLOAD' instead\";\nreturn $output;\n}\n\nThis functionality could be used for a simple human-readable error screen, or for more\nsophisticated application behaviors.\n\nstartmode()\n$webapp->startmode('mode1');\n\nThe startmode contains the name of the mode as specified in the runmodes() table. Default mode\nis \"start\". The mode key specified here will be used whenever the value of the CGI form\nparameter specified by modeparam() is not defined. Generally, this is the first time your\napplication is executed.\n\ntmplpath()\n$webapp->tmplpath('/path/to/some/templates/');\n\nThis access/mutator method sets the file path to the directory (or directories) where the\ntemplates are stored. It is used by loadtmpl() to find the template files, using\nHTML::Template's \"path\" option. To set the path you can either pass in a text scalar or an array\nreference of multiple paths.\n"
                    },
                    {
                        "name": "More Application Methods",
                        "content": "You can skip this section if you are just getting started.\n\nThe following additional methods are inherited from CGI::Application, and are available to be\ncalled by your application within your Application Module. These functions are listed in\nalphabetical order.\n\ndelete()\n$webapp->delete('myparam');\n\nThe delete() method is used to delete a parameter that was previously stored inside of your\napplication either by using the PARAMS hash that was passed in your call to new() or by a call\nto the param() method. This is similar to the delete() method of CGI.pm. It is useful if your\napplication makes decisions based on the existence of certain params that may have been removed\nin previous sections of your app or simply to clean-up your param()s.\n\ndump()\nprint STDERR $webapp->dump();\n\nThe dump() method is a debugging function which will return a chunk of text which contains all\nthe environment and web form data of the request, formatted nicely for human readability. Useful\nfor outputting to STDERR.\n\ndumphtml()\nmy $output = $webapp->dumphtml();\n\nThe dumphtml() method is a debugging function which will return a chunk of text which contains\nall the environment and web form data of the request, formatted nicely for human readability via\na web browser. Useful for outputting to a browser. Please consider the security implications of\nusing this in production code.\n\nerrormode()\n$webapp->errormode('myerrorrm');\n\nIf the runmode dies for whatever reason, \"run() will\" see if you have set a value for\n\"errormode()\". If you have, \"run()\" will call that method as a run mode, passing $@ as the only\nparameter.\n\nPlugins authors will be interested to know that just before \"errormode()\" is called, the\n\"error\" hook will be executed, with the error message passed in as the only parameter.\n\nNo \"errormode\" is defined by default. The death of your \"errormode()\" run mode is not trapped,\nso you can also use it to die in your own special way.\n\nFor a complete integrated logging solution, check out CGI::Application::Plugin::LogDispatch.\n\ngetcurrentrunmode()\n$webapp->getcurrentrunmode();\n\nThe \"getcurrentrunmode()\" method will return a text scalar containing the name of the run mode\nwhich is currently being executed. If the run mode has not yet been determined, such as during"
                    },
                    {
                        "name": "setup",
                        "content": "headeradd()\n# add or replace the 'type' header\n$webapp->headeradd( -type => 'image/png' );\n\n- or -\n\n# add an additional cookie\n$webapp->headeradd(-cookie=>[$extracookie]);\n\nThe \"headeradd()\" method is used to add one or more headers to the outgoing response headers.\nThe parameters will eventually be passed on to the CGI.pm header() method, so refer to the CGI\ndocs for exact usage details.\n\nUnlike calling \"headerprops()\", \"headeradd()\" will preserve any existing headers. If a scalar\nvalue is passed to \"headeradd()\" it will replace the existing value for that key.\n\nIf an array reference is passed as a value to \"headeradd()\", values in that array ref will be\nappended to any existing values for that key. This is primarily useful for setting an additional\ncookie after one has already been set.\n\nheaderprops()\n# Set a complete set of headers\n%setheaders = $webapp->headerprops(-type=>'image/gif',-expires=>'+3d');\n\n# clobber / reset all headers\n%setheaders = $webapp->headerprops({});\n\n# Just retrieve the headers\n%setheaders = $webapp->headerprops();\n\nThe \"headerprops()\" method expects a hash of CGI.pm-compatible HTTP header properties. These\nproperties will be passed directly to the \"header()\" or \"redirect()\" methods of the query()\nobject. Refer to the docs of your query object for details. (Be default, it's CGI.pm).\n\nCalling headerprops with an empty hashref clobber any existing headers that have previously\nset.\n\n\"headerprops()\" returns a hash of all the headers that have currently been set. It can be\ncalled with no arguments just to get the hash current headers back.\n\nTo add additional headers later without clobbering the old ones, see \"headeradd()\".\n\nIMPORTANT NOTE REGARDING HTTP HEADERS\n\nIt is through the \"headerprops()\" and \"headeradd()\" method that you may modify the outgoing\nHTTP headers. This is necessary when you want to set a cookie, set the mime type to something\nother than \"text/html\", or perform a redirect. The headerprops() method works in conjunction\nwith the headertype() method. The value contained in headertype() determines if we use\nCGI::header() or CGI::redirect(). The content of headerprops() is passed as an argument to\nwhichever CGI.pm function is called.\n\nUnderstanding this relationship is important if you wish to manipulate the HTTP header properly.\n\nheadertype()\n$webapp->headertype('redirect');\n$webapp->headertype('none');\n\nThis method used to declare that you are setting a redirection header, or that you want no\nheader to be returned by the framework.\n\nThe value of 'header' is almost never used, as it is the default.\n\nExample of redirecting:\n\nsub someredirectmode {\nmy $self = shift;\n# do stuff here....\n$self->headertype('redirect');\n$self->headerprops(-url=>  \"http://site/path/doc.html\" );\n}\n\nTo simplify that further, use CGI::Application::Plugin::Redirect:\n\nreturn $self->redirect('http://www.example.com/');\n\nSetting the header to 'none' may be useful if you are streaming content. In other contexts, it\nmay be more useful to set \"$ENV{CGIAPPRETURNONLY} = 1;\", which suppresses all printing,\nincluding headers, and returns the output instead.\n\nThat's commonly used for testing, or when using CGI::Application as a controller for a cron\nscript!\n\nmodeparam()\n# Name the CGI form parameter that contains the run mode name.\n# This is the default behavior, and is often sufficient.\n$webapp->modeparam('rm');\n\n# Set the run mode name directly from a code ref\n$webapp->modeparam(\\&somemethod);\n\n# Alternate interface, which allows you to set the run\n# mode name directly from $ENV{PATHINFO}.\n$webapp->modeparam(\npathinfo=> 1,\nparam =>'rm'\n);\n\nThis accessor/mutator method is generally called in the setup() method. It is used to help\ndetermine the run mode to call. There are three options for calling it.\n\n$webapp->modeparam('rm');\n\nHere, a CGI form parameter is named that will contain the name of the run mode to use. This is\nthe default behavior, with 'rm' being the parameter named used.\n\n$webapp->modeparam(\\&somemethod);\n\nHere a code reference is provided. It will return the name of the run mode to use directly.\nExample:\n\nsub somemethod {\nmy $self = shift;\nreturn 'runmodex';\n}\n\nThis would allow you to programmatically set the run mode based on arbitrary logic.\n\n$webapp->modeparam(\npathinfo=> 1,\nparam =>'rm'\n);\n\nThis syntax allows you to easily set the run mode from $ENV{PATHINFO}. It will try to set the\nrun mode from the first part of $ENV{PATHINFO} (before the first \"/\"). To specify that you\nwould rather get the run mode name from the 2nd part of $ENV{PATHINFO}:\n\n$webapp->modeparam( pathinfo=> 2 );\n\nThis also demonstrates that you don't need to pass in the \"param\" hash key. It will still\ndefault to \"rm\".\n\nYou can also set \"pathinfo\" to a negative value. This works just like a negative list index: if\nit is -1 the run mode name will be taken from the last part of $ENV{PATHINFO}, if it is -2, the\none before that, and so on.\n\nIf no run mode is found in $ENV{PATHINFO}, it will fall back to looking in the value of a the\nCGI form field defined with 'param', as described above. This allows you to use the convenient\n$ENV{PATHINFO} trick most of the time, but also supports the edge cases, such as when you don't\nknow what the run mode will be ahead of time and want to define it with JavaScript.\n\nMore about $ENV{PATHINFO}.\n\nUsing $ENV{PATHINFO} to name your run mode creates a clean separation between the form\nvariables you submit and how you determine the processing run mode. It also creates URLs that\nare more search engine friendly. Let's look at an example form submission using this syntax:\n\n<form action=\"/cgi-bin/instance.cgi/editform\" method=post>\n<input type=\"hidden\" name=\"breedid\" value=\"4\">\n\nHere the run mode would be set to \"editform\". Here's another example with a query string:\n\n/cgi-bin/instance.cgi/editform?breedid=2\n\nThis demonstrates that you can use $ENV{PATHINFO} and a query string together without problems.\n$ENV{PATHINFO} is defined as part of the CGI specification should be supported by any web\nserver that supports CGI scripts.\n\nprerunmode()\n$webapp->prerunmode('newrunmode');\n\nThe prerunmode() method is an accessor/mutator which can be used within your cgiappprerun()\nmethod to change the run mode which is about to be executed. For example, consider:\n\n# In WebApp.pm:\npackage WebApp;\nuse base 'CGI::Application';\nsub cgiappprerun {\nmy $self = shift;\n\n# Get the web user name, if any\nmy $q = $self->query();\nmy $user = $q->remoteuser();\n\n# Redirect to login, if necessary\nunless ($user) {\n$self->prerunmode('login');\n}\n}\n\nIn this example, the web user will be forced into the \"login\" run mode unless they have already\nlogged in. The prerunmode() method permits a scalar text string to be set which overrides\nwhatever the run mode would otherwise be.\n\nThe use of prerunmode() within cgiappprerun() differs from setting modeparam() to use a\ncall-back via subroutine reference. It differs because cgiappprerun() allows you to selectively\nset the run mode based on some logic in your cgiappprerun() method. The call-back facility of"
                    },
                    {
                        "name": "mode_param",
                        "content": "mode with your own method. The prerunmode() method should be used in cases where you want to\nuse CGI::Application's normal run mode switching facility, but you want to make selective\nchanges to the mode under specific conditions.\n\nNote: The prerunmode() method may ONLY be called in the context of a cgiappprerun() method.\nYour application will die() if you call prerunmode() elsewhere, such as in setup() or a run\nmode method.\n"
                    },
                    {
                        "name": "Dispatching Clean URIs to run modes",
                        "content": "Modern web frameworks dispense with cruft in URIs, providing in clean URIs instead. Instead of:\n\n/cgi-bin/item.cgi?rm=view&id=15\n\nA clean URI to describe the same resource might be:\n\n/item/15/view\n\nThe process of mapping these URIs to run modes is called dispatching and is handled by\nCGI::Application::Dispatch. Dispatching is not required and is a layer you can fairly easily add\nto an application later.\n"
                    },
                    {
                        "name": "Offline website development",
                        "content": "You can work on your CGI::Application project on your desktop or laptop without installing a\nfull-featured web-server like Apache. Instead, install CGI::Application::Server from CPAN. After\na few minutes of setup, you'll have your own private application server up and running.\n"
                    },
                    {
                        "name": "Automated Testing",
                        "content": "Test::WWW::Mechanize::CGIApp allows functional testing of a CGI::App-based project without\nstarting a web server. Test::WWW::Mechanize could be used to test the app through a real web\nserver.\n\nDirect testing is also easy. CGI::Application will normally print the output of it's run modes\ndirectly to STDOUT. This can be suppressed with an environment variable, CGIAPPRETURNONLY.\nFor example:\n\n$ENV{CGIAPPRETURNONLY} = 1;\n$output = $webapp->run();\nlike($output, qr/good/, \"output is good\");\n\nExamples of this style can be seen in our own test suite.\n"
                    }
                ]
            },
            "PLUG-INS": {
                "content": "CGI::Application has a plug-in architecture that is easy to use and easy to develop new plug-ins\nfor.\n",
                "subsections": [
                    {
                        "name": "Recommended Plug-ins",
                        "content": "The following plugins are recommended for general purpose web/db development:\n\n*   CGI::Application::Plugin::Redirect - is a simple plugin to provide a shorter syntax for\nexecuting a redirect.\n\n*   CGI::Application::Plugin::ConfigAuto - Keeping your config details in a separate file is\nrecommended for every project. This one integrates with Config::Auto. Several more config\nplugin options are listed below.\n\n*   CGI::Application::Plugin::DBH - Provides easy management of one or more database handles and\ncan delay making the database connection until the moment it is actually used.\n\n*   CGI::Application::Plugin::FillInForm - makes it a breeze to fill in an HTML form from data\noriginating from a CGI query or a database record.\n\n*   CGI::Application::Plugin::Session - For a project that requires session management, this\nplugin provides a useful wrapper around CGI::Session\n\n*   CGI::Application::Plugin::ValidateRM - Integration with Data::FormValidator and\nHTML::FillInForm\n"
                    },
                    {
                        "name": "More plug-ins",
                        "content": "Many more plugins are available as alternatives and for specific uses. For a current complete\nlist, please consult CPAN:\n\nhttp://search.cpan.org/search?m=dist&q=CGI%2DApplication%2DPlugin\n\n*   CGI::Application::Plugin::AnyTemplate - Use any templating system from within\nCGI::Application using a unified interface\n\n*   CGI::Application::Plugin::Apache - Use Apache::* modules without interference\n\n*   CGI::Application::Plugin::AutoRunmode - Automatically register runmodes\n\n*   CGI::Application::Plugin::Config::Context - Integration with Config::Context.\n\n*   CGI::Application::Plugin::Config::General - Integration with Config::General.\n\n*   CGI::Application::Plugin::Config::Simple - Integration with Config::Simple.\n\n*   CGI::Application::Plugin::CompressGzip - Add Gzip compression\n\n*   CGI::Application::Plugin::LogDispatch - Integration with Log::Dispatch\n\n*   CGI::Application::Plugin::Stream - Help stream files to the browser\n\n*   CGI::Application::Plugin::TemplateRunner - Allows for more of an ASP-style code structure,\nwith the difference that code and HTML for each screen are in separate files.\n\n*   CGI::Application::Plugin::TT - Use Template::Toolkit as an alternative to HTML::Template.\n\nConsult each plug-in for the exact usage syntax.\n"
                    },
                    {
                        "name": "Writing Plug-ins",
                        "content": "Writing plug-ins is simple. Simply create a new package, and export the methods that you want to\nbecome part of a CGI::Application project. See CGI::Application::Plugin::ValidateRM for an\nexample.\n\nIn order to avoid namespace conflicts within a CGI::Application object, plugin developers are\nrecommended to use a unique prefix, such as the name of plugin package, when storing\ninformation. For instance:\n\n$app->{PARAM} = 'foo'; # BAD! Could conflict.\n$app->{'MyPlugin::Module::PARAM'} = 'foo'; # Good.\n$app->{'MyPlugin::Module'}{PARAM} = 'foo'; # Good.\n"
                    },
                    {
                        "name": "Writing Advanced Plug-ins - Using callbacks",
                        "content": "When writing a plug-in, you may want some action to happen automatically at a particular stage,\nsuch as setting up a database connection or initializing a session. By using these 'callback'\nmethods, you can register a subroutine to run at a particular phase, accomplishing this goal.\n\nCallback Examples\n\n# register a callback to the standard CGI::Application hooks\n#   one of 'init', 'prerun', 'postrun', 'teardown' or 'loadtmpl'\n# As a plug-in author, this is probably the only method you need.\n\n# Class-based: callback will persist for all runs of the application\n$class->addcallback('init', \\&someothermethod);\n\n# Object-based: callback will only last for lifetime of this object\n$self->addcallback('prerun', \\&somemethod);\n\n# If you want to create a new hook location in your application,\n# You'll need to know about the following two methods to create\n# the hook and call it.\n\n# Create a new hook\n$self->newhook('pretemplate');\n\n# Then later execute all the callbacks registered at this hook\n$self->callhook('pretemplate');\n\nCallback Methods\n\naddcallback()\n$self->addcallback ('teardown', \\&callback);\n$class->addcallback('teardown', 'method');\n\nThe addcallback method allows you to register a callback function that is to be called at the\ngiven stage of execution. Valid hooks include 'init', 'prerun', 'postrun' and 'teardown',\n'loadtmpl', and any other hooks defined using the \"newhook\" method.\n\nThe callback should be a reference to a subroutine or the name of a method.\n\nIf multiple callbacks are added to the same hook, they will all be executed one after the other.\nThe exact order depends on which class installed each callback, as described below under\nCallback Ordering.\n\nCallbacks can either be *object-based* or *class-based*, depending upon whether you call\n\"addcallback\" as an object method or a class method:\n\n# add object-based callback\n$self->addcallback('teardown', \\&callback);\n\n# add class-based callbacks\n$class->addcallback('teardown', \\&callback);\nMy::Project->addcallback('teardown', \\&callback);\n\nObject-based callbacks are stored in your web application's $c object; at the end of the request\nwhen the $c object goes out of scope, the callbacks are gone too.\n\nObject-based callbacks are useful for one-time tasks that apply only to the current running\napplication. For instance you could install a \"teardown\" callback to trigger a long-running\nprocess to execute at the end of the current request, after all the HTML has been sent to the\nbrowser.\n\nClass-based callbacks survive for the duration of the running Perl process. (In a persistent\nenvironment such as \"modperl\" or \"PersistentPerl\", a single Perl process can serve many web\nrequests.)\n\nClass-based callbacks are useful for plugins to add features to all web applications.\n\nAnother feature of class-based callbacks is that your plugin can create hooks and add callbacks\nat any time - even before the web application's $c object has been initialized. A good place to\ndo this is in your plugin's \"import\" subroutine:\n\npackage CGI::Application::Plugin::MyPlugin;\nuse base 'Exporter';\nsub import {\nmy $caller = scalar(caller);\n$caller->addcallback('init', 'mysetup');\ngoto &Exporter::import;\n}\n\nNotice that \"$caller->addcallback\" installs the callback on behalf of the module that contained\nthe line:\n\nuse CGI::Application::Plugin::MyPlugin;\n\nnewhook(HOOK)\n$self->newhook('pretemplate');\n\nThe \"newhook()\" method can be used to create a new location for developers to register\ncallbacks. It takes one argument, a hook name. The hook location is created if it does not\nalready exist. A true value is always returned.\n\nFor an example, CGI::Application::Plugin::TT adds hooks before and after every template is\nprocessed.\n\nSee \"callhook(HOOK)\" for more details about how hooks are called.\n\ncallhook(HOOK)\n$self->callhook('pretemplate', @args);\n\nThe \"callhook\" method is used to executed the callbacks that have been registered at the given\nhook. It is used in conjunction with the \"newhook\" method which allows you to create a new hook\nlocation.\n\nThe first argument to \"callhook\" is the hook name. Any remaining arguments are passed to every\ncallback executed at the hook location. So, a stub for a callback at the 'pretemplate' hook\nwould look like this:\n\nsub myhook {\nmy ($c,@args) = @;\n# ....\n}\n\nNote that hooks are semi-public locations. Calling a hook means executing callbacks that were\nregistered to that hook by the current object and also those registered by any of the current\nobject's parent classes. See below for the exact ordering.\n\nCallback Ordering\n\nObject-based callbacks are run before class-based callbacks.\n\nThe order of class-based callbacks is determined by the inheritance tree of the running\napplication. The built-in methods of \"cgiappinit\", \"cgiappprerun\", \"cgiapppostrun\", and\n\"teardown\" are also executed this way, according to the ordering below.\n\nIn a persistent environment, there might be a lot of applications in memory at the same time.\nFor instance:\n\nCGI::Application\nOther::Project   # uses CGI::Application::Plugin::Baz\nOther::App    # uses CGI::Application::Plugin::Bam\n\nMy::Project      # uses CGI::Application::Plugin::Foo\nMy::App       # uses CGI::Application::Plugin::Bar\n\nSuppose that each of the above plugins each added a callback to be run at the 'init' stage:\n\nPlugin                           init callback\n------                           -------------\nCGI::Application::Plugin::Baz    bazstartup\nCGI::Application::Plugin::Bam    bamstartup\n\nCGI::Application::Plugin::Foo    foostartup\nCGI::Application::Plugin::Bar    barstartup\n\nWhen \"My::App\" runs, only \"foocallback\" and \"barcallback\" will run. The other callbacks are\nskipped.\n\nThe @ISA list of \"My::App\" is:\n\nMy::App\nMy::Project\nCGI::Application\n\nThis order determines the order of callbacks run.\n\nWhen \"callhook('init')\" is run on a \"My::App\" application, callbacks installed by these modules\nare run in order, resulting in: \"barstartup\", \"foostartup\", and then finally \"cgiappinit\".\n\nIf a single class installs more than one callback at the same hook, then these callbacks are run\nin the order they were registered (FIFO).\n"
                    }
                ]
            },
            "COMMUNITY": {
                "content": "Therese are primary resources available for those who wish to learn more about CGI::Application\nand discuss it with others.\n\nWiki\n\nThis is a community built and maintained resource that anyone is welcome to contribute to. It\ncontains a number of articles of its own and links to many other CGI::Application related pages:\n\n<http://www.cgi-app.org>\n\nSupport Mailing List\n\nIf you have any questions, comments, bug reports or feature suggestions, post them to the\nsupport mailing list! To join the mailing list, visit\nhttp://lists.openlib.org/mailman/listinfo/cgiapp\n\nSource Code\n\nThis project is managed using git and is available on Github:\n\n<https://github.com/MartinMcGrath/CGI--Application>\n",
                "subsections": []
            },
            "SEE ALSO": {
                "content": "o   CGI\n\no   HTML::Template\n\no   CGI::Application::Framework - A full-featured web application based on CGI::Application.\nhttp://www.cafweb.org/\n",
                "subsections": []
            },
            "MORE READING": {
                "content": "If you're interested in finding out more about CGI::Application, the following articles are\navailable on Perl.com:\n\nUsing CGI::Application\nhttp://www.perl.com/pub/a/2001/06/05/cgi.html\n\nRapid Website Development with CGI::Application\nhttp://www.perl.com/pub/a/2006/10/19/cgiapplication.html\n\nThanks to O'Reilly for publishing these articles, and for the incredible value they provide to\nthe Perl community!\n",
                "subsections": []
            },
            "AUTHOR": {
                "content": "Jesse Erlbaum <jesse@erlbaum.net>\n\nMark Stosberg has served as a co-maintainer since version 3.2, Martin McGrath became a\nco-maintainer as of version 4.51, with the help of the numerous contributors documented in the\nChanges file.\n",
                "subsections": []
            },
            "CREDITS": {
                "content": "CGI::Application was originally developed by The Erlbaum Group, a software engineering and\nconsulting firm in New York City.\n\nThanks to Vanguard Media (http://www.vm.com) for funding the initial development of this library\nand for encouraging Jesse Erlbaum to release it to the world.\n\nMany thanks to Sam Tregar (author of the most excellent HTML::Template module!) for his\ninnumerable contributions to this module over the years, and most of all for getting me off my\nass to finally get this thing up on CPAN!\n\nMany other people have contributed specific suggestions or patches, which are documented in the\n\"Changes\" file.\n\nThanks also to all the members of the CGI-App mailing list! Your ideas, suggestions, insights\n(and criticism!) have helped shape this module immeasurably. (To join the mailing list, visit\nhttp://lists.openlib.org/mailman/listinfo/cgiapp )\n",
                "subsections": []
            },
            "LICENSE": {
                "content": "CGI::Application : Framework for building reusable web-applications Copyright (C) 2000-2003\nJesse Erlbaum <jesse@erlbaum.net>\n\nThis module is free software; you can redistribute it and/or modify it under the terms of\neither:\n\na) the GNU General Public License as published by the Free Software Foundation; either version\n1, or (at your option) any later version,\n\nor\n\nb) the \"Artistic License\" which comes with this module.\n\nThis program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;\nwithout even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See\neither the GNU General Public License or the Artistic License for more details.\n\nYou should have received a copy of the Artistic License with this module, in the file ARTISTIC.\nIf not, I'll be glad to provide one.\n\nYou should have received a copy of the GNU General Public License along with this program; if\nnot, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA\n02111-1307 USA\n",
                "subsections": []
            }
        }
    }
}