76 lines
2.2 KiB
PHP
76 lines
2.2 KiB
PHP
<?php
|
|
namespace lib\Core;
|
|
|
|
use \PDO;
|
|
|
|
abstract class Model
|
|
{
|
|
private $db = null;
|
|
private $_debug = false;
|
|
private $_mode = PDO::FETCH_OBJ;
|
|
protected function __construct()
|
|
{
|
|
$envs = parse_ini_file("./env.ini", true);
|
|
if (!$envs) {
|
|
throw new \Exception(var_export($envs, true));
|
|
}
|
|
//echo var_dump($envs);exit;
|
|
$dsn = sprintf("%s:host=%s;dbname=%s;charset=%s", $envs['db']['driver'], $envs['db']['host'], $envs['db']['name'], $envs['db']['charset']);
|
|
$this->db = new PDO($dsn, $envs['db']['id'], $envs['db']['passwd']);
|
|
$this->db->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
|
|
$this->db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
|
|
} //
|
|
|
|
abstract public function getTable();
|
|
final public function getDB()
|
|
{
|
|
return $this->_db;
|
|
}
|
|
final public function setDebug($debug)
|
|
{
|
|
$this->_debug = $debug;
|
|
}
|
|
final public function getDebug()
|
|
{
|
|
return $this->_debug;
|
|
}
|
|
final public function setMode($mode)
|
|
{
|
|
$this->_mode = $mode;
|
|
}
|
|
final public function getMode()
|
|
{
|
|
return $this->_mode;
|
|
}
|
|
|
|
final public function execute($sql)
|
|
{
|
|
$stmt = $this->db->prepare($sql);
|
|
$stmt->execute();
|
|
return $stmt;
|
|
}
|
|
final protected function getRow($sql)
|
|
{
|
|
$stmt = $this->execute($sql);
|
|
return $stmt->fetch($this->getMode());
|
|
}
|
|
final protected function getRows($sql, $mode = PDO::FETCH_OBJ)
|
|
{
|
|
$stmt = $this->execute($sql);
|
|
return $stmt->fetchAll($this->getMode());
|
|
}
|
|
|
|
final public function getData($wheres = array(), $column = "*")
|
|
{
|
|
$sql = sprintf("SELECT %s FROM %s %s", $column, $this->getTable(), count($wheres) ? "WHERE " . implode("AND", $wheres) : "");
|
|
echo $sql;
|
|
return $this->getRow($sql);
|
|
}
|
|
final public function getDatas(array $wheres = array(), $column = "*")
|
|
{
|
|
$sql = sprintf("SELECT %s FROM %s %s", $column, $this->getTable(), count($wheres) ? "WHERE " . implode("AND", $wheres) : "");
|
|
echo $sql;
|
|
return $this->getRows($sql);
|
|
}
|
|
} //Class
|