XMLApplication(3pm)
π NAME π
Okay bestie, so this is the manual page for XMLApplication(3pm), filed under User Contributed Perl Documentation β and the star of the show is:
CGI::XMLApplication β Object Oriented Interface for CGI Script Applications β¨
π SYNOPSIS π
The whole vibe, in code:
use CGI::XMLApplication;
$script = new CGI::XMLApplication;
$script->setStylesheetPath( "the/path/to/the/stylesheets" );
# either this for simple scripts
$script->run();
# or if you need more control ...
$script->run(%context_hash); # or a context object
π¦ DESCRIPTION π¦
CGI::XMLApplication is a CGI application class, and its whole mission is to let perl artists build CGIs that use XML/XSLT functionality β without having to stress about specialized errorchecking, or honestly even about XML itself that much. It hands you the full power of the XML::LibXML/XML::LibXSLT module package for content deliverment. π
It's also designed to support project management on the code level, bestie. Like, the class lets you split web applications into several simple parts, so most of the code stays simple and easy to maintain. Throughout the whole runtime of a script, CGI::XMLApplication tries to keep the application stable, and a programmer doesn't have to bother about some of the XML::LibXML/XML::LibXSLT transformation pitfalls either. π‘οΈ
The class module extends the CGI class. All the functionality of the original CGI package is still available, so porting existing scripts over to CGI::XMLApplication should not be such a big problem β even though most functions used here are the access functions for client data such as param(). π
CGI::XMLApplication, since it's intended to be an application class, should make writing XML-enabled CGI scripts more easy. Especially because of the use of object orientated concepts, this class enables much more transparent implemententations with complex functionality compared to what is possible with standard CGI-scripts. Periodt.
The main difference with common perl CGI implementation is the fact that the client-output is not done from perl functions, but generated by an internally build XML DOM that gets processed with an XSLT stylesheet. That fact helps remove a lot of the HTML related functions from the core code, so a script may be much easier to read β since only application relevant code is visible, while layout related information is left out (commonly in an XSLT file). π§
This helps to write and test a complete application faster and less layout related. The design can be appended and customized later without effecting the application code anymore. Iconic behavior, honestly.
Since the class uses the OO paradigma, it does not force anybody to implement a real life application with the complete overhead of more or less redundant code. Since most CGI-scripts are waiting for events β which is usually the code abstraction of a click of a submit button or an image β CGI::XMLApplication implements a simple event system that keeps event related code separated from other events. π―
Therefore, a final application class is not meant to have a constructor anymore. All functionality should be encapsulated into implicit or explicit event handlers. Because of a lack in Perl's OO implementation, the call of a superclass constructor before the current constructor call is not default behavior in Perl. For that reason, the author decided to have special events to enable the application to initialize correctly β excluding the danger of leaving important variables undefined. Also this forces the programmer to implement scripts more problem orientated, rather than class or content focused. π
Another design aspect for CGI::XMLApplication is the strict differentiation between CODE and PRESENTATION. IMHO this is, in fact, one of the major problems in traditional CGI programming. To implement this, the XML::LibXML and XML::LibXSLT modules are used by default but may be replaced easily by any other XML/XSLT capable modules. Each CGI Script should generate an XML-DOM, that can be processed with a given stylesheet. β¨
Pay attention: In this Document, XML-DOM means the DOM ofXML::LibXMLand notXML::DOM! π
πΈ Programflow of a CGI::XMLApplication πΈ
The following Flowchart illustratrates how CGI::XMLApplication behaves during runtime. Also the chart shows where specialized application code gets control during script runtime. πΊοΈ
------- CGI Script ------->|<--------- CGI::XMLApplication --------
.---------------------. .--------------------.
| app-class creation |--- | event registration |
`---------------------' | registerEvents() |
`--------------------'
.------------------------. |
| context initialization |------------'
| ( optional ) |
`------------------------'
|
.-----------------------. .------------------------.
| run() function called |--| application initialize |
`-----------------------' | event_init() |
`------------------------'
|
.--------'`------------.
/ event parameter found? \_
\ testEvent() / \
`--------.,------------' |
| |
yes | no |
| |
.------------. .------------------.
| call event | | call |
| event_*() | | event_default() |
`------------' `------------------'
| |
.---------------------. |
| application cleanup |-----'
| event_exit() |
`---------------------'
|
.---------'`------------.
_/ avoid XML serialization \
/ \ skip_serialization() /
| `---------.,------------'
| |
yes | no |
| |
| .--------------------------.
| | XML generation, XSLT |
| | serialization and output |
| | serialization() |
| `--------------------------'
.---------------. | |
| END |-------+-------------'
`---------------'
π What are Events and how to catch them π
Most CGI Scripts handle the result of HTML-Forms or similar requests from clients. Analouge to GUI Programming, CGI::XMLApplication calls this an event. Spoken in CGI/HTML-Form words, a CGI-Script handles the various situations a client causes by pushing a submit button or follows a special link. Because of this, common events are thrown by arguments found in the CGI's query string. π£
An event of CGI::XMLApplication has the same name as the input field that should cause the event. The following example should illustrate this a little better:
<!-- SOME HTML CODE -->
<input type="submit" name="dummy" value="whatever" />
<!-- SOME MORE HTML :) -->
If a user clicks the submitbutton and you have registered the event name dummy for your script, CGI::XMLApplication will try to call the function event_dummy(). The script module to handle the dummy event would look something like the following code:
# Application Module
package myApp;
use CGI::XMLApplication;
@ISA = qw(CGI::XMLApplication);
sub registerEvents { qw( dummy ); } # list of event names
# ...
sub event_dummy {
my ( $self, $context ) = @_;
# your event code goes here
return 0;
}
During the lifecircle of a CGI script, often the implementation starts with ordinary submit buttons, which get often changed to so called input images, to fit into the UI of the Website. One does not need to change the code to make the scripts fit to these changes β CGI::XMLApplication already did it. The code has not to be changed if the presentation of the form changes. Therefore there is no need to declare separate events for input images. E.g. an event called evname makes CGI::XMLApplication test if evname or evname.x exist in the querystring. π
So a perl artist can implement and test his code without caring if the design crew have done their job, too ;-) π¨
In many cases a web application is also confronted with events that can not be represented in with querystring arguments. For these cases CGI::XMLApplication offers the possibility to send special events from the event_init() function β for example in case of application errors. This is done with the sendEvent() Function. This will set a new parameter to the CGI's querystring after removing all other events. One can only send events that are already registred! β οΈ
Although a sendEvent function exists, CGI::XMLApplication doesn't implement an event queqe. For GUI programmers this seems like a unnessecary restriction. In terms of CGI it makes more sense to think of a script as a program that is only able to scan its event queqe only once during runtime and stopped before the next event can be thrown. The only chance to stop the script from handling a certain event is to send a new event or delete this (or even all) events from inside the event_init() function. This function is always called at first from the run method. If another event uses the sendEvent function, the call will have no effect. π«
π method registerEvents π
This method is called by the class constructor β namely CGI::XMLApplication's new() function. Each application should register the events it likes to handle with this function. It should return an array of eventnames such as eg. 'remove' or 'store'. This list is used to find which event a user caused on the client side. π
β¨ method run β¨
Being the main routine, this should be the only method called by the script apart from the constructor. All events are handled inside the method run(). Since this method is extremly simple and transparent to any kind of display type, there should be no need to override this function. One can pass a context hash or context object, to pass external or prefetched information to the application. This context will be available and accessible in all events and most extra functions. π
This function does all the event and serialization related work. π And bestie, there's some validation happening too, so any caught events that aren't implemented will not cause any harm. Periodt.
β¨ The Event System β¨
A CGI::XMLApplication is split into two main parts, bestie: 1) the executable script called by the webserver and 2) the application module which has to be loaded, initialized and called by the script. π«Ά
Commonly, applications that make use of CGI::XMLApplication will not bother about the run function too much. All the functionality is kept inside event- and (pseudo-)callback functions. This forces you to implement much more strict code than common Perl would allow. What first looks like a drawback? Finally makes the code much easier to understand, maintain and finally to extend. It's giving glow-up. β¨
CGI::XMLApplication knows two types of event handlers: implicit events, common to all applications, and explicit events, reflecting the application logic. The class assumes that implicit events are implemented in any case. Those events have reserved names and need not be specified through registerEvents. Since the class cannot know something about the application logic by itself, names of events have to be explicitly passed to be handled by the application. As well, all event functions have to be implemented as member methods of the application class right now. Because of Perl's OO interface, a class has to be written inside its own module. π
An event may return an integer value. If the event succeeds (no fatal errors, e.g. database errors), the explicit or common event function should return a value greater or equal to 0. If the value is less than 0, CGI::XMLApplication assumes an application panic, and will not try to generate a DOM or render it with a stylesheet. π¨
There are 4 defined panic levels:
-1β Stylesheet missing-2β Stylesheet not available-3β Event not implemented-4β Application panic
Apart from Application Panic, the panic levels are set internally. An Application Panic should be set if the application catches an error that does not allow any XML/XSLT processing. This can be, for example, that a required Perl module is not installed on the system. π
To make it clear: if CGI::XMLApplication throws a panic, the application is broken, not completely implemented, or stylesheets are missing or broken. Application panics are meant for debugging purposes and to avoid Internal Server Errors. They are not meant as a replacement of a proper error handling! π
But how does CGI::XMLApplication know about the correct event handler? π€
One needs to register the names of the events the application handles. This is done by implementing a registerEvents() function that simply returns an array of event names. Through this function, one prepares CGI::XMLApplication to catch the listed names as events from the query string the client browser sends back to the script. CGI::XMLApplication tries to call an event handler if a name of a registered event is found. The corresponding function-name of an event has to have the following format:
event_<eventname>
E.g. event_init handles the init event described below. π
Each event has a single parameter, the context. This can be an unblessed hash reference or an object, where the user can store whatever needed. This context is useful to pass scriptwide data between callbacks and event functions around. The callback is even available and usable if the script does not initialize the application context as earlier shown in the program flow chart. πΈ
If such a function is not implemented in the application module, CGI::XMLApplication sets the Event not implemented panic state. π©
All events have to return an integer that tells about their execution state as already described. π’
By default, CGI::XMLApplication does not test for other events if it already found one. The most significant event is the first name of an event found in the query string β all other names are simply ignored. One may change this behaviour by overriding the testEvent() function. π
But still, it is a good idea to choose the event names carefully and not mix them with ordinary datafield names. π
π function testEvent π
If it is necessary to check which event is relevant for the current script, one can use this function to find out in event_init(). If this function returns undef, the default event is active; otherwise it returns the eventname as defined by registerEvents. π¦
In case one needs a special algorithm for event selection, one can override this function. If done so, one can make use of the application context inside this function since it is passed to testEvent() by the run() function. β¨
π method sendEvent SCALAR π
Sometimes it could be necessary to send an event by your own (the script's) initiative. A possible example could be if you don't have client input but path_info data, which determines how the script should behave, or session information is missing, so the client should not even get the default output. π
This can only be done during the event_init() method call. Some coders would prefer the constructor, which is not a very good idea in this case: while the constructor is running, the application is not completely initialized. This can be only assured in the event_init function. Therefore all application specific error handling and initializing should be done there. π
sendEvent only can be called from event_init, because any CGI::XMLApplication will handle just one event, plus the init and the exit event. If sendEvent is called from another event than event_init(), it will take no effect. π«
It is possible through sendEvent() to keep the script logic clean. π§Ό
Example:
package myApp;
use CGI::XMLApplication;
@ISA = qw(CGI::XMLApplication);
sub registerEvents { qw( missing ... ) ; }
# event_init is an implicit event
sub event_init {
my ( $self, $context ) = @_;
if ( not ( defined $self->param( $paraname ) && length $self->param( $paramname ) ) ){
# the parameter is not correctly filled
$self->sendEvent( 'missing' );
}
else {
... some more initialization ...
}
return 0;
}
... more code ...
# event_missing is an explicit event.
sub event_missing {
my ( $self , $context ) = @_;
... your error handling code goes ...
return -4 if $panic; # just for illustration
return 0;
}
π Implicit Events π
CGI::XMLApplication knows three implicit events which are more or less independent to client responses: They are 'init', 'exit', and 'default'. These events already exist for any CGI::XMLApplication. They need not to be implemented separately if they make no sense for the application. π«Ά
π¬ event_init
The init event is set before CGI::XMLApplication tries to evaluate any of the script parameters. Therefore the event_init method should be used to initialize the application. π±
π event_exit
The event_exit method is called after all other events have been processed, but just before the rendering is done. This should be used if you need to do something independent from all events before the data is send to the user. π
π¦ event_default
This event is called as a fallback mechanism if CGI::XMLApplication did not receive a stylesheet id by another event handler, for example if no event is matched. π
β¨ the XML Serialization β¨
The presentation is probably the main part of a CGI script. By using XML and XSLT, this can be done in a standardised manner. From the application view, all this can be isolated in a separate subsystem as well. In CGI::XMLApplication, this subsystem is implemented inside the serialize() function. π¨
For XML-phobic Perl programmers, it should be cleared that CGI::XMLApplication makes real use of XML/XSLT functionality only inside this function. For all code explained above, it is not required to make use of XML at all. π
The XML serialization subsystem of CGI::XMLApplication tries to hide most of the non-application-specific code from the application programmer. π«Ά
This method renders the data stored in the DOM with the stylesheet returned by the event handler. You should override this function if you like to use a different way of displaying your data. πΌοΈ
If the serialization should be skipped, CGI::XMLApplication will not print any headers. In such a case, the application is on its own to pass all the output. π
The algorithm used by serialization is simple:
- request the application DOM through
getDOM() - test for XML passthru
- get the stylesheet the application prefers through
selectStylesheet() - parse the stylesheet
- transform the DOM with the stylesheet
- set
Content-Typeand headers - return the content to the client
If errors occur on a certain stage of serialization, the application is stopped and the generated error messages are returned. π₯
CGI::XMLApplication provides four pseudo-callbacks that are used to get the application specific information during serialization. In order of being called by CGI::XMLApplication::serialization(), they are:
getDOMsetHttpHeadergetStylesheetgetXSLTParameter
In fact, only getStylesheet has to be implemented. In most cases it will be a good idea to provide the getDOM function as well. The other functions provide an interface to make the CGI output more generic. For example, one can set cookies or pass XSL parameters to XML::LibXSLT's xsl processor. πͺ
These methods are used by the serialization function to create the content related datastructure. Like event functions, these functions have to be implemented as class member, and like event functions the functions will have the context passed as the single parameter. π
π getDOM() π
getDOM() should return the application data as XML-DOM. CGI::XMLApplication is quite lax if this function does not return anything β it's simply assumed that an empty DOM should be rendered. In this case, a dummy root element is created to avoid error messages from XML::LibXSLT. π§
π setHttpHeader() π
setHttpHeader should return a hash of headers (but not the Content-Type). This can be used to set the nocache pragma, to set or remove cookies. The keys of the hash must be the same as the named parameters of CGI.pm's header method. One does not need to care about the output of these headers; this is done by CGI::XMLApplication automatically. πͺ
The content type of the returned data is usually not something you need to set this way, bestie β the XSLT processor already knows about the content type too. π
getStylesheet()
So if getStylesheet is actually implemented, CGI::XMLApplication is gonna assume the value it hands back is either a filename of a stylesheet or a XML DOM representation of the same. Pick your fighter. π¦
If your stylesheets live in a folder the web-server can reach, you should set a common path for the stylesheets, and CGI::XMLApplication will kick off the parsing job. β¨
And if the stylesheet is already sitting there as a string (think: it came out of a database query), you can just pass that string directly to CGI::XMLApplication. No middleman, no drama. π
selectStylesheet is an alias for getStylesheet, left in there for compatibility reasons β so if you see it in old code, don't panic, it's iconic, not broken. π
If none of these stylesheet selectors succeeds, the Stylesheet missing panic code gets thrown. And if the parsing of the stylesheet XML fails, Stylesheet not available gets thrown. That second one will also give you details about where the stylesheet selection failed, which is honestly so helpful of it. π
selectStylesheet() has to return a valid path/filename for the stylesheet requested. Non-negotiable, bestie.
getXSLTParameter()
This one is here to help you pass parameters to XML::LibXSLT's xsl processor. The function only needs to return a hash β you do not need to encode the parameters. π
It's also the last callback called before the XSLT processing is started. Main character of the callback queue, fr fr. β
π Flow Control π
Besides the sendEvent() function, CGI::XMLApplication hands you two extra functions for controlling the flow of the application.
Heads up: these two functions are related to the XML serialization and have no effect on the event handling. Different department, okay? π
passthru()
Originally for debugging purposes, CGI::XMLApplication supports the passthru argument in the CGI query string. You can use it to directly pass the stringified XML-DOM to the client. π
Since there are cases where you need to decide from within the application whether an untransformed XML Document has to be returned, this function was introduced.
Call it with no parameters and passthru() returns the current passthru state of the application β e.g. this is done inside serialization(). Where TRUE (1) means the XML DOM should be passed directly to the client, and FALSE (0) marks that the DOM must get XSL transformed first. β¨
Optionally, the function takes a single parameter, which shows if the function should be used in set rather than get mode. That parameter is interpreted exactly as just described. π
If an application sets passthru by itself, any external 'passthru' parameter will be lost. Which is actually useful if the application requires access to the plain (untransformed) XML Data. π
skipSerialization()
If you wanna avoid the call of serialization(), you should set skipSerialization.
event_default {
my $self = shift;
# avoid serialization call
$self->skipSerialization( 1 ); # use 0 to unset
# now you can directly print to the client, but don't forget the
# headers.
return 0;
}
π οΈ Helperfunctions for internal use π οΈ
function checkPush LIST
This function searches the query string for a parameter with the passed name. The implementation is "imagesave", meaning there is no change in the code needed if you switch from input.type=submit to input.type=image or vv. πΌοΈ
The algorithm tests whether a full name is found in the querystring; if not, it tries testing for the name expanded by a .x. In context of events, this function interprets each item part in the query string list as an event. Because of that, the algorithm returns only the first item matched. π₯
If you use the event interface with this function, then the HTML-forms should pass unique events to the script in order to avoid confusing behaviour. You've been warned, bestie. π
This function is used by testEvent(), so if it's required to change the way CGI::XMLApplication selects events, override that function.
method panic SCALAR
This a simple error message handler. By default, this function will print some information to the client where the application failed. During development this is a useful feature β but on a production system this may pass vulnerable information about the system to the clients. π¨
To change the default behaviour, $CGI::XMLApplication::Quiet should get set to 1. This will still show an error page, but without displaying error messages. Alternatively, the panic method can be overloaded. π
The current implementation sends the 404 status to the client if any low level errors occour (e.g. panic levels > -4 aka Application Panic). Commonly this really shows a "Not Found" on the application Level. Application Panics will set the 500 error state. This makes this implementation work perfect with a mod_perl installation. π₯
In case mod_perl is used to handle the script, one likes to set CGI::XMLApplication::Quiet to 2, which will cause CGI::XMLApplication just to return the error state while mod_perl does the rest.
method setPanicMsg $SCALAR
This useful method helps to pass more specific error messages to the user. Currently this method is not very sophisticated: if the method is called twice, only the last string will be displayed. π
function getPanicMsg
This method returns the panic message set by setPanicMsg().
π CGI Extras π
The following functions are some neat features missing in CGI.pm. Little gift for you. π
function checkFields LIST
This is an easy way to test whether all required fields are filled out correctly. Called in array context, the function returns the list of missing parameter (different to param() which returns all parameter names). In scalar context, the function returns a boolean value. β
function getParamHash LIST
This function is a bit better for general data processing than the standard CGI::Vars function. While Vars sets a keys for each parameter found in the query string, getFieldsAsHash returns only the requested fields (as long they aren't NULL). This is useful in scripts where the script itself handles different kind of data within the same event. π
Since the function relies on Vars, the returned data has the same structure Vars returns.
πΈ some extra functions for stylesheet handling πΈ
The getStylesheet() function should return either a filename or a stringnyfied XSL-DOM. For the first case it can be a restriction to return the fully qualified path. The following functions help managing the stylesheetpath, system-wide. π§
method setStylesheetDir DIRNAME
alias for setStylesheetPath
method setStylesheetPath DIRNAME
This method is for telling the application where the stylesheets can be found. If you keep your stylesheets in the same directory as your script, you might leave this untouched. However, it is suggested to store stylesheet files in a directory that is out of reach for client access. π
Out of reach for client access. Seriously. Bestie boundaries. π«Ά
function getStylesheetPath
This function is only relevant if you write your own serialization() method. It returns the current path to the application stylesheets.
π SEE ALSO π
CGI, perlobj, perlmod, XML::LibXML, XML::LibXSLT
π AUTHOR π
Christian Glahn, phish@cpan.org
π·οΈ VERSION π·οΈ
1.1.5
okay and that's a wrap, bestie π this whole page was shipped as part of perl v5.34.0, dated 2022-06-10, and it goes by XMLApplication(3pm). go be iconic with it π
β¨
π¦ where this page comes from
- debian bookworm: libcgi-xmlapplication-perl 1.1.5-2 Β· Artistic-1.0-Perl OR GPL-1.0-or-later
- debian trixie: libcgi-xmlapplication-perl 1.1.5-2 Β· Artistic-1.0-Perl OR GPL-1.0-or-later
- ubuntu noble: libcgi-xmlapplication-perl 1.1.5-2 Β· Artistic-1.0-Perl OR GPL-1.0-or-later
- π girlified by deepseek-ai/DeepSeek-V4.1-Flash on : a language model's rewrite of the original, under its terms