Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
466 views
in Technique[技术] by (71.8m points)

php - Slim 4 Framework Dynamic PDO Connections Using database connection information fetched from master database

Before anyone says this question has been answered already, do note that while defining multiple pdo connections in a container has already been explained here and here, my question is more around the best approach to building dynamic pdo connections from a json object fetched from a master database.

I have the following Database class I use to create any database connection I need, where and whenever they are needed.

class Database {

    private static $dbs = array();

    # we declare as static so the state is kept between function calls to connect
    # this allows to connect just once to the database and then just return the connection
    # on future function calls
    private static $conn = null;

    # now since we dont want to reinstiate the class anytime we need it, lets also set the constructor to private
    private function __construct(){}

    #  get the database connection
    public static function connect( $name, $opt, $struct, $key = null ) {
        if( empty( self::$dbs[$name] ) ) {
            try {
                $struct['username'] = ( null === $key ) ? $struct['username'] : Security::XORDecrypt( $struct['username'], $key );
                $struct['password'] = ( null === $key ) ? $struct['password'] : Security::XORDecrypt( $struct['password'], $key );

                switch( $struct['type'] ) {
                    case 'sqlsrv': # MSSQL
                        self::$conn = new PDO( "sqlsrv:server=" . $struct['hostname'] . ";" . "ConnectionPooling=1;" .  "database=" . $struct['database'], $struct['username'], $struct['password'], array( PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION, PDO::SQLSRV_ATTR_QUERY_TIMEOUT => intval( $struct['timeout'], 10 ) ) );
                    break;
                }

                self::$dbs[$name] = self::$conn;
                return self::$conn;
            }
            catch( PDOException $ex ) {
                if( $opt == 1 )
                    echo "<p class='bg-danger'>Connection error: " . $ex->getMessage() . "</p>";
                else
                    die( json_encode( array( 'outcome' => false, 'message' => 'Unable to connect' ) ) );
            }
        }
        return self::$dbs[$name];
    }

    public static function disconnect( $name ) {
        if( self::$dbs[$name] != NULL ) {
            self::$dbs[$name] = NULL;
        }
    }
}

And whenever I need to connect to a database it's done like this

$pre = '_' . $app_id; $$pre = ''; 
$conn = Database::connect( $pre, $env['options']['env'], $apps['db_conns'][$app_id], $i_key );

In the above:

$app_id: stores the id of the application instance who's data is being requested

$env['options']['env']: stores the environment we're operating under, development/production etcetera.

$apps['db_conns'][$app_id]: is a multi associative array which stores the database connection details (username/password/port) and etcetera per database

$i_key: stores the hash that was used to encrypt the connection details (fetched from another process)

Then the $conn is passed into the Class performing the requested database action. When the connection is no longer needed I close using

Database::disconnect( $pre );

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)
等待大神答复

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...