<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0"><channel><title><![CDATA[Consiglio PDOSingleton]]></title><description><![CDATA[<p dir="auto">Ciao ragazzi,</p>
<p dir="auto">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<br />
creato alla classe PDOStatement.</p>
<p dir="auto">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,<br />
ad esempio la gestione delle eccezione, è meglio metterli prima di ritornare<br />
l'stanza della classe al interno del Singleton (dove li ho commentati adesso)<br />
o dopo avere creato l'istanza con il comando:</p>
<pre><code class="language-php">$objPDO = PDOFactory::getInstance();
</code></pre>
<p dir="auto">P.S. I parametri che formano il DSN li prendo per comodità da un namespace incluso nella index.php</p>
<p dir="auto">//-&gt;class.IPDOFactory.php</p>
<pre><code class="language-php">&lt;?php

/**
 *
 *        ProjectName        :        FastCMS        
 *        ProjectAuthor    :        Adriano Giovannini
 *        ProjectMail        :        ...
 *        ProjectFile        :        class_IPDOFactory.php
 *        ProjectPackage    :        library\PDOFactory
 *        ProjectLicense    :        GPL V3. Se license\&lt;yourLanguage&gt;\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);
    
}

?&gt;
</code></pre>
<p dir="auto">//-&gt; class_PDOFactory.php</p>
<pre><code class="language-php">&lt;?php

require_once 'class_IPDOFactory.php';

/**
 *
 *        ProjectName        :        FastCMS        
 *        ProjectAuthor    :        Adriano Giovannini
 *        ProjectMail        :        ...
 *        ProjectFile        :        class_PDOFactory.php
 *        ProjectPackage    :        library\PDOFactory
 *        ProjectLicense    :        GPL V3. Se license\&lt;yourLanguage&gt;\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 =&gt; true) );
                                                            
            }
            // $objPDO-&gt;setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
            return self::$_blSingletonInstance;
        
        } catch ( PDOException $e ) {
        
            die ( "Error: " . $e-&gt;getMessage() );
            
         }
         
    }
    
    /**
     *
     *    Initiate a transaction
     *
     *    @return bool
     *
     */
    public function beginTransaction()
    {
    
        return self::$_blSingletonInstance-&gt;beginTransection();
        
    }
    
    /**
     *
     *    Commit a transaction
     *
     *    @return bool
     *
     */
    public function commit()
    {
        
        return self::$_blSingletonInstance-&gt;commit();
        
    }
    
    /**
     *
     *    Fetch the state of SQL associated whit the last operation on the database
     *
     *    @return string
     *
     */
    public function errorCode()
    {
    
        return self::$_blSingletonInstance-&gt;errorCode();
        
    }
    
    /**
     *
     *    Fetch the extended error information associated with the last operation on
     *    database
     *
     *    @return array
     *
     */
    public function errorInfo()
    {
    
        return self::$_blSingletonInstance-&gt;errorInfo();
        
    }
    
    /**
     *
     *    Execute SQL statement and return the number of affected row
     *
     *    @param string $PDOStatement
     *
     */
    public function exec($PDOStatement)
    {
    
        return self::$_blSingletonInstance-&gt;exec($PDOStatement);
        
    }
    
    /**
     *
     *    Retrieve a database connection attribute
     *
     *    @param int $PDOAttribute
     *
     *    @return int
     *
     */
    public function getAttribute($PDOAttribute)
    {
    
        return self::$_blSingletonInstance-&gt;getAttribute($PDOAttribute);
        
    }
    
    /**
     *
     *    Return an array of available PDO Drivers
     *
     *    @return array
     *
     */
    public function getAvailableDriver()
    {
    
        return self::$_blSingletonInstance-&gt;getAvailableDriver();
        
    }
    
    /**
     *
     *    Return the ID of the last inserted row
     *
     *    @param string $LastInsertIdName
     *
     *    @return string
     *
     */
    public function lastInsertId($LastInsertIdName)
    {
    
        return self::$_blSingletonInstance-&gt;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-&gt;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-&gt;query($PDOStatement);
        
    }
    
    /**
     *
     *    Execute Query and return all rows in assoc array
     *
     *    @param string $PDOStatement
     *
     *    @return array
     *
     */
    public function queryFetchAllAssoc($PDOStatement)
    {
    
        return self::$_blSingletonInstance-&gt;query($PDOStatement)-&gt;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-&gt;query($PDOStatement)-&gt;fetch(PDO::FETCH_ASSOC);
        
    }
    
    /**
     *
     *    Execute Query and select one column only
     *
     *    @param string $PDOStatement
     *
     *    @return mixed
     *
     */
    public function queryFetchColAssoc($PDOStatement)
    {
    
        return self::$_blSingletonInstance-&gt;query($PDOStatement)-&gt;fetchColumn();
        
    }
    
    /**
     *
     *    Quote a string for prevent sql injection
     *
     *    @param string $InputString
     *    @param int    $ParameterType
     *
     *    @return string
     *
     */
    public function quote($InputString, $ParameterType)
    {
    
        return self::$_blSingletonInstance-&gt;quote($InputString, $ParameterType);
        
    }
    
    /**
     *
     *    Rolls back a transaction
     *
     *    @return bool
     *
     */
    public function rollBack()
    {
    
        return self::$_blSingletonInstance-&gt;rollBack();
        
    }
    
    /**
     *
     *    Set attribute
     *
     *    @param int      $PDOAttribute
     *    @param mixed $PDOAttributeValue
     *
     *    @return bool
     *
     */
    public function setAttribute($PDOAttribute, $PDOAttributeValue)
    {
    
        return self::$_blSingletonInstance-&gt;setAttribute($PDOAttribue, $PDOAttributeValue);
        
    }

}

?&gt;
</code></pre>
<p dir="auto">//-&gt; class_PDOFactoryException.php</p>
<pre><code class="language-php">&lt;?php

/**
 *
 *        ProjectMail        :        ...
 *        ProjectFile        :        class_PDOFactoryException.php
 *        ProjectPackage    :        library\PDOFactory
 *        ProjectLicense    :        GPL V3. Se license\&lt;yourLanguage&gt;\license.tx
 *                                for more details
 *
 */

class PDOFactoryException
{

    
    public static function PDOExceptionDisplay ( $objPDO, $e, $objStatement)
    {
    
        /**
         *        Static method
         */
        echo "An error occurred connecting: " . $e-&gt;getMessage() . "&lt;br /&gt;";
            /**
             *        List PDOErrorInfo 
             */
            list ($intErrorCode1, $intErrorCode2, $strErrorInfo) = $objPDO-&gt;errorInfo();
                print "PDOExceptionError&lt;br /&gt;";
                print "Error Code: '$intErrorCode1'&lt;br /&gt;";
                print "Driver Code: '$intErrorCode2'&lt;br /&gt;";
                print "Error Info: '$strErrorInfo'&lt;br /&gt;";
                
                /**
                 *        Check error for PDOStatement class
                 */
                if ($objStatement instanceof PDOStatement)
                {
                
                    /**
                     *        Print PDOStatement error
                     */
                    list ($intErrorCode1, $intErrorCode2, $strErrorInfo) = $objStatement-&gt;errorInfo();
                    print "PDOStatementExceptoinError&lt;br /&gt;";
                    print "Error Code: '$intErrorCode1'&lt;br /&gt;";
                    print "Driver Code: '$intErrorCode2'&lt;br /&gt;";
                    print "Error Info: '$strErrorInfo'&lt;br /&gt;";
                    
                }
                exit();
                
    }
    
}

?&gt;
</code></pre>
<p dir="auto">//-&gt; PDONamespace.php</p>
<pre><code class="language-php">&lt;?php

namespace PDONS
{

    const DSN         = 'mysql:host=localhost;charset=utf8;dbname=forum';
    const USERNAME      = 'tuauser';
    const PASSWORD      = 'tuapass';
    
}

?&gt;
</code></pre>
<p dir="auto">//-&gt; index.php</p>
<pre><code class="language-php">&lt;?php

require_once 'PDONamespace.php';
require_once 'library\PDOFactory\class_PDOFactory.php';

try
{

    $objPDO = PDOFactory::getInstance();
    $objPDO-&gt;setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
        //-&gt; Inizio test PDO
    $i = 0;
    $strQuery = "SELECT * FROM user";
    $objStatement = $objPDO-&gt;prepare($strQuery);
    $objStatement-&gt;execute();
    // Rimuovere dai metodi della classe singleton le costanti nel fetch
    while ($arRow = $objStatement-&gt;fetch(PDO::FETCH_ASSOC))
    {
        print "Row $i";
        foreach ($arRow as $key =&gt; $value)
        {    
            print " - Column $key, value $value&lt;br /&gt;";
        }
        $i++;
    }    
    //-&gt; 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-&gt;getMessage() );
    
}


?&gt;
</code></pre>
<p dir="auto">Che ne pensate ?</p>
]]></description><link>https://dev.connect.gt/topic/175611/consiglio-pdosingleton</link><generator>RSS for Node</generator><lastBuildDate>Thu, 26 Nov 2026 10:11:36 GMT</lastBuildDate><atom:link href="https://dev.connect.gt/topic/175611.rss" rel="self" type="application/rss+xml"/><pubDate>Tue, 14 Aug 2012 16:03:51 GMT</pubDate><ttl>60</ttl></channel></rss>