如何扩展 Silex Doctrine MySQL 查询库?
How to extend Silex Doctrine MySQL query library?
正如标题所说,我正在使用 Silex 和 Doctrine。不过,我想使用我自己的一些简单 classes 来扩展 Doctrine。但是我不知道在'extends ....?'后面放什么。这是我将如何扩展学说的示例:
public function action($action, $table, $where = array()) {
if(count($where) === 3) {
$operators = array('=', '>', '<', '>=', '<=');
$field = $where[0];
$operator = $where[1];
$value = $where[2];
if(in_array($operator, $operators)) {
$sql = "{$action} FROM {$table} WHERE {$field} {$operator} ?";
if(!$this->query($sql, array($value))->error()) {
return $this;
}
}
}
return false;
}
还有这个:
public function insert($table, $fields = array()) {
$keys = array_keys($fields);
$values = null;
$x = 1;
foreach($fields as $field) {
$values .= '?';
if ($x < count($fields)) {
$values .= ', ';
}
$x++;
}
$sql = "INSERT INTO {$table} (`" . implode('`, `', $keys) . "`) VALUES ({$values})";
if(!$this->query($sql, $fields)->error()) {
return true;
}
return false;
}
因此,创建一个扩展 Doctrine 的外部 class。我的 class 会是什么样子:
class DB extends ... {
//blablabla
}
您需要创建您的自定义实体存储库 (Symfony example is crystal clear on this) 您可以看到您必须扩展 Doctrine\ORM\EntityRepository
在您的自定义实体存储库中,您需要使用以下方法之一创建您的方法:
- EntityRepository 方法:findBy、findOneBy 等(最简单但有限)
- DQL(几乎 SQL 但有类固醇)
- QueryBuilder(不错的 OOP API)
- NativeSQL(最差选项)
您需要开始考虑 ORM 方式,而不是旧的 concatenate-strings-to-form-my-insecure-sql 方式 ;)
正如标题所说,我正在使用 Silex 和 Doctrine。不过,我想使用我自己的一些简单 classes 来扩展 Doctrine。但是我不知道在'extends ....?'后面放什么。这是我将如何扩展学说的示例:
public function action($action, $table, $where = array()) {
if(count($where) === 3) {
$operators = array('=', '>', '<', '>=', '<=');
$field = $where[0];
$operator = $where[1];
$value = $where[2];
if(in_array($operator, $operators)) {
$sql = "{$action} FROM {$table} WHERE {$field} {$operator} ?";
if(!$this->query($sql, array($value))->error()) {
return $this;
}
}
}
return false;
}
还有这个:
public function insert($table, $fields = array()) {
$keys = array_keys($fields);
$values = null;
$x = 1;
foreach($fields as $field) {
$values .= '?';
if ($x < count($fields)) {
$values .= ', ';
}
$x++;
}
$sql = "INSERT INTO {$table} (`" . implode('`, `', $keys) . "`) VALUES ({$values})";
if(!$this->query($sql, $fields)->error()) {
return true;
}
return false;
}
因此,创建一个扩展 Doctrine 的外部 class。我的 class 会是什么样子:
class DB extends ... {
//blablabla
}
您需要创建您的自定义实体存储库 (Symfony example is crystal clear on this) 您可以看到您必须扩展 Doctrine\ORM\EntityRepository
在您的自定义实体存储库中,您需要使用以下方法之一创建您的方法:
- EntityRepository 方法:findBy、findOneBy 等(最简单但有限)
- DQL(几乎 SQL 但有类固醇)
- QueryBuilder(不错的 OOP API)
- NativeSQL(最差选项)
您需要开始考虑 ORM 方式,而不是旧的 concatenate-strings-to-form-my-insecure-sql 方式 ;)