Blogger Information
Blog 44
fans 0
comment 0
visits 35567
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
封装一个数据库常用操作类Query.php-2019年3月4日
的博客
Original
1128 people have browsed it

链式操作:

所谓链式操作最简单的理解就是 操作完毕之后再返回对象$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()可以实现优雅的代码结构

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