Correcting teacher:天蓬老师
Correction status:qualified
Teacher's comments:想过为什么要把类分为抽象类,接口这么多类型呢
abstract
声明,不应该被实例化protected
,否则为private
interface
声明abstract
关键字public
implements
关键字来实现接口
<?php
//接口 定义数据库的增删查改操作
interface iDB_curd{
//使用静态方法避免实例化
public static function Insert($db, $options);
public static function Delete($db, $where);
public static function Select($db, $where);
public static function Update($db, $options);
}
//抽象类 实现数据库操作接口 定义数据库连接
abstract class aDB_con implements iDB_curd{
//使用单例模式连接:创建类的唯一实例,唯一对象
protected static $db = null;
//连接数据库
public static function connect($dsn, $username, $password){
if(is_null(self::$db)){
//如果当前连接对象时null 表示当前未连接数据库
self::$db = new PDO($dsn, $username, $password);
}
return self::$db;
}
}
//实现类 数据库增删查改的操作实现
class DB_curd extends aDB_con{
//使用静态方法避免实例化
public static function Insert($db, $options){
$sql = "INSERT `user` SET `username`=?, `password`=?, `age`=?";
$stmt = $db->prepare($sql);
$stmt->execute($options);
return sprintf("新增了%d条记录,主键ID:%d<br>", $stmt->rowCount(),$db->lastInsertId());
}
public static function Delete($db, $where){
$sql = "DELETE FROM `user` WHERE `id`=?";
$stmt = $db->prepare($sql);
$stmt->execute($where);
return "删除成功 ".$stmt->rowCount()."条记录<br>";
}
public static function Select($db, $where){
$sql = "SELECT `id`,`username`,`age` FROM `user` WHERE `age`>?";
$stmt = $db->prepare($sql);
$stmt->execute($where);
return $stmt->fetchALL(PDO::FETCH_ASSOC);
}
public static function Update($db, $options){
$sql = "UPDATE `user` SET `username`=?, `password`=?, `age`=? WHERE id=?";
$stmt = $db->prepare($sql);
$stmt->execute($options);
return "更新成功 ".$stmt->rowCount()."条记录<br>";
}
}
$config = require __DIR__.'/../0720/config.php';
extract($config);
//$dsn:数据源名称
$dsn = "{$type}:host={$host};dbname={$dbname};charset={$charset};port={$port}";
$db = aDB_con::connect($dsn, $username, $password);
echo DB_curd::Insert($db, ['abstract', md5('abstract'), 12]);
echo DB_curd::Delete($db, [69]);
echo DB_curd::Update($db, ['interface', md5('interface'), 22, 73]);
$user = DB_curd::Select($db, [12]);
foreach($user as $v){
vprintf('%d, %s, %d<br>', $v);
}