Question

How to connect model in controller? should I use require 'model.php' in '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() {}
}
Was it helpful?

Solution

Since you are looking into the MVC paradigm you should also look into autoloading PHP classes. This way you wont have to manually include/require individual files in your controllers.

Here is a the from php.net on autolaoding http://www.php.net/manual/en/language.oop5.autoload.php

OTHER TIPS

Yes you should include your modele in your controller, exemple :

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

Good luck!

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top