Blogger Information
Blog 14
fans 0
comment 0
visits 8788
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
数据库连接及事件委托
于星辉
Original
648 people have browsed it
  1. <?php
  2. /**
  3. * 事件委托:数据库查询构造器
  4. */
  5. //被委托的类
  6. class Query
  7. {
  8. //创建类的唯一实例 :pdo对象
  9. private static $db;
  10. protected $table;
  11. protected $field;
  12. protected $limit;
  13. //private 私有的 阻止此类在外部进行实例化
  14. private function __construct()
  15. {
  16. }
  17. static function connect($dsn,$username,$pwd)
  18. {
  19. //创建pdo类的唯一实例 :pdo对象
  20. if (is_null(static::$db))
  21. {
  22. static::$db = new PDO($dsn,$username,$pwd);
  23. }
  24. //返回query实例
  25. return new static();
  26. }
  27. public function table($table)
  28. {
  29. $this->table = $table;
  30. return $this;
  31. }
  32. public function field($field)
  33. {
  34. $this->field = $field;
  35. return $this;
  36. }
  37. public function limit($limit)
  38. {
  39. $this->limit = $limit;
  40. return $this;
  41. }
  42. public function getSql()
  43. {
  44. return sprintf('SELECT %s FROM %s LIMIT %d',$this->field,$this->table,$this->limit);
  45. }
  46. public function select()
  47. {
  48. return static::$db->query($this->getSql())->fetchAll(PDO::FETCH_ASSOC);
  49. }
  50. }
  51. class Db
  52. {
  53. static function __callStatic($method,$args)
  54. {
  55. $dsn = 'mysql:localhost;dbname=yu';
  56. $username = 'root';
  57. $pwd ='123456yu';
  58. //获取到被委托的类query实例
  59. $query = Query::connect($dsn,$username,$pwd);
  60. return call_user_func([$query,$method],...$args);
  61. }
  62. }
  63. $res = Db::table('cate')->field('catname,catid')->limit(5)->select();
  64. echo '<pre>';
  65. print_r($res);
  66. ?>
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