- Home
- Categorie
- Coding e Sistemistica
- PHP
- Consiglio PDOSingleton
-
Consiglio PDOSingleton
Ciao ragazzi,
oggi stavo partorendo una classe Factory per PDO capace di implementare il Sigleton anche su tutti i metodi della classe PDO passando poi l'oggetto PDO
creato alla classe PDOStatement.Vorrei innanzi tutto sapere cosa ne pensate del codice della classe e del interfaccia e in secondo luogo se secondo la vostra esperienza gli attributi,
ad esempio la gestione delle eccezione, è meglio metterli prima di ritornare
l'stanza della classe al interno del Singleton (dove li ho commentati adesso)
o dopo avere creato l'istanza con il comando:[php]
$objPDO = PDOFactory::getInstance();
[/php]P.S. I parametri che formano il DSN li prendo per comodità da un namespace incluso nella index.php
//->class.IPDOFactory.php
[php]
<?php/**
*-
ProjectName : FastCMS
-
ProjectAuthor : Adriano Giovannini
-
ProjectMail : ...
-
ProjectFile : class_IPDOFactory.php
-
ProjectPackage : library\PDOFactory
-
ProjectLicense : GPL V3. Se license\<yourLanguage>\license.tx
-
for more details
*/
interface IPDOFactory
{/** * * Singleton Method * * @return bool $_blSingletonInstance * */ public static function getInstance(); /** * * Initiate a transaction * * @return bool * */ public function beginTransaction(); /** * * Commit a transaction * * @return bool * */ public function commit(); /** * * Fetch the state of SQL associated whit the last operation on the database * * @return string * */ public function errorCode(); /** * * Fetch the extended error information associated with the last operation on * database * * @return array * */ public function errorInfo(); /** * * Execute SQL statement and return the number of affected row * * @param string $PDOStatement * */ public function exec($PDOStatement); /** * * Retrieve a database connection attribute * * @param int $PDOAttribute * * @return int * */ public function getAttribute($PDOAttribute); /** * * Return an array of available PDO Drivers * * @return array * */ public function getAvailableDriver(); /** * * Return the ID of the last inserted row * * @param string $LastInsertIdName * * @return string * */ public function lastInsertId($LastInsertIdName); /** * * Prepare a statemet for execution and return a PDOStatement object * * @param string $PDOStatement * @param array $PDODriverOptions * * @return $PDOStatement * */ public function prepare($PDOStatement, $PDODriverOptions = false); /** * * Execute a SQL Statement and returning result set a PDOStatement object * * @param string $PDOStatement * * @return object $PDOStatement * */ public function query($PDOStatement); /** * * Execute Query and return all rows in assoc array * * @param string $PDOStatement * * @return array * */ public function queryFetchAllAssoc($PDOStatement); /** * * Execute Query and return one rows in assoc array * * @param string $PDOStatement * * @return array * */ public function queryFetchRowAssoc($PDOStatement); /** * * Execute Query and select one column only * * @param string $PDOStatement * * @return mixed * */ public function queryFetchColAssoc($PDOStatement); /** * * Quote a string for prevent sql injection * * @param string $InputString * @param int $ParameterType * * @return string * */ public function quote($InputString, $ParameterType); /** * * Rolls back a transaction * * @return bool * */ public function rollBack(); /** * * Set attribute * * @param int $PDOAttribute * @param mixed $PDOAttributeValue * * @return bool * */ public function setAttribute($PDOAttribute, $PDOAttributeValue);
}
?>
[/php]//-> class_PDOFactory.php
[php]
<?phprequire_once 'class_IPDOFactory.php';
/**
*-
ProjectName : FastCMS
-
ProjectAuthor : Adriano Giovannini
-
ProjectMail : ...
-
ProjectFile : class_PDOFactory.php
-
ProjectPackage : library\PDOFactory
-
ProjectLicense : GPL V3. Se license\<yourLanguage>\license.tx
-
for more details
*/
class PDOFactory implements IPDOFactory
{/** * * PDOConnection params * * @param strind $_strDSN * @param strung $_strUsernme * @param string $_strPassword * */ private static $_strDSN = PDONS\DSN; private static $_strUsername = PDONS\USERNAME; private static $_strPassword = PDONS\PASSWORD; /** * * Singleton Instance * * @param bool * */ private static $_blSingletonInstance = null; /** * * Preventi construct and cloning creation * */ private function __construct() { trigger_error ( "Construct is not allowed" . E_USER_ERROR ); } private function __clone() { trigger_error ( "Clone is not allowed" . E_USER_ERROR ); } /** * * Singleton Method * * @return bool $_blSingletonInstance * */ public static function getInstance() { try { if ( self::$_blSingletonInstance == null ) { self::$_blSingletonInstance = new PDO ( self::$_strDSN, self::$_strUsername, self::$_strPassword, array(PDO::ATTR_PERSISTENT => true) ); } // $objPDO->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); return self::$_blSingletonInstance; } catch ( PDOException $e ) { die ( "Error: " . $e->getMessage() ); } } /** * * Initiate a transaction * * @return bool * */ public function beginTransaction() { return self::$_blSingletonInstance->beginTransection(); } /** * * Commit a transaction * * @return bool * */ public function commit() { return self::$_blSingletonInstance->commit(); } /** * * Fetch the state of SQL associated whit the last operation on the database * * @return string * */ public function errorCode() { return self::$_blSingletonInstance->errorCode(); } /** * * Fetch the extended error information associated with the last operation on * database * * @return array * */ public function errorInfo() { return self::$_blSingletonInstance->errorInfo(); } /** * * Execute SQL statement and return the number of affected row * * @param string $PDOStatement * */ public function exec($PDOStatement) { return self::$_blSingletonInstance->exec($PDOStatement); } /** * * Retrieve a database connection attribute * * @param int $PDOAttribute * * @return int * */ public function getAttribute($PDOAttribute) { return self::$_blSingletonInstance->getAttribute($PDOAttribute); } /** * * Return an array of available PDO Drivers * * @return array * */ public function getAvailableDriver() { return self::$_blSingletonInstance->getAvailableDriver(); } /** * * Return the ID of the last inserted row * * @param string $LastInsertIdName * * @return string * */ public function lastInsertId($LastInsertIdName) { return self::$_blSingletonInstance->lastInsertId($LastInsertIdName); } /** * * Prepare a statemet for execution and return a PDOStatement object * * @param string $PDOStatement * @param array $PDODriverOptions * * @return $PDOStatement * */ public function prepare($PDOStatement, $PDODriverOptions = false) { if (!$PDODriverOptions) { $PDODriverOptions = array(); } return self::$_blSingletonInstance->prepare($PDOStatement, $PDODriverOptions); } /** * * Execute a SQL Statement and returning result set a PDOStatement object * * @param string $PDOStatement * * @return object $PDOStatement * */ public function query($PDOStatement) { return self::$_blSingletonInstance->query($PDOStatement); } /** * * Execute Query and return all rows in assoc array * * @param string $PDOStatement * * @return array * */ public function queryFetchAllAssoc($PDOStatement) { return self::$_blSingletonInstance->query($PDOStatement)->fetchAll(PDO::FETCH_ASSOC); } /** * * Execute Query and return one rows in assoc array * * @param string $PDOStatement * * @return array * */ public function queryFetchRowAssoc($PDOStatement) { return self::$_blSingletonInstance->query($PDOStatement)->fetch(PDO::FETCH_ASSOC); } /** * * Execute Query and select one column only * * @param string $PDOStatement * * @return mixed * */ public function queryFetchColAssoc($PDOStatement) { return self::$_blSingletonInstance->query($PDOStatement)->fetchColumn(); } /** * * Quote a string for prevent sql injection * * @param string $InputString * @param int $ParameterType * * @return string * */ public function quote($InputString, $ParameterType) { return self::$_blSingletonInstance->quote($InputString, $ParameterType); } /** * * Rolls back a transaction * * @return bool * */ public function rollBack() { return self::$_blSingletonInstance->rollBack(); } /** * * Set attribute * * @param int $PDOAttribute * @param mixed $PDOAttributeValue * * @return bool * */ public function setAttribute($PDOAttribute, $PDOAttributeValue) { return self::$_blSingletonInstance->setAttribute($PDOAttribue, $PDOAttributeValue); }
}
?>
[/php]//-> class_PDOFactoryException.php
[php]
<?php/**
*-
ProjectMail : ...
-
ProjectFile : class_PDOFactoryException.php
-
ProjectPackage : library\PDOFactory
-
ProjectLicense : GPL V3. Se license\<yourLanguage>\license.tx
-
for more details
*/
class PDOFactoryException
{public static function PDOExceptionDisplay ( $objPDO, $e, $objStatement) { /** * Static method */ echo "An error occurred connecting: " . $e->getMessage() . "<br />"; /** * List PDOErrorInfo */ list ($intErrorCode1, $intErrorCode2, $strErrorInfo) = $objPDO->errorInfo(); print "PDOExceptionError<br />"; print "Error Code: '$intErrorCode1'<br />"; print "Driver Code: '$intErrorCode2'<br />"; print "Error Info: '$strErrorInfo'<br />"; /** * Check error for PDOStatement class */ if ($objStatement instanceof PDOStatement) { /** * Print PDOStatement error */ list ($intErrorCode1, $intErrorCode2, $strErrorInfo) = $objStatement->errorInfo(); print "PDOStatementExceptoinError<br />"; print "Error Code: '$intErrorCode1'<br />"; print "Driver Code: '$intErrorCode2'<br />"; print "Error Info: '$strErrorInfo'<br />"; } exit(); }
}
?>
[/php]//-> PDONamespace.php
[php]
<?phpnamespace PDONS
{const DSN = 'mysql:host=localhost;charset=utf8;dbname=forum'; const USERNAME = 'tuauser'; const PASSWORD = 'tuapass';
}
?>
[/php]//-> index.php
[php]
<?phprequire_once 'PDONamespace.php';
require_once 'library\PDOFactory\class_PDOFactory.php';try
{$objPDO = PDOFactory::getInstance(); $objPDO->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); //-> Inizio test PDO $i = 0; $strQuery = "SELECT * FROM user"; $objStatement = $objPDO->prepare($strQuery); $objStatement->execute(); // Rimuovere dai metodi della classe singleton le costanti nel fetch while ($arRow = $objStatement->fetch(PDO::FETCH_ASSOC)) { print "Row $i"; foreach ($arRow as $key => $value) { print " - Column $key, value $value<br />"; } $i++; } //-> PDO Test
} catch ( PDOException $e ) {
require_once 'library\PDOFactory\class_PDOFactoryException.php'; PDOFactoryException::PDOExceptionDisplay ($objPDO, $e, $objStatement);
} catch ( Excpetion $e ) {
die ( "An error occurred: " . $e->getMessage() );
}
?>
[/php]Che ne pensate ?
-