Blogger Information
Blog 30
fans 1
comment 0
visits 16059
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
单例模式实现数据库的增删查改
moon
Original
662 people have browsed it

单例模式实现mysql数据库的增删查改

  1. <?php
  2. // 单例模式连接数据库 应用程序跟设计库交互
  3. namespace app\chloe;
  4. use pdo;
  5. interface idbBase
  6. {
  7. // 数据库连接curd
  8. static function insert($db, $data);
  9. static function select($db, $where = []);
  10. static function update($db, $where = []);
  11. static function delete($db, $data, $where = []);
  12. // 数据库连接
  13. static function doconnect($dsn, $user, $password);
  14. }
  15. // 单例模式连接数据库
  16. abstract class adb implements idbBase
  17. {
  18. private static $_instance;
  19. private function __construct()
  20. {
  21. }
  22. private function __clone()
  23. {
  24. }
  25. static function doconnect($dsn, $user, $password)
  26. {
  27. // 创建adb类的唯一实例 获取唯一的pdo对象
  28. if (is_null(self::$_instance)) {
  29. echo 2;
  30. self::$_instance = new pdo($dsn, $user, $password);
  31. }
  32. return self::$_instance;
  33. }
  34. }
  35. //工作类
  36. class DB extends adb
  37. {
  38. // 数据库连接curd
  39. static function insert($db, $data)
  40. {
  41. }
  42. static function select($db, $where = ['uid' => 1])
  43. {
  44. foreach ($where as $k => $v) {
  45. $sql = $k . ' > ' . $v;
  46. }
  47. return $db->query("SELECT * FROM `mj_user` WHERE " . $sql . " LIMIT 3;")->fetchAll(PDO::FETCH_ASSOC);
  48. }
  49. static function update($db, $where = [])
  50. {
  51. }
  52. static function delete($db, $data, $where = [])
  53. {
  54. }
  55. }
  56. //客户端代码
  57. $config = [
  58. 'type' => $type ?? 'mysql',
  59. 'host' => $host ?? 'localhost',
  60. 'dbname' => $dbname ?? 'phpcn',
  61. 'username' => $username ?? 'root',
  62. 'password' => $password ?? '',
  63. 'port' => $port ?? '3308',
  64. 'charset' => $charset ?? 'utf8'
  65. ];
  66. extract($config);
  67. $dsn = sprintf('%s:host=%s;port=%s;charset=%s;dbname=%s', $type, $host, $port, $charset, $dbname);
  68. $pdo = DB::doconnect($dsn, $username, $password);
  69. // var_dump(DB::select($pdo));
  70. // 检查是否获取到pdo唯一实例
  71. for ($i = 0; $i < 10; $i++) {
  72. adb::doconnect($dsn, $username, $password);
  73. }
Correcting teacher:PHPzPHPz

Correction status:qualified

Teacher's comments:
Statement of this Website
The copyright of this blog article belongs to the blogger. Please specify the address when reprinting! If there is any infringement or violation of the law, please contact admin@php.cn Report processing!
All comments Speak rationally on civilized internet, please comply with News Comment Service Agreement
0 comments
Author's latest blog post