Using a database class in my user class

前端 未结 6 607
慢半拍i
慢半拍i 2021-02-09 01:00

In my project I have a database class that I use to handle all the MySQL stuff. It connects to a database, runs queries, catches errors and closes the connection.

Now I

6条回答
  •  我在风中等你
    2021-02-09 01:35

    What I like to do is make the database class with the Singleton pattern in mind. That way, if you already have a database object, it just retrieves it, otherwise creates a new one. For example:

    Database.class.php
    
    class Db
    {
        protected static $_link;
    
        private function __construct()
        {
            // access your database here, establish link
        }
    
        public static function getLink()
        {
            if(self::_link === null) {
                new Db();
            }
            return self::_link;
        }
    
        // etc.
    
    }
    
    
    User.class.php
    
    class User
    {
        protected $_link;    // This will be the database object
        ...
    
        public function __construct()
        {
            $this->_link = Db::getLink();
        }
    
    }
    

    And now you can use User's $_link property to do the database functions, like $this->_link->query(...). You don't necessarily have to put the Db::getLink() in the constructor if your class doesn't have to interact with the database that much.

提交回复
热议问题