<?php
/**
* 控制器基类
*/
class Controller
{
protected $_controller;
protected $_action;
protected $_view;
// 构造函数,初始化属性,并实例化对应模型
function __construct($controller, $action)
{
$this->_controller = $controller;
$this->_action = $action;
$this->_view = new View($controller, $action);
}
// 分配变量
function assign($name, $value)
{
$this->_view->assign($name, $value);
}
// 渲染视图
function __destruct()
{
$this->_view->render();
}
}
<?php
class Model extends Sql
{
protected $_model;
protected $_table;
function __construct()
{
// 连接数据库
$this->connect(DB_HOST, DB_USER, DB_PASSWORD, DB_NAME);
// 获取模型名称
$this->_model = get_class($this);
$this->_model = rtrim($this->_model, 'Model');
// 数据库表名与类名一致
$this->_table = strtolower($this->_model);
}
function __destruct()
{
}
}
<?php
class Sql
{
protected $_dbHandle;
protected $_result;
// 连接数据库
public function connect($host, $user, $pass, $dbname)
{
try {
$dsn = sprintf("mysql:host=%s;dbname=%s;charset=utf8", $host, $dbname);
$this->_dbHandle = new PDO($dsn, $user, $pass, array(PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC));
} catch (PDOException $e) {
exit('错误: ' . $e->getMessage());
}
}
// 查询所有
public function selectAll()
{
$sql = sprintf("select * from `%s`", $this->_table);
$sth = $this->_dbHandle->prepare($sql);
$sth->execute();
return $sth->fetchAll();
}
// 根据条件 (id) 查询
public function select($id)
{
$sql = sprintf("select * from `%s` where `id` = '%s'", $this->_table, $id);
$sth = $this->_dbHandle->prepare($sql);
$sth->execute();
return $sth->fetch();
}
// 根据条件 (id) 删除
public function delete($id)
{
$sql = sprintf("delete from `%s` where `id` = '%s'", $this->_table, $id);
$sth = $this->_dbHandle->prepare($sql);
$sth->execute();
return $sth->rowCount();
}
// 自定义SQL查询,返回影响的行数
public function query($sql)
{
$sth = $this->_dbHandle->prepare($sql);
$sth->execute();
return $sth->rowCount();
}
// 新增数据
public function add($data)
{
$sql = sprintf("insert into `%s` %s", $this->_table, $this->formatInsert($data));
return $this->query($sql);
}
// 修改数据
public function update($id, $data)
{
$sql = sprintf("update `%s` set %s where `id` = '%s'", $this->_table, $this->formatUpdate($data), $id);
return $this->query($sql);
}
// 将数组转换成插入格式的sql语句
private function formatInsert($data)
{
$fields = array();
$values = array();
foreach ($data as $key => $value) {
$fields[] = sprintf("`%s`", $key);
$values[] = sprintf("'%s'", $value);
}
$field = implode(',', $fields);
$value = implode(',', $values);
return sprintf("(%s) values (%s)", $field, $value);
}
// 将数组转换成更新格式的sql语句
private function formatUpdate($data)
{
$fields = array();
foreach ($data as $key => $va