首页 > 解决方案 > 如何在不使用 PHP MVC 中的 Extend 的情况下将数据库操作层与 BaseModel 层分离?

问题描述

我正在编写一个一切正常的代码,但我目前面临的问题是我想通过将 myBaseModel Class与我的DbOPerations Class.

目前,我正在这样做:

基本模型.php

class BaseModel extends DbOperatons implements ModelInterface{

    protected $table = 'default';
    protected $db;
    private $OperateOnDb=new DbOperations();

    /**
     * Fetch all records from table
     * @return array
     */
    public function all(){
        return $this->db->select(["*"])->run();
    }

    /**
     * Find record by given id
     * @param int $id
     * @return array
     */
    public function find($id = 1){
        return $this->db->select(["*"])->where(['id'=>$id])->run();
    }

}

DbOperations.php:

<?php

namespace core\others;

use PDO;

class DbOperations {

    protected $pdo;

    protected $selectParams = '*';

    protected $table       = '';

    protected $lastTable       = '';

    protected $groupByColumns       = '';

    protected $where      = '';


    /**
     * DbOperations constructor.
     * @param PDO $pdo
     */
    public function __construct(PDO $pdo) {
        $this->pdo= $pdo;

    }

    /**
     * Setting select parameters
     * @param $params
     * @return $this
     */
    public function select($params){
        $this->selectParams = implode(",",$params);
        return $this;
    }

    /**
     * Set table name as array like ["students","teachers"]
     * @param array $table
     * @return $this
     */
    public function setTable($table = []){
        $this->lastTable = $this->table;
        $this->table = $table;
        if(is_array($table)) {
            $tableNames = '';
            foreach($table as $table)
                $tableNames .=  $table . ", ";
            $this->table = rtrim($tableNames, ", ");
        }
        return $this;
    }

    /**
     * Setting group by clause
     * @param array $columns
     * @return $this
     */
    public function groupBy($columns = []){
        $this->groupByColumns = implode(", ", $columns);
        return $this;
    }

    /**
     * Setting Where clause
     * @param array $whereClause
     * @param string $operator
     * @param string $operand
     * @return $this
     */
    public function where($whereClause = [],$operator = '=', $operand = 'AND'){
        $where = [];
        foreach ($whereClause as $column => $data)
            $where[] =  $column . $operator . $data;
        $where = implode(' ' . $operand . ' ', $where);
        $this->where = $where;
        return $this;
    }

    /**
     * Generate dynamic SQL
     * @return string
     */
    public function generateSQL(){
        $query = "SELECT {$this->selectParams} FROM {$this->table}";
        if ($this->where!='')
            $query .= " WHERE " . $this->where;
        if ($this->groupByColumns!='')
            $query .= " GROUP BY " . $this->groupByColumns;
        return $query;
    }
    /**
     * Returns a result of dynamic query made by select, where, group by functions
     * @return array
     */
    public function run(){
        $query = $this->generateSQL();
        $statement = $this->pdo->prepare($query);
        $statement->execute();
        $this->table = $this->lastTable;
        return $statement->fetchAll(2);
    }


    /**
     * For creating record in DB with key value pair
     * @param array $data
     * @param null $table
     * @return integer Last Inserted id
     */
    public function create($data = ['key'=>'value'],$table = null){
        $this->lastTable = $this->table;
        $table = (isset($table)?$table : $this->table);
        $columns = '';
        $values= '';
        foreach($data as $key => $valuePair){
            $columns .= "{$key},";
            $values .= "?,";
        }
        $columns = substr($columns, 0, -1);
        $values = substr($values, 0, -1);
        $query = "INSERT INTO {$table} ({$columns}) VALUES ({$values})";
        $this->pdo->prepare($query)->execute(array_values($data));
        return $this->pdo->lastInsertId();
    }

    // @codeCoverageIgnoreStart
    /**
     * For updating record in database table
     * @param array $data
     * @return $this
     */
    public function update($data = []){
        $columns = '';
        foreach($data as $key => $valuePair){
            if($key!='id')
                $columns .= "{$key}=?, ";
        }
        $columns = substr($columns, 0, -2);
        $query = "UPDATE {$this->table} SET {$columns} WHERE id=?";
        $this->pdo->prepare($query)->execute(array_values($data));
        return $this;
    }

    /**
     * For deleting record in database table
     * @param $id
     * @param null $table
     * @return $this
     */
    public function delete($id,$table = null){
        $this->lastTable = $this->table;
        $table = (isset($table)?$table : $this->table);
        $query = "DELETE FROM {$table} WHERE id =:id";
        $statement = $this->pdo->prepare( $query);
        $statement->bindParam(':id', $id);
        $statement->execute();
        return $this;
    }
}

现在我想使用 my 的功能DBOPerationsbasemodel class不扩展的情况下工作。我曾尝试在 basemodel 类中声明一个 dboperation 对象,但我无法做到这一点,请帮忙!

标签: phpdatabasemodel-view-controller

解决方案


推荐阅读