php - 如何在不使用PHP MVC扩展的情况下将数据库操作层与BaseModel层分开?

标签 php database model-view-controller

我正在编写一个代码,其中所有的工作都非常好,但我目前面临的问题是,我希望通过将我的BaseModel 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;
    }
}

现在我想使用DBOPerations的功能在basemodel class中工作,而不需要扩展。我试图在basemodel类中声明一个dboperation对象,但是我不能这样做,请帮助!

最佳答案

实际上,不允许使用new创建实例并将其设置为属性。您可以在构造函数中执行此赋值,但是您可以在两个类之间实现unwanted tight coupling。正确的解决方案涉及依赖注入。因此,要么将已经创建的实例注入构造函数(并在构造函数中分配),要么通过setter方法注入(并在方法中分配)。构造函数注入更好。根据您的代码,这里是您如何划分职责的。
core/others/databaseadapter.php

<?php

namespace core\others;

interface DatabaseAdapter {

    public function select($params);
    public function setTable($table = []);
    public function groupBy($columns = []);
    public function where($whereClause = [], $operator = '=', $operand = 'AND');
    public function generateSQL();
    public function run();
    public function create($data = ['key' => 'value'], $table = null);
    public function update($data = []);
    public function delete($id, $table = null);
}

core/others/pdoadapter.php
<?php

namespace core\others;

use core\others\DatabaseAdapter;

class PdoAdapter implements DatabaseAdapter {

    private $connection;
    private $selectParams = '*';
    protected $table = '';
    protected $lastTable = '';
    protected $groupByColumns = '';
    protected $where = '';

    /**
     * @param \PDO $connection Database connection.
     */
    public function __construct(\PDO $connection) {
        $this->connection = $connection;
    }

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

    /* ... */

}

core/models/basemodel.php
<?php

namespace core\models;

use core\others\DatabaseAdapter;

/**
 * Class BaseModel
 * @package core\models
 */
class BaseModel {

    /**
     * Database adapter.
     *
     * @var DatabaseAdapter
     */
    protected $dbAdapter;

    /**
     * Table name.
     *
     * @var string|array
     */
    protected $table = 'default';

    /**
     * @param DatabaseAdapter $dbAdapter Database adapter.
     */
    public function __construct(DatabaseAdapter $dbAdapter) {
        $this->dbAdapter = $dbAdapter;
    }

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

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

    /**
     * Create a new record.
     *
     * @param array $columns (optional) The list of column name/value pairs, like:
     *  array(
     *      'name' => 'example name',
     *      'phone' => 'example phone number',
     *  )
     * @return int Last insert id.
     */
    public function create($columns = []) {
        return $this->dbAdapter->create($columns, $this->table);
    }

    /**
     * Update a record.
     *
     * @param array $columns (optional) The list of column name/value pairs, like:
     *  array(
     *      'id' => 123,
     *      'name' => 'example name',
     *      'phone' => 'example phone number',
     *  )
     * @return $this
     */
    public function update($columns = []) {
        $this->dbAdapter
                ->setTable($this->table)
                ->update($columns)
        ;
        return $this;
    }

    /**
     * Remove a record.
     *
     * @param int $id Record id.
     * @return $this
     */
    public function delete($id) {
        $this->dbAdapter->delete($id, $this->table);
        return $this;
    }

    /**
     * Get table name.
     *
     * @return string|array
     */
    public function getTable() {
        return $this->table;
    }

    /**
     * Set table name.
     *
     * @param string|array $table
     * @return $this
     */
    public function setTable($table = []) {
        $this->table = $table;

        if (is_array($table)) {
            $tableNames = '';
            foreach ($table as $table) {
                $tableNames .= $table . ", ";
            }
            $this->table = rtrim($tableNames, ", ");
        }

        return $this;
    }

}

core/models/modelfactory.php
<?php

namespace core\models;

use core\others\PdoAdapter;
use app\models\DefaultModel;
use core\others\DependencyContainer;

/**
 * Class ModelFactory
 * @package core\models
 */
class ModelFactory {

    /**
     * @param $model
     * @param null $pdo
     * @return DefaultModel
     */
    public static function build($model, $pdo = null) {
        $model = 'app\models\\' . ucfirst($model) . 'Model';

        $dbInstance = ($pdo) ? $pdo : DependencyContainer::getInstance("Database");
        $pdoAdapterInstance = new PdoAdapter($dbInstance);

        if (class_exists($model)) {
            return new $model($pdoAdapterInstance);
        }

        return new DefaultModel($pdoAdapterInstance);
    }

}

关于php - 如何在不使用PHP MVC扩展的情况下将数据库操作层与BaseModel层分开?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52550398/

相关文章:

php - 无法让简单的 INSERT 工作

带有两个查询的 PHP MySQL

javascript - 将数组从 MVC Controller 传递到 Javascript

php - 如何使用 PHP 将 mysql/json 文件转换为 csv 文件

php - $_POST 中的字符限制

php - 选择 mySQL 中具有不同 ID 的最新条目

database - 按城市/州或邮政编码或电话分类的官方/准确时区数据库

mysql - MySQL数据库在哪里存储数据?

c# - Unity IOC,无法修复无参数构造函数问题

asp.net-mvc - ASP.NET MVC 与时代精神