How to properly set up a PDO connection

后端 未结 4 1562
温柔的废话
温柔的废话 2020-11-21 07:24

From time to time I see questions regarding connecting to database.
Most answers is not the way I do it, or I might just not get the answers correctly. Anyway; I\'ve nev

4条回答
  •  逝去的感伤
    2020-11-21 08:04

    The goal

    As I see it, your aim in this case is twofold:

    • create and maintain a single/reusable connection per database
    • make sure that the connection has been set up properly

    Solution

    I would recommend to use both anonymous function and factory pattern for dealing with PDO connection. The use of it would looks like this :

    $provider = function()
    {
        $instance = new PDO('mysql:......;charset=utf8', 'username', 'password');
        $instance->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
        $instance->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
        return $instance;
    };
    
    $factory = new StructureFactory( $provider );
    

    Then in a different file or lower in the same file:

    $something = $factory->create('Something');
    $foobar = $factory->create('Foobar');
    

    The factory itself should look something like this:

    class StructureFactory
    {
        protected $provider = null;
        protected $connection = null;
    
        public function __construct( callable $provider )
        {
            $this->provider = $provider;
        }
    
        public function create( $name)
        {
            if ( $this->connection === null )
            {
                $this->connection = call_user_func( $this->provider );
            }
            return new $name( $this->connection );
        }
    
    }
    

    This way would let you have a centralized structure, which makes sure that connection is created only when required. It also would make the process of unit-testing and maintenance much easier.

    The provider in this case would be found somewhere at the bootstrap stage. This approach would also give a clear location where to define the configuration, that you use for connecting to the DB.

    Keep in mind that this is an extremely simplified example. You also might benefit from watching two following videos:

    • Global State and Singletons
    • Don't Look For Things!

    Also, I would strongly recommend reading a proper tutorial about use of PDO (there are a log of bad tutorial online).

提交回复
热议问题