Reputation: 2848
I'm new in MVC, I try to put my PDO into my Model
something like
Model{
public function connectDB(){... }
public function prepare(){... }
public funciton closeDB(){... }
}
//connect DB///////////////////////////////////////////////////////
$dsn = "mysql:host=127.0.0.1; dbname=abc; charset=utf8;";
$username = "member";
$password = "123";
$options = array(PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES utf8');
$db = new PDO($dsn, $username, $password, $options);
$db->setAttribute(PDO::ATTR_EMULATE_PREPARES, FALSE);
$db->setAttribute(PDO::ATTR_ERRMODE,PDO::ERRMODE_EXCEPTION);
//////////////////////////////////////////////////////////////////
$SQL = $db -> prepare("SELECT pday FROM pday");
$SQL -> execute();
$db = NULL;
How can I put connect DB part into Model's method?
and how can I put prepare, execute and close connection into Model too?
something like...
$SQL = new Model;
$SQL->connect_db(); //connect DB part
I'm not sure is this right way or are any better way can suggest me?
Upvotes: 1
Views: 940
Reputation: 11689
There are many way, in fact.
First of all, consider to create a Singleton class for DB Model.
Otherwise, instantiating an object like in your example, you have to construct the class in this way:
class Model
{
private var $pdo;
private var $dbHost;
private var $dbUser;
private var $dbPassword;
private var $dbDB;
public function __construct( $host=Null, $user=Null, $pass=Null, $db=Null )
{
if( $host && $user && $pass && $db )
{
$this->connect( $host, $user, $pass, $db );
}
}
public function connect( $host, $user, $pass, $db )
{
$dsn = 'mysql etc...';
if( $this->pdo = new PDO( $dsn, $user, $pass ) )
{ return True; }
else
{ return False; } // or do some errors
}
public function query( $arg1, ... )
{
(...)
$this->pdo( $query );
(...)
}
}
Then you can call your class in this way:
$SQL = new Model();
$SQL->connect_db( $host, $user, $pass, $db ); //connect DB part
Or directly:
$SQL = new Model( $host, $user, $pass, $db );
Inside the class, the methods refer to PDO instance using $this->pdo
Upvotes: 1