Cgiapp2
[ class tree: Cgiapp2 ] [ index: Cgiapp2 ] [ all elements ]

Class: Cgiapp2

Source Location: /Cgiapp2.class.php

Class Overview


Cgiapp2 - Framework for building reusable web-applications


Author(s):

Version:

  • @release-version@

Methods


Child classes:

Cgiapp2_FrontController
Cgiapp2_FrontController

Class Details

[line 82]
Cgiapp2 - Framework for building reusable web-applications

A PHP5 port of perl's CGI::Application, a framework for building reusable web applications.

SYNOPSIS

  1. // In "WebApp.class.php"...
  2. require_once 'Cgiapp2.class.php';
  3. class WebApp extends Cgiapp2
  4. {
  5. function setup()
  6. {
  7. $this->start_mode('mode1');
  8. $this->mode_param('rm');
  9. $this->run_modes(array(
  10. 'mode1' => 'do_stuff',
  11. 'mode2' => 'do_more_stuff',
  12. 'mode3' => 'do_something_else'
  13. ));
  14. }
  15. function do_stuff() { ... }
  16. function do_more_stuff() { ... }
  17. function do_something_else() { ... }
  18. }
  19.  
  20.  
  21. // In "webapp.php"...
  22. require_once 'WebApp.class.php';
  23. $webapp = new WebApp();
  24. $webapp->run();

For more information, see the tutorials.




Tags:

abstract:  
version:  @release-version@
tutorial:  Introduction


[ Top ]


Class Methods


constructor __construct [line 350]

bool __construct( [array $args = null])

Constructor

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

[ Top ]

method add_callback [line 884]

boolean add_callback( string $hook, string|array $callback, [string|object|null $class = null])

Register a callback for a class instance

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.

The callback should be a valid PHP callback; see PHP callback documentation for more information.

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:

  1. class Cgiapp2_Plugin_MyPlugin
  2. {
  3. function my_setup($cgiapp)
  4. {
  5. // do some stuff...
  6. }
  7. }
  8. Cgiapp2::add_callback('init', array('Cgiapp2_Plugin_MyPlugin', 'my_setup'));

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.




Tags:

static:  
access:  public


Parameters:

string   $hook  
string|array   $callback  
string|object|null   $class  

[ Top ]

method array_to_hash [line 2528]

array array_to_hash( [array $data = null])

Convert an even-itemed array into an associative array

array_to_hash() can be used to turn an even-itemed array into an associative arary, where the even elements become keys for the odd elements. In a nutshell,

  1. array('key1', 'val1', 'key2', 'val2')
becomes
  1. array('key1' => 'val1', 'key2' => 'val2')

UPGRADE NOTE: This method is now static.




Tags:

return:  An associative array
static:  
access:  public


Parameters:

array   $data   The array to convert

[ Top ]

method call_hook [line 1014]

mixed call_hook( string $hook)

Call (execute) a hook

Executes a callback registered at the given hook. The first argument is the hook name. All remaining arguments are passed to the callback at that hook location.

The first argument passed to the hook will always be the current object. Thus, your callback should, at the very least, accept a single argument:

  1. function myHookCallback($cgiapp)
  2. {
  3. }

Some hooks may accept additional arguments (e.g., cgiapp_init(), cgiapp_prerun(), and cgiapp_postrun()); this will be determined by how the hook is called.

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:

access:  public


Parameters:

string   $hook  

[ Top ]

method cap_hash [line 2468]

void cap_hash( [array $rprops = null])

Convert the keys of an associative array to UPPER CASE

UPGRADE NOTE: This method is now static.




Tags:

static:  
access:  public


Parameters:

array   $rprops  

[ Top ]

method carp [line 2568]

void carp( string $message)

Echo a warning to screen

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.

UPGRADE NOTE: This method is now static.




Tags:

static:  
access:  public


Parameters:

string   $message   The warning message to display

[ Top ]

method cgiapp_init [line 607]

void cgiapp_init( array $args, object $cgiapp)

Perform application specific initialization behaviour

cgiapp_init() is called during the $_INSTALLED_CALLBACKS, which is during object instantiation, and prior to calling of the setup() method.

When used, this method provides an optional initialization hook, which allows for customization of the class and all descendents.

The first argument received is the array of arguments sent to the constructor method.

As a callback hook, the second argument expected is an object instance; this may be safely ignored if implementing in a Cgiapp2-based class.

An example of the benefits provided by utilizing this hook is creating a custom "application super-class" from which which all your applications would inherit, instead of Cgiapp2.

Consider the following:

  1. // In MySuperclass.php:
  2. require_once 'Cgiapp2.class.php';
  3. class MySuperclass extends Cgiapp2
  4. {
  5. function cgiapp_init($args, $cgiapp)
  6. {
  7. // Perform some project-specific init behavior
  8. // such as to load settings from a database or file.
  9. }
  10. }
  11.  
  12.  
  13. // In MyApplication.php:
  14. class MyApplication extends MySuperclass
  15. {
  16. function setup { ... }
  17. function teardown { ... }
  18. // The rest of your Cgiapp2-based class follows...
  19. }

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.




Tags:

access:  protected


Parameters:

array   $args   Uses $args sent to constructor
object   $cgiapp   Observed Cgiapp2-based object

[ Top ]

method cgiapp_postrun [line 749]

void cgiapp_postrun( string $body, object $cgiapp)

Execute code following execution of the current run mode method

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.

A potential cgiapp_postrun() method might be implemented as follows:

  1. function cgiapp_postrun($body, $cgiapp)
  2. {
  3. // Enclose output HTML table
  4. $new_output = "<table border=1>";
  5. $new_output .= "<tr><td> Hello, World! </td></tr>";
  6. $new_output .= "<tr><td>". $body ."</td></tr>";
  7. $new_output .= "</table>";
  8.  
  9. # Replace old output with new output
  10. $cgiapp->postrun_body($body);
  11. }

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().




Tags:

access:  protected


Parameters:

string   $body   Content returned by the run mode
object   $cgiapp   Observed Cgiapp2-based object

[ Top ]

method cgiapp_prerun [line 673]

void cgiapp_prerun( string $rm, object $cgiapp)

Perform operations before selected run mode is executed

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.

Consider the following:

  1. // In MySuperclass.php:
  2. class MySuperclass extends Cgiapp2 {
  3. function cgiapp_prerun($rm, $cgiapp) {
  4. // Perform some project-specific init behavior
  5. // such as to implement run mode specific
  6. // authorization functions.
  7. }
  8. }
  9.  
  10.  
  11. // In MyApplication.php:
  12. class MyApplication extends MySuperclass {
  13. function setup()
  14. {
  15. ...
  16. }
  17. function teardown()
  18. {
  19. ...
  20. }
  21. // The rest of your Cgiapp2-based class follows...
  22. }

By using Cgiapp2 and the cgiapp_prerun() method as illustrated, a suite of applications could be designed to share certain characteristics, such as a common authorization scheme.

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.




Tags:

access:  protected


Parameters:

string   $rm   Current selected run mode
object   $cgiapp   Observed Cgiapp2-based object

[ Top ]

method croak [line 2590]

void croak( string $message)

Exit the script with a warning message

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:

string   $message   The warning message to display

[ Top ]

method delete [line 2097]

bool delete( [string $key = null])

Delete an application parameter

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.

Example usage:

  1. $webapp->delete('my_param');




Tags:

access:  public


Parameters:

string   $key   The name of the parameter to delete

[ Top ]

method dump [line 1146]

void dump( )

dump debugging information to the screen

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.

Example:

  1. echo $webapp->dump();




Tags:

access:  public


[ Top ]

method dump_html [line 1177]

void dump_html( )

Dump debugging information as HTML to the screen

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.

Example usage:

  1. $output = $webapp->dump_html();




Tags:

access:  public


[ Top ]

method error_mode [line 1912]

string error_mode( [string $error_mode = null])

Set or retrieve the method to use for handling errors

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:

string   $error_mode  

[ Top ]

method get_current_runmode [line 1890]

string get_current_runmode( )

Display the currently selected run mode

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.

Example usage

  1. $webapp->get_current_runmode();




Tags:

return:  Name of currently selected run mode
access:  public


[ Top ]

method header_props [line 1229]

array header_props( [array $data = null])

Set or return a list of header properties

The header_props() method expects an associative array of valid HTTP header properties. These properties will be passed directly to PHP's header() method. Refer to the PHP header function documentation for exact usage details.

If called multiple times, each set of headers is merged with the list already contained; thus, later headers of the same type will overwrite previous headers.

Headers are not sent until the entire document is ready to be returned.

Example usage:

  1. $webapp->header_props(array(
  2. 'type' => 'image/gif',
  3. 'expires' => '+3d'
  4. ));




Tags:

return:  Array of header properties
access:  public


Parameters:

array   $data   Optional; associative array of header types and values

[ Top ]

method header_type [line 1291]

string header_type( [string $header_type = null])

Set the header type for the current instance of the application

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).

To perform a redirect using Cgiapp2, you would do the following:

  1. function some_redirect_mode()
  2. {
  3. $new_url = "http://site/path/doc.html";
  4. $this->header_type('redirect');
  5. $this->header_props(array('url' => $new_url));
  6. return "Redirecting to $new_url";
  7. }

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.

Example usage:

  1. $webapp->header_type('redirect');




Tags:

access:  public


Parameters:

string   $header_type   Type of header to set: 'none', 'redirect', or 'header' are valid.

[ Top ]

method is_assoc_array [line 2496]

bool is_assoc_array( [array $php_val = null])

Test an array to determine if it is associative

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 method is now static.




Tags:

return:  Success
static:  
access:  public


Parameters:

array   $php_val   A value to test

[ Top ]

method load_tmpl [line 1356]

string load_tmpl( string $tmpl_file)

load_tmpl() - fetch a compiled template

load_tmpl() takes the name of a template file and returns the text generated by filling that template file. It does so by calling the tmpl_fetch hook.

If more than one callback hook has been registered for the tmpl_fetch hook, and each returns a value, than all values will be concatenated with a newline.

Example usage:

  1. // Fetching a template from an object instance:
  2. $text = $webapp->load_tmpl('some.tpl');
  3.  
  4. // Fetching a template from within a class method:
  5. // Common usage is to return the fetched and populated template as
  6. // the value of the run mode:
  7. function someRunMode() {
  8. // Do some processing...
  9. return $this->load_tmpl('some.tpl');
  10. }

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:

  1. require_once 'Cgiapp2.class.php';
  2. require_once 'Cgiapp2/Plugin/Smarty.class.php';




Tags:

return:  Contents of the compiled template
access:  public


Parameters:

string   $tmpl_file   Name of a template to load

[ Top ]

method mode_param [line 1562]

string mode_param( [string|array $mode_param = null])

Set the CGI parameter used to indicate the run mode

mode_param() is generally called in the setup() method. The mode_param() method is used to tell the run() method how to determine the requested run mode. Three possibilities exist:

  1. Use a $CGIAPP_REQUEST parameter (this is the default, and 'rm' is the default value)
  2. Provide a function or a method name to use as a callback
  3. Provide the index in PATH_INFO to use
As noted in (1), above, if mode_param() is not specified by the developer, the method defaults to using the $CGIAPP_REQUEST parameter 'rm'.

In the first case, you would call mode_param() simply as:

  1. $webapp->mode_param('mode');
Note: if the parameter name you specify matches a method or function you've defined, Cgiapp2 will use that function or method instead. This is probably a bug.

Alternatively you can set mode_param() to use a method or function name, as described in (2), above:

  1. $webapp->mode_param('some_method');
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":
  1. function some_method()
  2. {
  3. // Do some stuff here, such as looking at SERVER_NAME or
  4. // PATH_INFO, and return a mode parameter accordingly
  5. return 'run_mode_x';
  6. }

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:

  1. $webapp->mode_param(array('path_info' => 2, 'param' => 'q'));
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:
  1. /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:
  1. /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

[ Top ]

method new_hook [line 958]

boolean new_hook( string $hook, [string|object|null $class = null])

Create a new hook location in which to register callbacks

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.

See call_hook() for information on how hooks are called.




Tags:

static:  
access:  public


Parameters:

string   $hook  
string|object|null   $class  

[ Top ]

method param [line 1991]

mixed param( mixed $data)

Set one or more application parameters; retrieve an application parameter; or retrieve a list of available application parameters

The param() method provides a facility through which you may set application instance properties which are accessible throughout your application.

The param() method may be used in two basic ways. First, you may use it to get or set the value of a parameter:

  1. $webapp->param('scalar_param', '123');
  2. $scalar_param_values = $webapp->param('some_param');
Second, when called in the context of an array, with no parameter name specified, param() returns an array containing all the parameters which currently exist:
  1. $all_params = $webapp->param();
The param() method also allows you to set a bunch of parameters at once by passing in an associative array or array:
  1. $webapp->param(array(
  2. 'key1' => 'val1',
  3. 'key2' => 'val2',
  4. 'key3' => 'val3'
  5. ));
  6.  
  7. // or
  8.  
  9. $webapp->param(array(
  10. 'key1', 'val1',
  11. 'key2', 'val2',
  12. 'key3', 'val3'
  13. ));
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.

Example usage:

  1. $webapp->param('pname', $somevalue);




Tags:

return:  What is returned depends on what is given; see the docs
access:  public


Parameters:

mixed   $data   Optional

[ Top ]

method path_info [line 2380]

array|false path_info( [int $idx = false])

Generate array of PATH_INFO arguments

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:

  1. // path is: /controller/action/article/1/page/2
  2. $page = Cgiapp2::path_info('page');
  3. $article = Cgiapp2::path_info('article');
  4. $action = Cgiapp2::path_info('action');

Returns false if PATH_INFO is unavailable or an index does not exist.

NOTE: Indices begin with 0!




Tags:

static:  
access:  public


Parameters:

int   $idx   Optional index of element to fetch

[ Top ]

method postrun_body [line 1865]

void postrun_body( string $body)

Reset the body contents post-run mode, but prior to returning or echoing

the value. Use this method from cgiapp_postrun() or a postrun callback hook to reset the content returned by the run mode. A typical usage would be to place the content in a sitewide template.




Tags:

access:  public
final:  


Parameters:

string   $body  

[ Top ]

method prerun_mode [line 1829]

string prerun_mode( [string $prerun_mode = null])

Override the run mode that was passed to the application

The prerun_mode() method is an accessor/mutator which can be used within your cgiapp_prerun() method to change the run mode which is about to be executed. For example, consider:

  1. // In WebApp.pm:
  2. require_once 'Cgiapp2.class.php';
  3. class WebApp extends Cgiapp2
  4. {
  5. function cgiapp_prerun($rm)
  6. {
  7. # Get the web user name, if any
  8. $user = $this->s_param('remote_user');
  9.  
  10. # Redirect to login, if necessary
  11. if (!$user) {
  12. $this->prerun_mode('login');
  13. }
  14. }
  15. }
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.

Example usage

  1. $webapp->prerun_mode('new_run_mode');




Tags:

return:  Name of the run mode that will override the requested run mode
access:  public


Parameters:

string   $prerun_mode   String containing name of the new run mode to be used

[ Top ]

method query [line 2342]

array &query( )

Get POST and GET variables and store them for usage

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.

UPGRADE NOTE: This method is now static.




Tags:

return:  Reference to $CGIAPP_REQUEST
static:  
access:  public


[ Top ]

method run [line 434]

void run( )

Run the application

The run() method is called upon your Application object, from your Instance Script. When called, it executes the functionality in your Application Class.

  1. $webapp = new WebApp();
  2. $webapp->run();

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:

access:  public


[ Top ]

method run_modes [line 1698]

array run_modes( [array $data = null], [bool $flag = null])

Define or return a list of the valid run modes for the application

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):

  1. 'mode_name_by_ref' => &mode_function()
  2. '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:
  1. return $this->load_tmpl('some_template.tpl');
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:

  1. $webapp->run_modes(array('mode1', 'method1, 'mode2', 'method2'));
This is the same as the following, via an associative array:
  1. $webapp->run_modes(array(
  2. 'mode1' => 'method1',
  3. 'mode2' => 'method2'
  4. ));

Finally, you can also pass an array plus an optional flag set to true to. This will assign each element of the array to the correspondingly named method as its run mode:

  1. // Sets run mode 'mode1' to point to method 'mode1', and so on
  2. $webapp->run_modes(array('mode1', 'mode2'), true);

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.

Example usage:

  1. $webapp->run_modes(array(
  2. 'mode1' => 'some_sub_by_name',
  3. 'mode2' => &some_other_sub_by_ref()
  4. ));




Tags:

return:  Associative array of run mode => method mappings
access:  public


Parameters:

array   $data   (Associative) array of run mode => method mappings
bool   $flag   Optional flag indicating that $data is a regular array and that each element refers to a corresponding class method.

[ Top ]

method setup [line 793]

void setup( )

Setup the application's environment

This method is called by the inherited constructor method. The setup() method should be used to define the following property/methods:

  • mode_param() - set the name of the run mode CGI param.
  • start_mode() - text scalar containing the default run mode.
  • run_modes() - hash table containing mode => function mappings.
  • tmpl_path() - text scalar containing path to template files.
Your setup() method may call any of the instance methods of your application. This function is a good place to define properties specific to your application via the param() method.

Your setup() method might be implemented something like this:

  1. function setup()
  2. {
  3. $this->tmpl_path('/path/to/my/templates/');
  4. $this->start_mode('putform');
  5. $this->run_modes(array(
  6. 'putform' => 'my_putform_func',
  7. 'postdata' => 'my_data_func'
  8. ));
  9. $this->param('myprop1');
  10. $this->param('myprop2', 'prop2value');
  11. $this->param('myprop3', array('p3v1', 'p3v2', 'p3v3'));
  12. }




Tags:

access:  protected
abstract:  


Overridden in child classes as:

Cgiapp2_FrontController::setup()
Setup

[ Top ]

method start_mode [line 1758]

string start_mode( [string $start_mode = null])

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.

Example usage:

  1. $webapp->start_mode('mode1');




Tags:

return:  Name of the default run mode
access:  public


Parameters:

string   $start_mode   Optional; the name of the default run mode

[ Top ]

method s_delete [line 2249]

void s_delete( [string $key = null])

Remove a session variable

Like delete(), s_delete() deletes a session parameter.




Tags:

access:  public


Parameters:

string   $key   The name of the session parameter to delete

[ Top ]

method s_param [line 2159]

mixed s_param( mixed $data)

Add, list, or retrieve session 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.
  • If more than two values are passed, emit a warning.




Tags:

return:  What is returned depends on what is given; see the docs
access:  public


Parameters:

mixed   $data   Optional

[ Top ]

method teardown [line 814]

void teardown( object $cgiapp)

Perform cleanup after running the application

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:

object   $cgiapp   Observed Cgiapp2-based object

[ Top ]

method tmpl_assign [line 1402]

void tmpl_assign( mixed $data, mixed $var,$val)

Assign content to a template

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.

Example usage:

  1. // Assigning values via an object instance
  2. $webapp->tmpl_assign('var_name', 'value');
  3.  
  4. // From within the class:
  5. function someRunMode()
  6. {
  7. // Assign a single value
  8. $this->tmpl-assign('var_name', $value);
  9.  
  10. // Assign several values
  11. $this->tmpl_assign(array(
  12. 'var1' => $value1,
  13. 'var2' => $value2
  14. ));

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:

  1. require_once 'Cgiapp2.class.php';
  2. require_once 'Cgiapp2/Plugin/Smarty.class.php';




Tags:

access:  public


Parameters:

mixed   $data   An associative array of var => val pairs to assign to the template
mixed   $var,$val   Assign $val to $var in the template

[ Top ]

method tmpl_path [line 1444]

string tmpl_path( [string $tmpl_path = null], [array $extra_params = null])

Set template path and initialize template object

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.

See Cgiapp2_Plugin_Smarty::init() for an example of a tmpl_path hook in practice.

Example usage:

  1. $webapp->tmpl_path('/path/to/some/templates/');

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:

  1. require_once 'Cgiapp2.class.php';
  2. require_once 'Cgiapp2/Plugin/Smarty.class.php';




Tags:

return:  Template path
access:  public


Parameters:

string   $tmpl_path   Optional; path to base template directory
array   $extra_params   Optional; associative array of arguments to pass to template engine constructor

[ Top ]

method _class_hierarchy [line 1115]

void _class_hierarchy( string|object $class)

Get class hierarchy for a class name or object

Determines the class hierarchy for a class, as an ordered array (current class to eldest grandparent). Sets $_CALLBACK_CLASSES.




Tags:

access:  protected


Parameters:

string|object   $class  

[ Top ]

method _send_headers [line 2285]

void _send_headers( )

_send_headers() - send HTTP headers before displaying content



Tags:

access:  protected


[ Top ]


Documentation generated on Sat, 03 Jun 2006 10:48:39 -0400 by phpDocumentor 1.3.0RC5