0

我正在学习 PHP 中的 MVC 并使用 PDO 进行数据库访问。

我的数据库类如下(我在数据库变量的配置文件中使用 DEFINE):

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;
        }
    }
}

在一个示例模型中,我有:

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();
    }
}

我有两个问题:

  1. 在我的数据库类中,我对不同数据库连接(供不同模型使用)的方法是否可以?开关结构是否很好地用于这种情况以及连接到哪里的变量?

  2. 我可以连接到不同模型中的不同数据库,但是如果需要,我将如何从 1 个相同模型中的不同数据库中获取数据。例如,在显示来自不同来源的信息的仪表板中。不仅仅是 $this->db,是吗?

提前谢谢你。

4

1 回答 1

1

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.

于 2013-09-21T18:35:29.503 回答