Use of PDO in classes

后端 未结 4 997
面向向阳花
面向向阳花 2020-11-28 01:40

I have a few classes that perform some MySQL queries and prepared statements. However, I am lost in how to incorporate my PDO object within those classes. For example, I w

4条回答
  •  感情败类
    2020-11-28 02:22

    You can instantiate your connection to the database in a class that implement the singleton pattern. The connection will be done once and this class will be easily accessible by all of your other objects / scripts.

    i use a class called "Core" in the following example;

    class Core
    {
        public $dbh; // handle of the db connexion
        private static $instance;
    
        private function __construct()
        {
            // building data source name from config
            $dsn = 'pgsql:host=' . Config::read('db.host') .
                   ';dbname='    . Config::read('db.basename') .
                   ';port='      . Config::read('db.port') .
                   ';connect_timeout=15';
            // getting DB user from config                
            $user = Config::read('db.user');
            // getting DB password from config                
            $password = Config::read('db.password');
    
            $this->dbh = new PDO($dsn, $user, $password);
        }
    
        public static function getInstance()
        {
            if (!isset(self::$instance))
            {
                $object = __CLASS__;
                self::$instance = new $object;
            }
            return self::$instance;
        }
    
        // others global functions
    }
    

    this class take parameters from a static class called "Config" where you can store your configuration:

    in all your scripts / objects you just have to get the instance of Core and then query the DB

    $sql = "select login, email from users where id = :id";
    
    try {
        $core = Core::getInstance();
        $stmt = $core->dbh->prepare($sql);
        $stmt->bindParam(':id', $this->id, PDO::PARAM_INT);
    
        if ($stmt->execute()) {
            $o = $stmt->fetch(PDO::FETCH_OBJ);
            // blablabla....
    

    If you need more information about singleton look at the PHP doc http://php.net/manual/en/language.oop5.patterns.php

提交回复
热议问题