Which is a better way to connect to a database

Yes, of course. The factory decides whether to create and use only one instance or more. A simplest example of a factory that returns only one instance:

class DbFactory {
    private $db;
    
    public function getDb() {
        if (!$this->db) {
            $this->db = new DbConnection();
        }
        
        return $this->db;
    } 
}
1 Like