douzaipou3327 2012-09-05 04:00
浏览 68

使用基本CRUD功能扩展PDO的建议

Just recently I started rewriting a previously procedurally written website by myself, I chose PDO as the wrapper since I'm also getting used to the OOP way of doing things. I would like some advice about the structure of the classes.

Mostly everything is database-driven, like adding categories and subcategories, brands of products, products, users, etc. I suppose each of them could be one class and since I need CRUD operations on all of them, I need a generic way of inserting, updating, deleting records in the MySql database. The problem is not the code, I'd like to (and already have) coded some of the CRUD operations by myself according to my needs, the real problem is the structure and how would I go to correctly distribute and extend those classes.

Right now I've coded 3 different approaches:

  1. A class called 'Operations' which will be extended by all the other classes that need CRUD functions, this class contains pretty generic properties such as $id, $atributes, $fields and $table, and of course the generic methods to insert, update, delete. That way I can create, let's say my Product object with some parameters (name, category, price) and immediately Product->insert() it into the database, without passing any parameters to the insert function. The CRUD functions in this class don't accept parameters, they depend on the created object's properties.

  2. Same as above but the CRUD functions accept parameters, making them (I suppose) more generic, in case I just need to insert something without creating an object with useless properties previously.

  3. The 'Operations' class extends PDO, the way of working is similar to 2, but now they can be directly accessed when I create the database connection, not depending of other objects.

I'm leaning towards the first option because I think, for the most part, that it will satisfy everything I'll do with this website, again the website is already coded but procedurally, which has been a mess to maintain, so basically I need to re-do things but OO.

CMSs or already coded wrappers aside (the purpose of doing this is to learn PDO and getting used to OOP), which would be the best way to do that? not limited to the options I mentioned.

Here's the 'Operations' class I've managed to code so far, where I've been doing tests sandbox-like, don't mind the spanish variable names. Advices on the code are welcome too.

class Operaciones {     
private $database;

protected $id;
protected $atributos;

protected $tabla;
protected $campos;

public function __construct($link) {
    $this->database = $link;
}

public function insertar() {
    if (!$this->verificarCamposNulos($this->atributos, $this->campos))
        echo 'Campos nulos<br />';
    else {
        $this->prepararCampos();
        $placeholders = $this->generarPlaceholders();           

        $stmt = $this->database->prepare("INSERT INTO {$this->tabla} ({$this->campos}) VALUES ({$placeholders})");

        $valores = array_values($this->atributos);
        $stmt->execute($valores);

        $stmt = NULL;           
        echo 'Se ha insertado exitosamente';
    }
}

public function modificar() {
    if (!$this->verificarCamposNulos() || empty($this->id))
        echo 'Campos nulos<br />';
    else {
        $this->prepararCampos('=?');                        

        $stmt = $this->database->prepare("UPDATE {$this->tabla} SET {$this->campos} WHERE id = {$this->id}");

        $valores = array_values($this->atributos);
        $stmt->execute($valores);

        $stmt = NULL;           
        echo 'Se ha modificado exitosamente';           
    }
}

private function generarPlaceholders() {
    for($i=0;$i<count($this->atributos);$i++) 
        $qmarks[$i] = '?';

    return implode(',', $qmarks);
}

// Check if the values to be inserted are NULL, depending on the field format given
private function verificarCamposNulos() {
    $n_campos = explode(',', $this->campos);

    $valores = array_values($this->atributos);

    foreach($n_campos as $i => $result) {       
        if (strstr($result, '@'))           
            if (empty($valores[$i]))
                return false;
    }

    return true;
}   

// Removes the '@' from each field, used to check which fields are NOT NULL in mysql
private function prepararCampos($sufijo = NULL) {
    $n_campos = explode(',', $this->campos);

    foreach($n_campos as $i => $result)         
        $n_campos[$i] = str_replace('@', '', $result) . $sufijo;

    $this->campos = implode(',', $n_campos);
}
}
  • 写回答

0条回答 默认 最新

    报告相同问题?

    悬赏问题

    • ¥15 下图接收小电路,谁知道原理
    • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
    • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
    • ¥15 手机接入宽带网线,如何释放宽带全部速度
    • ¥30 关于#r语言#的问题:如何对R语言中mfgarch包中构建的garch-midas模型进行样本内长期波动率预测和样本外长期波动率预测
    • ¥15 ETLCloud 处理json多层级问题
    • ¥15 matlab中使用gurobi时报错
    • ¥15 这个主板怎么能扩出一两个sata口
    • ¥15 不是,这到底错哪儿了😭
    • ¥15 2020长安杯与连接网探