面向对象—工厂模式示例(数据库示例)

来源:互联网 发布:足球关注分析软件 编辑:程序博客网 时间:2024/05/01 10:57
<?phpheader("content-type:text/html;charset=utf8");class DBFactory{    public static function create($type){        return  new $type;    }}/** * 定义接口 */interface DB{    public function connect();    public function exec($sql);    public function query($sql);    public function add($arr);    public function find($where);    public function del($where);    public function save($arr,$where);}/** * 具体封装方法 */class Mysql implements DB{    public $dsn;    public function __construct(){        $this->dsn = "mysql:host=127.0.0.1;dbname=cms";    }    //链接数据库    public function connect(){        $pdo = new PDO($this->dsn, 'root', 'root');        $pdo->exec("set names utf8");        return $pdo;    }    //具体执行的方法    public function exec($sql){        return $this->connect()->exec($sql);    }    public function query($sql){        return $this->connect()->query($sql);    }    //增    public function add($arr)    {        $key = '';        $value = '';        foreach($arr as $k=>$v)        {            $key .= "$k,";            $value .= "'$v',";        }        $key = substr($key,0,-1);        $value = substr($value,0,-1);        $sql = "insert into cmss ($key) values ($value)";        $res = $this->exec($sql);        return $res;    }    //删    public function del($where)    {        $sql = "delete from cmss where $where";        $res = $this->exec($sql);        return $res;    }    //改    public function save($arr,$where)    {        $str = '';        foreach($arr as $k=>$v)        {            $str .= "$k='$v',";        }        $str = substr($str,0,-1);        $sql = "update cmss set $str where $where";        $res = $this->exec($sql);        return $res;    }    //查    public function find($where)    {        $sql = "select * from cmss where $where";        $arr = $this->query($sql)->fetchAll(PDO::FETCH_ASSOC);        return $arr;    }}$mysql = DBFactory::create("Mysql");$res = $mysql->find("1");var_dump($res);?>
0 0