Classe PDOFactory

bismark2005

Utente Attivo
8 Mar 2011
70
0
0
Qualcuno potrebbe spiegarmi cosa fa questa classe:

Codice:
<?php
class PDOfactory{
    public static function GetPDO($strDNS,$strUser,$strPass, $arParms){
        $strKey=md5(serialize(array($strDNS,$strUser,$strPass,$arParam)));
        if(!($GLOBALS["PDOS"][$strKey] istanceof PDO)){
            $GLOBALS["PDOS"][$STRkEY]=new PDO ($strDNS,$strUser,$strPass,$arParm);
        }
        return ($GLOBALS["PDOS"][$strKey]);
        
    }
    
}
?>
 
Sistemata qua e là:
PHP:
class PdoFactory
{
    static private $instances = array();

    public static function getPdo($dsn, $user, $pass, array $params = array())
    {
        $key = md5(serialize($dsn, $user, $pass, $params));

        if (!isset(self::$instances[$key])) {
            self::$instances[$key] = new PDO($dsn, $user, $pass, $params);
        }

        return self::$instances[$key];
    }
}
Serve per gestire diverse istanze di PDO con il design pattern Singleton.

Tuttavia la trovo un po' scomoda, perché ogni volta devi passare tutti i parametri per fare in modo che funzioni:
PHP:
// crea una connessione PDO se non esiste, altrimenti restituisce quella esistente
$db = PdoFactory::getPdo('mysql:host=localhost;dbname=test', 'root', 'password');
 
Perché non usare una chiave scelta dall'utente?

PHP:
class PdoFactory 
{ 
    static private $instances = array(); 

    public static function getPdo($key, $dsn=false, $user=false, $pass=false, $params = array()) 
    { 
        if (!isset(self::$instances[$key])) {
            try{
            self::$instances[$key] = new PDO($dsn, $user, $pass, $params); 
            }catch(PDOException $e){
                echo $e->getMessage();
            }
        } 

        return self::$instances[$key]; 
    } 
}  


//esempi

$pdo = PdoFactory::getPdo('my_key','mysql:host=localhost;dbname=test','root','password1');
$pdo2 = PdoFactory::getPdo('my_key');
$pdo3 = PdoFactory::getPdo('my_key2','mysql:host=localhost;dbname=prova','root','password2');

var_dump($pdo);
var_dump($pdo2);
var_dump($pdo3);
 
Aspettate ragazzi, sennò mi incasinate le idee!! Cosa significa md5 e serialize?
md5 genera un hash alfanumerico di 32 caratteri e serialize genera una stringa serializzata(byte-stream) della variabile passata, che sia un oggetto, un array, una stringa o altro
 
Ok e perchè nel codice si scrive così:

self::$instances[$key] = new PDO($dsn, $user, $pass, $params);

e non così:

self::$instances = new PDO($dsn, $user, $pass, $params);

[$key] quanto vale?
 
Ok e perchè nel codice si scrive così:

self::$instances[$key] = new PDO($dsn, $user, $pass, $params);

e non così:

self::$instances = new PDO($dsn, $user, $pass, $params);

[$key] quanto vale?
Semplice, perché l'attributo $instances è un array che dovrebbe contenere secondo la logica di questo script ogni istanza diversa di pdo identificata con una chiave univoca.
 
Codice:
class User {

        private $ID;
        private $objPDO;
        private $strTableName;
        private $arRelationMap;
        private $blForDeletion;

        private $FirstName;
        private $LastName;
        private $Username;
        private $Password;
        private $EmailAddress;

        private $DateLastLogin;
        private $TimeLastLogin;
        private $DateAccountCreated;
        private $TimeAccountCreated;

        public function __construct(PDO $objPDO, $id = NULL) {
                $this->strTableName = "system_user";
                $this->arRelationMap = array(
                        "id" => "ID",
                        "first_name" => "FirstName",
                        "last_name" => "LastName",
                        "username" => "Username",
                        "md5_pw" => "Password",
                        "email_address" => "EmailAddress",
                        "date_last_login" => "DateLastLogin",
                        "time_last_login" => "TimeLastLogin",
                        "date_account_created" => "DateAccountCreated",
                        "time_account_created" => "TimeAccountCreated");
                $this->objPDO = $objPDO;
                if (isset($id)) {
                        $this->ID = $id;
                        $strQuery = "SELECT ";
                        foreach ($this->arRelationMap as $key => $value) {
                                $strQuery .= "\"" . $key . "\",";
                        }
                        $strQuery = substr($strQuery, 0, strlen($strQuery)-1);--------------------------->Da qui
                        $strQuery .= " FROM " . $this->strTableName . " WHERE
                                     \"id\" = :eid";
                        $objStatement = $this->objPDO->prepare($strQuery);
                        $objStatement->bindParam(':eid', $this->ID, 
                                                 PDO::PARAM_INT);
                        $objStatement->execute();
                        $arRow = $objStatement->fetch(PDO::FETCH_ASSOC);
                        foreach($arRow as $key => $value) {
                                $strMember = $this->arRelationMap[$key];
                                if (property_exists($this, $strMember)) {
                                        if (is_numeric($value)) {
                                                eval('$this->' . $strMember . ' = 
                                                     ' . $value . ';');
                                        } else {
                                                eval('$this->' . $strMember . ' =
                                                     "' . $value . '";');
                                        };
                                };
                        };
                };
        }

Il pezzo di codice che inizia da $strQuery = substr($strQuery, 0, strlen($strQuery)-1); a seguire non mi è chiaro. Qualcuno potrebbe illuminarmi?

Ps: Ma perchè a me nn colora il codice?
 
Codice:
class User {

        private $ID;
        private $objPDO;
        private $strTableName;
        private $arRelationMap;
        private $blForDeletion;

        private $FirstName;
        private $LastName;
        private $Username;
        private $Password;
        private $EmailAddress;

        private $DateLastLogin;
        private $TimeLastLogin;
        private $DateAccountCreated;
        private $TimeAccountCreated;

        public function __construct(PDO $objPDO, $id = NULL) {
                $this->strTableName = "system_user";
                $this->arRelationMap = array(
                        "id" => "ID",
                        "first_name" => "FirstName",
                        "last_name" => "LastName",
                        "username" => "Username",
                        "md5_pw" => "Password",
                        "email_address" => "EmailAddress",
                        "date_last_login" => "DateLastLogin",
                        "time_last_login" => "TimeLastLogin",
                        "date_account_created" => "DateAccountCreated",
                        "time_account_created" => "TimeAccountCreated");
                $this->objPDO = $objPDO;
                if (isset($id)) {
                        $this->ID = $id;
                        $strQuery = "SELECT ";
                        foreach ($this->arRelationMap as $key => $value) {
                                $strQuery .= "\"" . $key . "\",";
                        }
                        $strQuery = substr($strQuery, 0, strlen($strQuery)-1);--------------------------->Da qui
                        $strQuery .= " FROM " . $this->strTableName . " WHERE
                                     \"id\" = :eid";
                        $objStatement = $this->objPDO->prepare($strQuery);
                        $objStatement->bindParam(':eid', $this->ID, 
                                                 PDO::PARAM_INT);
                        $objStatement->execute();
                        $arRow = $objStatement->fetch(PDO::FETCH_ASSOC);
                        foreach($arRow as $key => $value) {
                                $strMember = $this->arRelationMap[$key];
                                if (property_exists($this, $strMember)) {
                                        if (is_numeric($value)) {
                                                eval('$this->' . $strMember . ' = 
                                                     ' . $value . ';');
                                        } else {
                                                eval('$this->' . $strMember . ' =
                                                     "' . $value . '";');
                                        };
                                };
                        };
                };
        }

Il pezzo di codice che inizia da $strQuery = substr($strQuery, 0, strlen($strQuery)-1); a seguire non mi è chiaro. Qualcuno potrebbe illuminarmi?

Ps: Ma perchè a me nn colora il codice?
Metti il codice fra i tag [ php ] , comunque in quel punto concatena tutti gli elementi da prendere dalla tabella e poi togli l'ultima virgola

Se devo dare un mio parere non mi piace questa classe, poco dinamica e con troppe proprietà.

Inoltre quel foreach e il substr sono riassumibili in una linea, e non è necessario mettere le virgolette per i campi di una tabella
PHP:
$strQuery = "SELECT ".join(',',array_keys($this->arRelationMap));

Senza contare l'inutile eval alla fine dato che è possibile fare cosi
PHP:
$this->{$strMember}= $value;
 
Il codice del manuale non è scritto molto bene, prolisso e confuso. Certo è che spendere circa 50 euro per un manuale del genere è uno spreco. Non capisco gli autori. Se scrivere un libro non è per voi statevene a casa!!
 
Ma davvero quel libro è "PHP 6. Guida per lo sviluppatore"? A me ne avevano parlato bene, ma a quanto pare devo ricredermi...


Si è proprio quel manuale. Io non sono in grado di giudicare codice altrui, ma se voi dite così mi fido. Però devo continuare con questo manuale perchè è l'unico in ita a trattare argomenti avanzati in Php
 

Discussioni simili