Blogger Information
Blog 43
fans 0
comment 0
visits 30475
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
数据库请求委托代理
橙絮圆
Original
450 people have browsed it

数据库请求委托代理

作业标题:0816 oop编程-4
作业内容:请用请求委托原理封装查询构造器(只封装查询操作即可)


  • 请求委托原理封装查询构造器
  1. class Query{
  2. private static $db;
  3. protected $table;
  4. protected $field;
  5. protected $limit;
  6. private function __construct()
  7. {
  8. }
  9. static function connect($dsn,$username,$pwd)
  10. {
  11. //创建PDO类的唯一实例 pdo对象
  12. if(is_null(static::$db))
  13. {
  14. static::$db = new PDO($dsn,$username,$pwd);
  15. }
  16. // 返回query实例
  17. return new static();
  18. }
  19. public function table($table)
  20. {
  21. $this->table = $table;
  22. return $this;
  23. }
  24. public function field($field)
  25. {
  26. $this->field = $field;
  27. return $this;
  28. }
  29. public function limit($limit)
  30. {
  31. $this->limit = $limit;
  32. return $this;
  33. }
  34. public function getSql()
  35. {
  36. return sprintf('SELECT %s FROM %s LIMIT %d ',$this->field,$this->table,$this->limit);
  37. }
  38. public function select()
  39. {
  40. return static::$db->query($this->getSql())->fetchAll(PDO::FETCH_ASSOC);
  41. }
  42. }
  43. class Db{
  44. static function __callStatic($method,$args)
  45. {
  46. $dsn = 'mysql:host=localhost;dbname=my_test';
  47. $username = 'root';
  48. $pwd = 'root';
  49. // 获取到被委托的类query实例
  50. $query = Query::connect($dsn,$username,$pwd);
  51. return call_user_func([$query,$method],...$args);
  52. }
  53. }$res = Db::table('emp')->field('ename,empno')->limit(5)->select();
  54. echo '<pre>';
  55. print_r($res);

数据库链式操作

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