Tags:

Class Methods

The constructor sets up default values for _HEADER_TYPE, _MODE_PARAM, and _START_MODE. If an associative array has been passed to it as an argument, it processes it. The array should have one or more of the following elements:

TMPL_PATH: an optional path argument passed to tmpl_path()
along with _TMPL_ARGS (if given) to instantiate the
template object. This should be the path to the base template
directory; if using Smarty, this would be the directory holding the
templates, templates_c, configs, and cache directories.

TMPL_ARGS: an optional associative array of arguments to pass to the
template object constructor. These can include any valid arguments to
the template object constructor.

PARAMS: an optional associative array of parameters that your
application needs for setup purposes. These might include a database
DSN, template file names, or specific environment selectors. Keys will
be normalized using cap_hash, and all parameters will be made
into class variables using the param() method.

Once the above have been processed, Cgiapp2 calls the cgiapp_init() method, followed by the setup() method; both of these should be overridden in your class extension.

Tags:

return:

success

access:

public

Parameters:

array

$args

Optional, an associative array; see method and class intro notes for details

The add_callback() method allows you to register a callback function that is to be called at the given stage of execution. Valid hooks include 'init', 'prerun', 'postrun' and 'teardown', 'tmpl_path', 'tmpl_fetch', and any other hooks defined using the new_hook() method.

If multiple callbacks are added to the same hook, they will all be executed one after the other. The exact order depends on which class installed each callback, and the order in which they were registered.

If no $class is specified, and an object callback is specified, and the object is a Cgiapp2-derived class, that object's class will be used.

Callbacks are executed first for the current class, then the parent class, and on up the class hierarchy. Additionally, if multiple callbacks are registered for a given class, then they are executed in the order in which they are registered.

Callbacks are stored in the $_INSTALLED_CALLBACKS static property. $_INSTALLED_CALLBACKS is a multi-dimensional array with the first key being the hook, and the second the classname; callbacks are stored under $_INSTALLED_CALLBACKS[$hook][$classname].

Class-based callbacks are useful for plugins to add features to all web applications.

Another feature of class-based callbacks is that your plugin can create hooks and add callbacks at any time - even before the web application's object has been initialized. You could do this in your class definition file:

The above code would register a global plugin that would execute in the cgiapp_init() method.

NOTE: Due to the nature of templating, the various tmpl_* hooks are setup so that they always register with the Cgiapp2 class, and such that only one callback is allowed per template hook; the last callback to register will be the callback used.

Make sure that the callback is executable (i.e., the visibility allows call_hook() to call it).

Looks in the current class, and then up the class hierarchy for any hooks registered, giving those further up the last call.

If more than one hook is executed or has a return value, than all return values will be returned as an array. Otherwise, call_hook() returns a single value as designated by the callback. You may want to pass references as arguments to your callbacks if you want them to cascade values.

Tags:

Parameters:

Carp is the name of a perl module and is used to provide warnings -- in other words, to notify the user/developer of non-fatal errors. The carp() method does similarly, but uses PHP's native trigger_error() function to do so, with an E_USER_WARNING level error. Note: If your application sets custom headers, a carp() may break them, if the INI setting 'display_errors' is on.

By using Cgiapp2 and the cgiapp_init() method as illustrated, a suite of applications could be designed to share certain characteristics, such as a database connection, template engine, etc. This has the potential for much cleaner code built on object-oriented inheritance.

UPGRADE NOTE: For those upgrading from a pre-2.0.0 version of Cgiapp2, please note that this method now accepts a second argument, an object instance.

cgiapp_postrun() implements the $_INSTALLED_CALLBACKS of the callback system. If implemented, the hook is called after the run mode method has returned its output, but before HTTP headers are generated or content presented. This will give you an opportunity to modify the content and headers before they are returned to the web browser.

A typical use for this hook is piping the output of a run mode through a series of "filter" processors. For example:

You want to enclose the output of all your run modes within a
larger, site-wide template.

Your run modes return structured data (such as XML), which you
want to transform using a standard mechanism (such as XSLT).

You want to modify HTTP headers in a particular way across all
run modes, based on particular criteria.

The first argument received is the current generated body content.

Since this is a add_callback() callback hook, the second argument is an object instance; if implementing in a Cgiapp2-based class, you can typically ignore this value.

NOTE:run() passes the output from your run mode to cgiapp_postrun(), but does not expect anything to return from the method (in point of fact, it does nothing with the method's return value). If you plan on modifying that content or replacing it, call postrun_body() with the new or modified content, as shown in the example above.

Obviously, with access to the Cgiapp2 object you have full access to use all the methods normally available in a run mode. You could, for example, use load_tmpl() to replace the static HTML in this example with content from a template (assigning $body to the template). You could change the HTTP headers (via header_type() and header_props() methods) to set up a redirect. You could also use the objects properties to apply changes only under certain circumstance, such as a in only certain run modes, and when a param() is a particular value.

UPGRADE NOTE: For those upgrading from a pre-2.0.0 version of Cgiapp2, please note that this method now accepts a second argument, an object instance. Also note that $body is no longer passed by reference, and that to update or change the generated $body, you must use postrun_body().

cgiapp_prerun() implements the $_INSTALLED_CALLBACKS of the callback system. If utilized, the hook is called automatically right before the selected run mode method is called.

The first argument passed is the name of the requested run mode.

Since this is a add_callback() callback hook, the second argument is an object instance; if implementing in a Cgiapp2-based class, you can typically ignore this value.

Use this hook and the run mode argument to provide functionality prior to the requested run mode method being called. Uses include checking ACLs for permissions to the requested run mode. You may call prerun_mode() from this method to then change the requested run mode.

Another benefit provided by utilizing this hook is creating a custom "application super-class" from which all your CGI applications would inherit, instead of Cgiapp2.

Tags:

Parameters:

croak() was originally a method of the perl Carp module; it's purpose is to trigger fatal errors. The croak() method here does the same, utilizing PHP's native trigger_error() function with an E_USER_ERROR level error.

UPGRADE NOTE: This method is now static.

Tags:

static:

access:

public

Parameters:

The delete() method is used to delete a parameter that was previously stored inside of your application either by using the PARAMS associative array that was passed when instantiating the object or by a call to the param() method. It is useful if your application makes decisions based on the existence of certain params that may have been removed in previous sections of your app or simply to clean-up your param()s.

Tags:

Parameters:

The dump() method is a debugging function which will return a chunk of text which contains all the environment and CGI form data of the request, formatted nicely for human readability. Useful for debugging in a CLI environment.

Tags:

The dump_html() method is a debugging function which will return a chunk of text which contains all the environment and CGI form data of the request, formatted nicely for human readability via a web browser. Useful for outputting to a browser.

Tags:

The error_mode() contains the name of a run mode to call in the event that the planned run mode call fails. No error_mode is defined by default. The death of your error_mode() run mode is not trapped, so you can also use it to die in your own special way.

error_mode() is used in the run() method. If your run mode (or a method it calls) generates an exception, error_mode() is called to determine a method to run that should generate the content to return to the user (i.e., the method should act like a run mode).

Tags:

access:

public

Parameters:

The get_current_runmode() method will return a text scalar containing the name of the run mode which is currently being executed. If the run mode has not yet been determined, such as during setup(), this method will return undef.

The header_type() method expects to be passed either 'header', 'redirect', or 'none'. This method specifies the type of HTTP headers which should be sent back to the browser. If not specified, defaults is 'header'. You can use this method to specify additional or alternate HTTP headers for your application or run mode; this could be useful for returning alternate content (a PDF or image file, for instance).

If you wish to suppress HTTP headers entirely (as might be the case if you're working in a slightly more exotic environment), you can set header_type() to "none". This will send no headers. Be warned: since you are programming in PHP, some headers will be passed if you are running your script via a web server.

is_assoc_array() tests an array to determine if it is an associative array; this is necessary functionality for a number of other methods, including param() and run_modes(). It is based on a function found in the document comments for is_array on php.net. It's primary bug is that an associative array made with sequential integer keys will look just like a regular array and thus return a false result.

UPGRADE NOTE This class may no longer be overridden, as it implements the callback hook 'tmpl_fetch'. Also, in order to use it, you will need to include a template plugin in your application or superclass:

This would allow you to create an instance method whose output would be used as the value of the current run mode. E.g., a "mode param method":

function some_method()

{

// Do some stuff here, such as looking at SERVER_NAME or

// PATH_INFO, and return a mode parameter accordingly

return 'run_mode_x';

}

In the third case mentioned above, you may specify the index of the PATH_INFO element to utilize as the run mode, where PATH_INFO elements are separated by a '/' character. With this method, it is also wise to pass a PARAM key which specifies a $CGIAPP_REQUEST parameter to use as a fallback. For example:

would look for the second element in the PATH_INFO string for the run mode, or the 'q' $CGIAPP_REQUEST key if not found. So, in the following:

/path/to/webapp.php/do/view/2

the run mode would be set to 'view' (as that's the second element in the PATH_INFO string). But in this:

/path/to/webapp.php/do/?q=form&id=2

since there is no second element in the PATH_INFO string, the application would grab the parameter from the 'q' $CGIAPP_REQUEST element.

If you use a negative index, then Cgiapp2 will look from the end of the PATH_INFO list. In the example above, if '-2' were passed as the index, it would use the item 'view' (second from the end).

If 'param' is not specified in the array passed to mode_param(), then the default run mode of 'rm' is assumed.

NOTE: As of 1.5.2, if the value passed to mode_param() is the name of a Cgiapp2 internal method (other than dump(), dump_html(), carp(), or croak()) or PHP internal function, the run mode will be pulled from the $CGIAPP_REQUEST parameter. This is to enhance security and also to allow using common keywords as mode parameters.

NOTE 2: Try not to use PHP internal function names as mode parameters. In order to check against the PHP internal function list when a mode parameter matching a function is passed, Cgiapp2 calls get_defined_functions(), which causes a significant performance hit.

Tags:

return:

Run mode parameter

access:

public

Parameters:

string|array

$mode_param

Optional; the name of the CGI run mode parameter, the name of a function or class method that can return a run mode, or an array specifying the index in PATH_INFO to use and an optional PARAM that could specify a run mode

Allows developers to create a new location to register callbacks. Takes up to two arguments, a hook name, and a class name or object. If no class name or object is specified, the hook is registered with the global Cgiapp2 class.

The param() method enables a very valuable system for customizing your applications on a per-instance basis. One Application Class might be instantiated by different Instance Scripts. Each Instance Script might set different values for a set of parameters. This allows similar applications to share a common code-base, but behave differently. For example, imagine a mail form application with a single Application Class, but multiple Instance Scripts. Each Instance Script might specify a different recipient. Another example would be a web bulletin boards system. There could be multiple boards, each with a different topic and set of administrators.

The constructor method provides a shortcut for specifying a number of run-time parameters at once. Internally, Cgiapp2 calls the param() method to set these properties. The param() method is a powerful tool for greatly increasing your application's re-usability.

Parameters:

If PATH_INFO exists in the server API, creates an array of elements found in PATH_INFO.

If called with no arguments, the entire array is passed. If provided a positive integer argument, the element in the array with that index is returned (if it exists); a negative integer argument returns that element from the end of the array.

Additionally, if passed a string argument, it will look for a path element matching that string and pass the value to its right:

In this example, the web user will be forced into the "login" run mode unless they have already logged in. The prerun_mode() method permits a scalar text string to be set which overrides whatever the run mode would otherwise be.

The use of prerun_mode() within cgiapp_prerun() differs from setting mode_param() to use a call-back via subroutine reference. It differs because cgiapp_prerun() allows you to selectively set the run mode based on some logic in your cgiapp_prerun() method. The call-back facility of mode_param() forces you to entirely replace Cgiapp2's mechanism for determining the run mode with your own method. The prerun_mode() method should be used in cases where you want to use Cgiapp2's normal run mode switching facility, but you want to make selective changes to the mode under specific conditions.

Note: The prerun_mode() method may ONLY be called in the context of a cgiapp_prerun() method. Your application will die() if you call prerun_mode() elsewhere, such as in setup() or a run mode method.

Parameters:

This method grabs all POST and GET variables and puts them in a single, protected array, $CGIAPP_REQUEST. This array may then be referenced when you wish to scrutinize GET or POST variables, but don't care where they come from. It is somewhat safer than using $_REQUEST as it does not utilize $_COOKIE variables, thus limiting one more source for a particular variable.

This method first determines the application state by looking at the value of the CGI parameter specified by mode_param() (defaults to 'rm' for "Run Mode"), which is expected to contain the name of the mode of operation. If not specified, the state defaults to the value of start_mode().

Once the mode has been determined, run() looks at the dispatch table stored in run_modes() and finds the function pointer which is keyed from the mode name. If found, the function is called and the data is returned to STDOUT (usually the browser). If the specified mode is not found in the run_modes() table, run() will croak().

Tags:

run_modes() expects an associative array which specifies the dispatch table for the different CGI states. The run() method uses the data in this table to send the CGI to the correct function as determined by reading the CGI parameter specified by mode_param() (defaults to 'rm' for "Run Mode"). These functions are referred to as "run mode methods".

The associative array set by this method is expected to contain the mode name as a key. The value should be either a reference to a function or method to the run mode method which you want to be called when the CGI enters the specified run mode, or the name of the run mode method to be called (preferred):

'mode_name_by_ref' => &mode_function()

'mode_name_by_name' => 'mode_function'

The run_mode() method specified is expected to return a block of text (e.g.: HTML) which will eventually be sent back to the web browser. Commonly, this block of text will be returned by using a construction like:

An advantage of specifying your run mode methods by name instead of by reference is that you can more easily create derivative applications using inheritance. For instance, if you have a new application which is exactly the same as an existing application with the exception of one run mode, you could simply inherit from that other application and override the run mode method which is different. If you specified your run mode method by reference, your child class would still use the function from the parent class.

In perl, there's a speed advantage to assigning by reference; however, in PHP this is not the case, which provides yet another reason to specify your run modes by name rather than reference.

The run_modes() method may be called more than once. Additional values passed into run_modes() will be added to the run modes table. In the case that an existing run mode is re-defined, the new value will override the existing value. This behavior might be useful for applications which are created via inheritance from another application, or some advanced application which modifies its own capabilities based on user input.

A second interface for designating run modes and their methods is via an indexed array:

Note that another importance of specifying your run modes in either an array or associative array is to assure that only those methods which are specifically designated may be called via your application. Application environments which don't specify allowed methods and disallow all others are insecure, potentially opening the door to allowing execution of arbitrary code. Cgiapp2 maintains a strict "default-deny" stance on all method invocation, thereby allowing secure applications to be built upon it.

Tags:

Set the default run mode to use when no run mode is specified by the client

The start_mode() contains the name of the mode as specified in the run_modes() table. Default mode is "start". The mode key specified here will be used whenever the value of the CGI form parameter specified by mode_param() is not defined. Generally, this is the first time your application is executed.

Tags:

Parameters:

Similar to param(), s_param() sets a session parameter for use with the application. Internally, it does the following:

Checks to see if session handling is active; if not, it
produces a warning and returns false.

Determines the session ID:

It checks for the existence of a parameter called
'$_SESSION_ID' and fetches it if found;

If the $_SESSION_ID parameter is *not* found,
call PHP's session_name() and use that value.

If no values are passed, returns an array of all $_SESSION
variables, whether or not they were set with the s_param
method.

If a single string value is passed to the method, prepend the
$_SESSION_ID to the value and return the value of that
session key; if the session key does not exist, return false; if
the session key is invalid (array, object), emit a warning.

If two values are passed to the method, and the first value is a
string, prepend the $_SESSION_ID to the first value and
set a session variable with that name and assign it a value of
the second parameter sent to s_param().

If an associative array is passed to the method, prepend each key
with the $_SESSION_ID and create session variables with
each key and value.

If an array with an even number of elements is passed to the
method, use array_to_hash() to create an associative
array out of it, and do the same as the above.

Parameters:

teardown() implements the $_INSTALLED_CALLBACKS of the callback system, which is called automatically after your application runs; it can be used to clean up after your operations.

A typical use of the teardown() method is to disconnect a database connection which was established in the setup() function (or init hook). You could also use the teardown() method to store state information about the application to the server.

UPGRADE NOTE: For those upgrading from a pre-2.0.0 version of Cgiapp2, please note that this method now accepts an argument, an object instance.

Tags:

access:

protected

Parameters:

Attempts to assign content to a template. If a tmpl_assign callback hook is registered, it will use that callback (see $_INSTALLED_CALLBACKS and add_callback() for information on plugin callbacks), passing it all arguments.

UPGRADE NOTE This class may no longer be overridden, as it implements the callback hook 'tmpl_assign'. Also, in order to use it, you will need to include a template plugin in your application or superclass:

tmpl_path() sets the file path to the base directory where the templates are stored. It then calls the tmpl_path hook.

tmpl_path() also takes an optional argument of an associative array of parameters to pass to the template engine constructor; this can be used to customize the template engine's behaviour for your application. It is passed to the tmpl_path hook.

UPGRADE NOTE This class may no longer be overridden, as it implements the callback hook 'tmpl_path'. Also, in order to use it, you will need to include a template plugin in your application or superclass: