PHP Database connection practice

前端 未结 2 1498
悲&欢浪女
悲&欢浪女 2020-12-29 00:16

I have a script that connects to multiple databases (Oracle, MySQL and MSSQL), each database connection might not be used each time the script runs but all could be used in

相关标签:
2条回答
  • 2020-12-29 00:58

    The best performance/practice rule is simple: do connect to one database only.

    As for the connects - try to implement some database access class. Which can connect automatically on demand.

    0 讨论(0)
  • 2020-12-29 01:11

    Use a lazy connection wrapper class:

    class Connection
    {
        private $pdo;
        private $dsn;
    
        public __construct($dsn)
        {
            $this->dsn = $dsn;
        }
    
        public query($sql)
        {
            //the connection will get established here if it hasn't been already
            if (is_null($this->pdo))
                $this->pdo = new PDO($this->dsn);
    
            //use pdo to do a query here
    
        }
    }
    

    I hope you're already using PDO. If not, you should be. PDO is database independent. If you did this using procedural functions, you'd have to create a new class for each database type.

    Anyways, this is just a skeleton (you'd want to add a $params option in query(), for example), but you should be able to get the idea. The connection is only attempted when you call query(). Constructing the object does not make a connection.

    As an aside, consider using Doctrine. It has lazy connections and makes life easier in general.

    0 讨论(0)
提交回复
热议问题