php中面向对象与mysqli实战攻略

<?php
//common.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();

        //设置smarty
        $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()
    {
        //连接MySQL数据库
        $this->db = new mysqli("localhost", "root", "root", "blog");

        //检查连接错误
        if (mysqli_connect_errno()) {
            exit("连接失败: %s<br>". mysqli_connect_error());
        }
        $this->db->query("set names utf8");
    }

     /***
     * 查询所有数据
     * @param $sql
     * @return array
     */
    protected function all($sql){
        $result = $this->db->query($sql);
        $array = array();
        while($row = $result->fetch_assoc()){
            $array[] = $row;
        }
        return $array;
    }

    /***
     * 查询单条数据
     * @param $sql
     * @return mixed
     */
    protected function one($sql){
        $result = $this->db->query($sql);
        $row = $result->fetch_assoc();
        return $row;
    }

    /***
     * 查询符合条件的记录数
     * @param $sql
     * @return int
     */
    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
//index.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();