php中面向对象与mysqli实战攻略
<?php
function dump($arr) {
echo "<pre>";
print_r($arr);
echo "</pre>";
}
define("PATH", getcwd());
require('smarty/libs/Smarty.class.php');
class CommonController extends Smarty
{
protected $db;
function __construct(){
parent::__construct();
$this->connect();
$this->smarty_config();
}
private function smarty_config()
{
$this->setTemplateDir(PATH.'/templates/');
$this->setCompileDir(PATH.'/templates_c/');
$this->setConfigDir(PATH.'/configs/');
$this->setCacheDir(PATH.'/cache/');
$this->left_delimiter = '{{';
$this->right_delimiter = '}}';
}
private function connect()
{
$this->db = new mysqli("localhost", "root", "root", "blog");
if (mysqli_connect_errno()) {
exit("连接失败: %s<br>". mysqli_connect_error());
}
$this->db->query("set names utf8");
}
protected function all($sql){
$result = $this->db->query($sql);
$array = array();
while($row = $result->fetch_assoc()){
$array[] = $row;
}
return $array;
}
protected function one($sql){
$result = $this->db->query($sql);
$row = $result->fetch_assoc();
return $row;
}
protected function count($table){
$result = $this->one("select count(*) as count from $table");
return $result["count"];
}
protected function jump($url, $info = "")
{
if ($info == "") {
echo "<script>location.href='" . $url . "'</script>";
} else {
echo "<script>alert('" . $info . "');location.href='" . $url . "'</script>";
}
}
}
<?php
require("common.php");
class IndexController extends CommonController {
function index()
{
$articles = $this->all("select * from article");
$this->assign("articles", $articles);
$this->display("index.html");
}
function show(){
$this->display("show.html");
}
function add()
{
$this->display("add.html");
}
function create()
{
if($_POST) {
}
}
function destroy()
{
$id = $_GET["id"];
$this->db->query("delete from article where id = '$id'");
$this->jump("index.php", "恭喜您,删除成功!");
}
}
$action = isset($_GET["a"]) ? $_GET["a"] : "index";
$index = new IndexController();
$index->$action();