控制器如何连接模型示例

时间:2014-04-18 02:41:29

标签: php pdo database-connection

如何在控制器中连接模型? 我应该使用require' model.php'在' controller.php'

Controller.php这样

class IndexController {
    public function __construct(){
        require 'models/system_db';
    }
    public function index(){
    if(empty($_GET)){
        // get data from model 
    } else {
      $get_page = $_GET['page'];

    }
  }
}

model.php

class system_db{
    public function __construct(){
        require_once '../config/connect_db.php';
        $dbconnect = new dbconnect();
        $dbconnect_system_db = $dbconnect->system_db();
    }

}

connect_db.php

class dbconnect {
    private $host = 'localhost';
    private $dbname;
    private $user;
    private $password;

    public function system_db() {
        $dbname = 'system_db';
        $user = 'user';
        $password = 'password';
        try {
            $dbh = new PDO('mysql:host='.$host.';dbname='.$dbname.'', $user, $password);
            $dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
        } catch (PDOException $e) {
            die();
        }
        return $dbh;
    }

    public function another_db() {}
}

2 个答案:

答案 0 :(得分:1)

由于您正在研究MVC范例,因此您还应该研究自动加载PHP类。这样您就不必在控制器中手动包含/要求单个文件。

这是来自php.net的自动编码http://www.php.net/manual/en/language.oop5.autoload.php

答案 1 :(得分:-1)

是的,您应该在控制器中包含您的模型,例如:

conroller.php

include(dirname(__FILE__).'/../modeles/profils.php');

profils.php:

function users_profils()
{
    $users = array();

    $req = mysql_query("SELECT id, name, cv, DATE_FORMAT(date, '%d/%m/%Y %H') AS date_formatee, contenu 
    FROM users_tab
    ORDER BY date DESC");
    while ($data = mysql_fetch_assoc($req))
    {
            $users[] = $data;
    } 
    return $news;
}
祝你好运!