博客列表 >封装一个数据库常用操作类Query.php-2019年3月4日

封装一个数据库常用操作类Query.php-2019年3月4日

的博客
的博客原创
2019年03月20日 23:26:081120浏览

链式操作:

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

声明:本文内容转载自脚本之家,由网友自发贡献,版权归原作者所有,如您发现涉嫌抄袭侵权,请联系admin@php.cn 核实处理。
全部评论
文明上网理性发言,请遵守新闻评论服务协议