mjpramos
mjpramos

Reputation: 543

PHP MVC PDO Multiple databases

I'm learning MVC in PHP and using PDO for database access.

My database class is as follows (I use DEFINE in a config file for database variables):

class Database extends PDO {

    public function __construct($dbconn ="mysql") {

        $options = array(PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_OBJ, PDO::ATTR_ERRMODE => PDO::ERRMODE_WARNING);

        switch($dbconn) {
            case 'usados':
                parent::__construct(DB_TYPE_USADOS . ':host=' . DB_HOST_USADOS . ';dbname=' . DB_NAME_USADOS, DB_USER_USADOS, DB_PASS_USADOS, $options);
                break;

            case 'autos':
                parent::__construct(DB_TYPE_AUTOS . ':host=' . DB_HOST_AUTOS . ';dbname=' . DB_NAME_AUTOS, DB_USER_AUTOS, DB_PASS_AUTOS, $options);
                break;

            case 'servicos':
                parent::__construct(DB_TYPE_SERVICOS . ':host=' . DB_HOST_SERVICOS . ';dbname=' . DB_NAME_SERVICOS, DB_USER_SERVICOS, DB_PASS_SERVICOS, $options);
                break;

            default:
                parent::__construct(DB_TYPE_MYSQL . ':host=' . DB_HOST_MYSQL . ';dbname=' . DB_NAME_MYSQL, DB_USER_MYSQL, DB_PASS_MYSQL, $options);
                break;
        }
    }
}

And in an example model, I have:

class Note_Model extends Model {

    public $errors = array();

    public function __construct() {
        parent::__construct($dbconn="mysql");
    }

    public function getAllNotes() {
        $sth = $this->db->prepare("SELECT user_id, note_id, note_text
                                    FROM note
                                    WHERE user_id = :user_id ;");
        $sth->execute(array(':user_id' => $_SESSION['user_id']));    

        return $sth->fetchAll();
    }
}

I have 2 questions:

  1. In my database class, is my approach for different database connections (to be used by different models) ok? Is the switch structure well used for this situation and a variable with where to connect?

  2. I can connect to different databases in different models, but how would I get data from different databases in 1 same model if I had the need. Say for example, in a dashboard that shows information from different sources. It's not just $this->db, is it?

Thank you in advanced.

Upvotes: 0

Views: 1264

Answers (1)

George Brighton
George Brighton

Reputation: 5151

A switch statement in a constructor is a code smell indicating the class is doing too much. I'd create 4 classes (extending PDO or your own base class) and use them instead.

Regarding models, I'm no expert in MVC, but I know you can join tables in different databases provided they're on the same server. However, that could lead to a 'boss' class that breaks the one-database-per-class rule. The best way is probably to have another class that ask whatever models you need for data, and then pieces it together.

Upvotes: 1

Related Questions