链式操作:
所谓链式操作最简单的理解就是 操作完毕之后再返回对象$this
以下案例实现的思路是通过__callStatic重载静态方法跨类调用(call_user_func_array())
db.php
<?php require 'Query.php'; class db{ protected static $pdo = null; public static function connection(){ self::$pdo = new PDO('mysql:host=127.0.0.1;dbname=php','root','root'); } public static function __callStatic($name,$arguments) { self::connection(); $query = new Query(self::$pdo); return call_user_func_array([$query,$name],[$arguments[0]]); //这个回调函数作用实际等于 return $query->$name($arguments[0]); } } $staffs = db::table('staff') ->field('id,name,position,mobile') ->where('id > 5') ->limit(5) ->select(); foreach ($staffs as $staff) { print_r($staff); echo '<br>'; }
Query.php
<?php /** * Created by PhpStorm. * User: ZCP * Date: 2019/3/20 * Time: 17:08 */ class Query { public $pdo; public $table; public $field; public $where; public $limit; function __construct($pdo) { $this->pdo = $pdo; } public function table($table) { $this->table = $table; return $this; } public function field($field) { $this->field = $field; return $this; } public function where($where) { $this->where = $where; return $this; } public function limit($limit) { $this->limit = $limit; return $this; } public function select() { $field = empty($this->field) ? '*' : $field = $this->field; $where = empty($this->where) ? '' : 'WHERE '.$where = $this->where; $limit = empty($this->empty) ? '' : 'LIMIT '.$limit = $this->limit; $sql = 'SELECT '.$field.' FROM '.$this->table.' '.$where.$limit; $stmt = $this->pdo->prepare($sql); $stmt->execute(); return $stmt->fetchALL(PDO::FETCH_ASSOC); } }
总结:链接操作是利用类方法返回$this来实现的
__callStatic和__call合理利用可以实现跨类调用
call_user_func_array()可以实现优雅的代码结构