PHP - a DB abstraction layer use static class vs singleton object?

后端 未结 5 899
小蘑菇
小蘑菇 2020-12-05 00:54

I don\'t want to create a discussion about singleton better than static or better than global, etc. I read dozens of questions about similar subjects on SO, but I couldn\'t

5条回答
  •  既然无缘
    2020-12-05 01:19

    What is wrong with the following (simplified) example:

    class Database
    {
        protected $_connection;
    
        protected $_config;
    
        public function __construct( array $config ) // or other means of passing config vars
        {
            $this->_config = $config;
        }
    
        public function query( $query )
        {
            // use lazy loading getter
            return $this->_getConnection()->query( $query );
        }
    
        protected function _getConnection()
        {
            // lazy load connection
            if( $this->_connection === null )
            {
                $dsn = /* create valid dsn string from $this->_config */;
    
                try
                {
                    $this->_connection = new PDO( $dsn, $this->_config[ 'username' ], $this->_config[ 'password' ] );
                }
                catch( PDOException $e )
                {
                    /* handle failed connecting */
                }
            }
    
            return $this->_connection;
        }
    }
    
    $db1 = new Database( array(
        'driver'   => 'mysql',
        'host'     => 'localhost',
        'dbname'   => 'test',
        'username' => 'test_root',
        'password' => '**********'
    ) );
    
    $db2 = new Database( array(
        'driver'   => 'pgsql',
        'host'     => '213.222.1.43',
        'dbname'   => 'otherdb',
        'username' => 'otherdb_root',
        'password' => '**********'
    ) );
    
    $someModel       = new SomeModel( $db1 );
    $someOtherModel  = new SomeOtherModel( $db2 );
    $yetAnotherModel = new YetAnotherModel( $db2 );
    

    This demonstrates how you can make use of lazy loading connections, and still have flexibility to use different database connections.

    The database instances will only connect to their individual connection when an object that consumes one of the instances (in this case one of the models) decides to call a method of the instance.

提交回复
热议问题