1. 抽象类与接口的组合应用
用抽象类来实现接口,对数据表进行增删改查的操作,示例如下:
<?php
// 1. 接口:定义接口中的方法(增删改查,基于pdo对象)
interface iDbBase
{
// 增
public static function insert ($pdo,$data);
// 删
public static function delete ($pdo,$where);
// 改
public static function update ($pdo,$options);
// 查
public static function select ($pdo,$options=[]);
}
// 2. 抽象类实现接口:放一些公共的操作(连接数据库,拿到pdo对象)
abstract class aDb implements iDbBase
{
protected static $pdo = null;
public static function connect ($dsn,$username,$password) {
if (is_null(self::$pdo)) {
self::$pdo = new PDO($dsn,$username,$password);
}
return self::$pdo;
}
}
// 3. 继承抽象类(真正实现类/子类),将接口中的方法全部实现
class Db extends aDb
{
// 插入
public static function insert ($pdo,$data) {
$stmt = $pdo->prepare(" INSERT `student` SET `username`='钱八',`password`='123456',`sex`='男',`age`='50',`tel`='12335647541' ");
$stmt->execute();
return "受影响的记录有".$stmt->rowCount()."条";
}
// 删除
public static function delete ($pdo,$where) {
$stmt = $pdo->prepare(' DELETE FROM `student` WHERE `id`=1010 ');
$stmt->execute();
return "被删除的记录有".$stmt->rowCount()."条";
}
// 更新
public static function update ($pdo,$options) {
$stmt = $pdo->prepare(' UPDATE `student` SET `username`=? WHERE `id`=? ');
$stmt->execute(['老大','4']);
return "更新的记录有".$stmt->rowCount()."条";
}
// 查询
public static function select ($pdo,$options=[]) {
return $pdo->query(' SELECT * FROM `student` ')->fetchAll(PDO::FETCH_ASSOC);
}
}
$config =[
'type' => $type ?? 'mysql',
'host' => $host ?? 'php.edu',
'username' => $username ?? 'root',
'password' => $password ?? 'root',
'dbname' => $dbname ?? 'first',
'port' => $port ?? '3306',
'charset' => $charset ?? 'utf8',
];
extract($config);
$dsn = sprintf('%s:host=%s;dbname=%s;charset=%s;port=%s',$type,$host,$dbname,$charset,$port);
$pdo = Db::connect($dsn,$username,$password);
// 调用 查询
$res = Db::select($pdo);
foreach ($res as $user) {
printf('| %d | %s | %s | %s | %s | %s |<br>',$user['id'],$user['username'],$user['password'],$user['sex'],$user['age'],$user['tel']);
}
// 调用 插入
echo Db::insert($pdo,$data);
// 调用 删除
echo Db::delete($pdo,$where);
// 调用 更新
echo Db::update($pdo,$options);
- 数据表原型:
- 调用查询操作:
- 调用插入操作:
- 调用删除操作:
- 调用更新操作:
2.总结
其他一些知识点都自己记录在xmind的笔记里了