- Java 双重比较
- java - 比较器与 Apache BeanComparator
- Objective-C 完成 block 导致额外的方法调用?
- database - RESTful URI 是否应该公开数据库主键?
我正在编写一个代码,其中所有的工作都非常好,但我目前面临的问题是,我希望通过将我的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();
}
}
<?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);
}
<?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;
}
/* ... */
}
<?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;
}
}
<?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/
我像那样遍历数组。 NSArray *array = [[currentRaum raumattribute] allObjects]; NSString *compositeString =
我想找到所有引用这种模式的子字符串:一些字符+一些字符+第一个字符。现在我在 Python 2.7 中有了这个: T = "i was here" m = re.findall(r"([a-z])[a
我想使用与 tidyr 分开将一列字符串(例如 [1, 58, 10] )分成几列。我的问题是有时列较短(永远不会更长)。我在同一个数据框中有很多列有这个问题。 加载包 require(tidyr)
我正在开发一个具有图形用户界面的网络测试工具。我现在面临的问题是,我无法将基础数据与 GUI 类分开。该应用程序由一个 QMainWindow 组成,它随后生成多个其他 QDialogs 并具有一些
我经常听到“策略与机制分离”的口头禅,尤其是在 Unix 哲学的背景下。这是什么意思,有哪些具体的例子?什么时候/为什么是/不是一件好事? 最佳答案 它基本上是将需求或业务功能与技术实现分离。机制是技
我正在使用 writeToFile:atomically: 方法将一些加密数据写入文本文件。问题是,需要保存的文件必须是用户加密的文件,并带有我选择的扩展名。这是我到目前为止所拥有的: [encryp
我有这串 abcdef x y z 或这个 "ab cd ef" x y z 我正试图将其解析为 s1 = "abcdef" arr = ["x","y","z"] 或者 s1 = "ab cd e
这个问题已经有答案了: One big javascript file or multiple smaller files? [duplicate] (7 个回答) 已关闭 6 年前。 我有 4 种类
我有这样的事情 - function DetailCtrl($scope) { $scope.persons = [{ id: 1, name: "Mark"
在操作(复制/移动)包含合并单元格的范围时,我总是收到错误消息“您的粘贴与合并单元格重叠。请取消合并单元格,然后重试”。但是,当尝试使用 Range#breakApart 取消合并范围内的单元格时,我
我有一个包含一些 TextFields 的 TableView。所述 TextFields 的值链接到二维数组(NSMutableArrays 的 NSArray)中的某些位置。 一个初始的干净数组定
我定义了一个标签,其中一半需要在左侧,另一半文本需要在右侧。我怎样才能解决这个问题,让另一半拉对? 我添加了 margin-right 以使文本向右拉,但它与其他 div 不一致。
我正在尝试创建一个正则表达式来将 JavaScript 中的每个单词与 .(点)分开。 function myFunction() { var url = "in.k1.k2.k3.k4.com"
如何使用 CSS 将网站的正文/内容区域与背景分开。为了向您展示我的意思,请看附图。因此,两侧的背景将扩展到拥有超大显示器的人,但内容将始终保持相同大小。 谢谢,阿马尔 http://i.imgur.
有可能用 CSS 将两个背景图像对 Angular 分开吗? 我知道如何只用一张图片制作它,但我不能用两张图片制作它。 这是一个例子: |-------------| | /|
这是一个JSFiddle我创建了展示代码的外观。我将如何给予这些 它们之间是否存在间隙,没有一个元素低于另一个元素? .main-content { width: 50%; float: le
我正在处理具有这样数据的项目(我使用带有 python 的 pandas 框架): days rain 0 1 2 0 3 1 1
我正在尝试编写一个宏来获取信息并将该信息发送到另一个函数,方法是将原始 va_list 拆分为字符串,然后从原始 va_list 生成另一个 va_list。 下面是我的代码。 调用宏 /* Usag
我需要来自 SharedToDomains 和 SharedFromDomains 的键和值数据。我想打印这些值。 var LogResponse = DeserializeFromJson(sLog
我现在正在使用 Alamofire 来发出发布请求。我首先在 ViewController 中构建它并开始工作。但后来我试图通过在另一个 class 中构建它来分离它。我使用 singleton 并且
我是一名优秀的程序员,十分优秀!