Blogger Information
Blog 33
fans 1
comment 0
visits 21826
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
5-07单利模式
冰雪琉璃
Original
648 people have browsed it
  1. <?php
  2. //定义一个接口
  3. interface iDbBase
  4. {
  5. //数据库的操作增删查改
  6. static function insert($db,$data);
  7. static function select($db,$where[]);
  8. static function delete($db,$where[]);
  9. static function update($db, $data,$where[]);
  10. // return $this;//实现链式调用
  11. static function doConnect($dsn,$username,$password);
  12. }
  13. //抽象类使用php中的单利模式来连接数据库
  14. abstract class aDb implements iDbBase
  15. {
  16. //返回pdo的链接对象
  17. private function $instance;
  18. //private阻止此类在外部进行实例化
  19. private function __construct()
  20. {
  21. }
  22. //只能由类的自身来进行实例化
  23. static function doConnect($dsn,$username,$password){
  24. //判断$instance是否是aDb类的对象。用instanceof
  25. //self访问静态成员$instance
  26. if(!self::$instance){
  27. //实例化本类,传入连接参数。
  28. self::$instance =new PDO($dsn,$username,$password)
  29. }
  30. return self::$instance;
  31. }
  32. //self单利模式继承
  33. }
  34. //工作类
  35. class Db extends aDb
  36. {
  37. //数据库的操作增删查改
  38. static function insert($db,$data){
  39. }
  40. static function select($db,$where['gender'=>1,'userid'=>2]){
  41. //声明一个变量
  42. $str="";
  43. foreach($where as $k=>$v){
  44. if(count($where)>1){
  45. $str.=$k.'=' .$v.'and';
  46. }
  47. else{
  48. $str.=$k.'=' .$v;
  49. }
  50. }
  51. if(count($where)>1) {
  52. $str=substr($str,0,strlen(strlen)-4);
  53. }
  54. else{
  55. echo $str;
  56. }
  57. //limit限定查询表的条数
  58. return $db->query("SELECT * FROM 'myid' WHERE $str LIMIT 2")->fetchAll(PDO::FETCH_ASSOC);
  59. }
  60. static function delete($db,$where['gender'=>1,'userid'=>2]){
  61. return $db->query("SELECT * FROM 'myid' WHERE $str LIMIT 1")->fetchAll(PDO::FETCH_ASSOC);
  62. }
  63. }
  64. //客户端代码
  65. $config=[
  66. 'type'=> $type??'mysql',
  67. 'host'=> $host='host'??'localhost',
  68. 'dbname'=>$dbname='dbname'??'news',
  69. 'password'=>$password='password'??'123456tyi',
  70. 'username'=> $username='username'??'root',
  71. ];
  72. $dsn=printf('%s:host', $config['type'],$config['host'],$config['dbname']);
  73. $username=$config['username'];
  74. $password=$config['password'];
  75. //获取PDO连接对象
  76. $db=Db::doConnect($dsn,$username,$password);
  77. echo '<pre>';
  78. print_r(Db::select($db));
  79. ?>
Correcting teacher:灭绝师太灭绝师太

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