Framework base class: swlib
Framework base class: swlib
The basic tasks that I want to have included in my scripts are collected in one frame
library, the swlib
. This class manages the autoloading for me and initializes error
exception handling, output buffering, tracer and session. Other functions are the
import/export of persistent variables, as well as a safe script shutdown (means that is
registers static shutdown functions that cause to print the output and trace output
even if the script was stopped after an error/uncaught exception or the die()
function - however, if the PHP parser aborts, then there is no way of catching this
with no shutdown handling). The class requires the (on this page published) classes
EException
, OutputBuffer
, Tracer
and Session
.
Funktionalitäten, die ich in jedem PHP-Skript dabeihaben möchte, habe ich in einem
Bibliothek-Manager eingebunden - der swlib
. Diese Klasse organisiert das Autoloading von
anderen Klassen für mich und initialisiert Exception-Behandlung, Ausgabepufferung, Tracer
und Session. Weitere Funktionen sind Export/Import von persistenten Variablen, sowie
Shutdown-Absicherung (auch wenn das Skript durch einen Fehler/Exception oder Verwendung
der die()
-Funktion abbricht wird die vorhandene Ausgabe und die Tracer-Ausgabe angezeigt -
jedoch muss dazu gesagt werden, dass wenn der PHP Parser einen Fehler wirft man dies
durch nichts in der Welt abfangen kann). Die swlib
benötigt die (auch auf diesen Seiten
veröffentlichten) Klassen EException
, OutputBuffer
, Tracer
und Session
.
Sample source code
Anwendungsbeispiel
<?php
include_once('swlib/swlib.class.php');
//
// Initialises Localizer, Tracer and autoloader.
// This is done automatically when you include the file.
//
// sw\swlib::start();
//
//
// Terminates Session, OutputBuffer, Localizer, Tracer.
// You don't need to call this - it is done on shutdown
//
// sw\swlib::stop();
//
//
// Example for configuring the class. Normally this is not required neither.
//
// sw\swlib::config(array(
// 'locale-char-type' => 'de-de'
// ));
//
// This that are set up now:
//
// - Localizer
// - Autoload for all library classes
// - If CLI, the output buffer is purged
// - Magic quotes are removed (if on)
// - global HTTP_*****_VARS are removed
// - Errors are converted to Exceptions
// - Uncaught exception handler installed
// - Tracer initialized
//
// Returns true if running from command line
$is_cli = sw\swlib::isCLIMode();
// lets throw something
trigger_error("WE HAVE AN ERROR", E_USER_ERROR);
// This will be caught, see output.
Output of the shell program
Ausgabe des Shellprogramms
Uncaught Exception: 'WE HAVE AN ERROR' in .../ex/swlib.t.php[44]
sw\EException::errorCallback(256,"WE HAVE AN ERROR","/tmp/ex/swlib.t.php",44,array(10))
/tmp/ex/swlib.t.php@44 ::trigger_error("WE HAVE AN ERROR",256)
Class source code
Klassen-Quelltext
<?php
/**
* SW PHP Library Core class. Organizes autoloading, settings import/export,
* and initializes all classes/modules to enable the features:
*
* - Exception handling
* - Tracing
* - Session management
* - Output bufferung
* - Update check of the whole package de.atwillys.sw.php.swLib
*
* Furthermore, it normalizes the GET,POST, etc input according to magic quotes
* (which are ALL removed).
*
* @gpackage de.atwillys.sw.php.swLib
* @author Stefan Wilhelm
* @copyright Stefan Wilhelm, 2005-2010
* @license GPL
* @version 1.0
* @uses Tracer
* @uses EException
* @uses OutputBuffer
* @uses Session
*/
namespace sw;
if (!class_exists(__NAMESPACE__ . '\\swlib', false)) {
// library core includes
require_once("core/EException.class.php");
require_once("core/Tracer.class.php");
require_once("core/OutputBuffer.class.php");
require_once("core/Localizer.class.php");
require_once("core/LException.class.php");
require_once("core/Session.class.php");
final class swlib {
/**
* Library configuration. Sets the specified config settings (merges
* with the existing). Returns the actual configuration after the
* new array has been merged to the defaults/previous settings.
* @param array $config
* @return array
*/
public static final function config($config = array()) {
static $conf = array();
if (!is_array($config)) {
throw new LException('swlib config is no array');
} else {
$conf = array_merge($conf, $config);
if (isset($config['locale-char-type'])) {
@setlocale(LC_CTYPE, $config['locale-char-type']);
}
}
return $conf;
}
/**
* Library startup, optional with setting the config. See the private
* $self::config variable for information about whar can be configured.
* @return void
*/
public static final function start() {
static $initialized = false;
if ($initialized) { return; }
$initialized = true;
if(!defined('PHP_MAJOR_VERSION') || (PHP_MAJOR_VERSION < 5) && (PHP_MINOR_VERSION < 3)) {
trigger_error("The swlib requires PHP 5.3 or higher (skipping initialization). Your version is " . phpversion() . "\n\n", E_USER_WARNING);
return;
}
@spl_autoload_register('\\' . __CLASS__ . '::autoload', true, false);
@setlocale(LC_CTYPE, 'en_US.UTF-8');
Localizer::start();
if (self::isCLIMode()) {
OutputBuffer::purge();
} else {
@header_remove('X-Powered-By');
OutputBuffer::start();
foreach (array('HTTP_ENV_VARS', 'HTTP_POST_VARS', 'HTTP_GET_VARS', 'HTTP_COOKIE_VARS', 'HTTP_SERVER_VARS', 'HTTP_POST_FILES', 'HTTP_SESSION_VARS') as $var) {
if (isset($GLOBALS[$var])) {
unset($GLOBALS[$var]);
}
}
if (function_exists('get_magic_quotes_gpc') && get_magic_quotes_gpc()) {
if (!function_exists('stripslashes_r')) {
function stripslashes_r($v) {
if (!is_array($v)) {
return isset($v) ? stripslashes($v) : null;
} else {
$a = array();
foreach ($v as $k => $t) {
$a[stripslashes($k)] = stripslashes_r($t);
}
return $a;
}
}
}
foreach (array($_GET, $_POST, $_FILES, $_COOKIE, $_REQUEST) as $k => $v) {
$GLOBALS[$k] = stripslashes_r($v);
}
}
}
EException::enable();
Tracer::start();
@register_shutdown_function(array(__CLASS__, "stop"), "inside");
}
/**
* Stops the library and flushes the output
* buffers. Do not call this method, it will
* be automatically called when the script
* stops. (using register_shutdown_function())
*/
public static final function stop() {
Session::stop();
OutputBuffer::abort();
Localizer::stop();
Tracer::stop();
}
/**
* Returns if PHP is running in CLI mode
* @return bool
*/
public static function isCLIMode() {
return strtolower(php_sapi_name()) == 'cli';
}
/**
* Returns the tmp path
* @return string
*/
public static final function getTmpPath() {
return sys_get_temp_dir();
}
/**
* Autoloads a class
* @param string $class
*/
public static final function autoload($class) {
static $autoloadableClasses = array();
$class = trim($class, "\\ ");
if (class_exists($class, false) || (stripos($class, "sw\\") !== 0)) {
return;
}
if (empty($autoloadableClasses)) {
require_once('sys/FileSystem.class.php');
foreach (FileSystem::find(dirname(__FILE__), '*.class.php') as $file) {
$cls = strtolower(__NAMESPACE__ . '\\' . basename($file, '.class.php'));
$autoloadableClasses[$cls] = $file;
}
}
$class = strtolower($class);
if (isset($autoloadableClasses[$class])) {
require_once($autoloadableClasses[$class]);
}
}
}
swlib::start();
} // class exist swlib