Design Patterns: How to create database object/connection only when needed?

前端 未结 10 961
野的像风
野的像风 2020-11-29 21:04

I\'ve a simple application, say it has some classes and an \"extra\" one that handles database requests. Currently i\'m creating the database object everytime the app is use

10条回答
  •  执念已碎
    2020-11-29 21:55

    interface IDatabase {
        function connect();
    }
    
    class Database implements IDatabase
    {
        private $db_type;
        private $db_host;
        private $db_name;
        private $db_user;
        private $db_pass;
        private $connection = null;
    
        public function __construct($db_type, $db_host, $db_name, $db_user, $db_pass)
        {
            $this->db_type = $db_type;
            $this->db_host = $db_host;
            $this->db_name = $db_name;
            $this->db_user = $db_user;
            $this->db_pass = $db_pass;
        }
    
        public function connect()
        {
            if ($this->connection === null) {
                try {
                    $this->connection = new PDO($this->db_type.':host='.$this->db_host.';dbname='.$this->db_name, $this->db_user, $this->db_pass);
                    $this->connection->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
                    return $this->connection;
                } catch (PDOException $e) {
                    return $e;
                }
            } else {
                return $this->connection;
            }
        }
    }
    

    How about this? In connect(), check if a connection has already been established, if yes, return it, if not, create it and return it. This will prevent you from having TOO many connections open. Let's say, in your controller action, you want to call two methods of UserRepository (that depends on the Database), getUsers() and getBlockedUsers(), if you call these methods, connect() will be called in each one of them, with this check in place it will return the already existing instance.

提交回复
热议问题