Salta al contenuto
  • CATEGORIES
  • La Community Connect.gt
  • Presentati alla Community
  • News Ufficiali da Connect.gt
  • Internet News
  • A Scuola Di
  • Digital Marketing
  • Intelligenza Artificiale
  • SEO & GEO
  • Web Marketing e Content
  • Google Analytics e Web Analytics
  • Google Ads & Advertising
  • YouTube
  • TikTok, Instagram e altri Social
  • Google Adsense, Affiliazioni e Guadagno
  • E-Commerce
  • Coding e Sistemistica
  • Help Center: consigli per il tuo progetto
  • Hosting e Cloud
  • Coding
  • CMS & Piattaforme Self-Hosted
  • Annunci e Collaborazioni
  • Annunci Vendita e Acquisto: Pubblicità, Domini, Link e altro
  • Collaborazioni WEB e Lavoro: offro e cerco
  • Impresa, Fisco e Leggi
  • Consulenza Legale e Professioni Web
  • Consulenza Fiscale, Imprese, Startup e P.Iva
  • Gli Off Topic
  • PC, Smartphone e altri Hardware
  • Tutti i Software
  • GT Fetish Cafè
  • Discussioni
  • 0 Non letti 0
  • Recenti
  • Hashtag
  • Popolare
  • Utenti
  • Privacy
  • Termini e condizioni
  • © 2026 Search On Media Group S.r.l.
Collassa
Connect.gt
Il network Search On
Connect.gt WMF AI Festival Accademia Advanced SEO Tool AgentCy Social Media Strategies Search Tech
Registrati Accedi
Connect.gt
Stream Interest Categorie Hashtag
  1. La community italiana di SEO, marketing digitale e AI
  2. Categorie
  3. Coding e Sistemistica
  4. Coding
  5. Consiglio PDOSingleton

Consiglio PDOSingleton

Pianificato Fissato Bloccato Spostato Coding
1 Post 1 Autori 694 Visualizzazioni 1 Seguito
  • Da Vecchi a Nuovi
  • Da Nuovi a Vecchi
  • Più Voti
Rispondi
  • Risposta alla discussione
Effettua l'accesso per rispondere
Questa discussione è stata eliminata. Solo gli utenti con diritti di gestione possono vederla.
  • A
    A
    aragonesse
    scritto su ultima modifica di
    User 0
    #1
    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:

    $objPDO = PDOFactory::getInstance();
    

    P.S. I parametri che formano il DSN li prendo per comodità da un namespace incluso nella index.php

    //->class.IPDOFactory.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);
        
    }
    
    ?>
    

    //-> class_PDOFactory.php

    <?php
    
    require_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);
            
        }
    
    }
    
    ?>
    

    //-> class_PDOFactoryException.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();
                    
        }
        
    }
    
    ?>
    

    //-> PDONamespace.php

    <?php
    
    namespace PDONS
    {
    
        const DSN         = 'mysql:host=localhost;charset=utf8;dbname=forum';
        const USERNAME      = 'tuauser';
        const PASSWORD      = 'tuapass';
        
    }
    
    ?>
    

    //-> index.php

    <?php
    
    require_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() );
        
    }
    
    
    ?>
    

    Che ne pensate ?

    1 Risposta Ultima Risposta
    Miglior risposta 0
    0

    Ciao! Sembra che tu sia interessato a questa conversazione, ma non hai ancora un account.

    Stanco di dover scorrere gli stessi post a ogni visita? Quando registri un account, tornerai sempre esattamente dove eri rimasto e potrai scegliere di essere avvisato delle nuove risposte (tramite email o notifica push). Potrai anche salvare segnalibri e votare i post per mostrare il tuo apprezzamento agli altri membri della comunità.

    Con il tuo contributo, questo post potrebbe essere ancora migliore 💗

    Registrati Accedi
    Rispondi
    • Risposta alla discussione
    Effettua l'accesso per rispondere
    • Da Vecchi a Nuovi
    • Da Nuovi a Vecchi
    • Più Voti


    • Accedi

    • Non hai un account? Registrati

    • Accedi o registrati per effettuare la ricerca.
    • Primo post
      Ultimo post
    Home Accedi Registrati
    Menu
    • CATEGORIES
    • La Community Connect.gt
    • Presentati alla Community
    • News Ufficiali da Connect.gt
    • Internet News
    • A Scuola Di
    • Digital Marketing
    • Intelligenza Artificiale
    • SEO & GEO
    • Web Marketing e Content
    • Google Analytics e Web Analytics
    • Google Ads & Advertising
    • YouTube
    • TikTok, Instagram e altri Social
    • Google Adsense, Affiliazioni e Guadagno
    • E-Commerce
    • Coding e Sistemistica
    • Help Center: consigli per il tuo progetto
    • Hosting e Cloud
    • Coding
    • CMS & Piattaforme Self-Hosted
    • Annunci e Collaborazioni
    • Annunci Vendita e Acquisto: Pubblicità, Domini, Link e altro
    • Collaborazioni WEB e Lavoro: offro e cerco
    • Impresa, Fisco e Leggi
    • Consulenza Legale e Professioni Web
    • Consulenza Fiscale, Imprese, Startup e P.Iva
    • Gli Off Topic
    • PC, Smartphone e altri Hardware
    • Tutti i Software
    • GT Fetish Cafè
    • Discussioni
    • Non letti 0
    • Recenti
    • Hashtag
    • Popolare
    • Utenti
    • Privacy
    • Termini e condizioni
    • © 2026 Search On Media Group S.r.l.