使用来自其他类的方法将对象保存到数据库

时间:2016-12-27 23:15:35

标签: php oop

我想通过使用QueryBuilder.php中的$furniture1方法将Product类的实例(例如save();)保存到数据库。有没有办法将对象传递给它?

是否有可能或有更好的方法吗?

QueryBuilder.php

class QueryBuilder {

  /**
   * @var PDO $pdo
   */
  protected $pdo;

  /**
   * Create a new query instance
   *
   * @param PDO $pdo
   */
  public function __construct($pdo) {
    $this->pdo = $pdo;
  }

  /**
   * Save object to database
   */
  public function save($obj, $table) {
    // gets an associative array
    $variables = get_object_vars($obj);

    // arrays
    $columns = [];
    $placeholders = [];
    $bindings = [];

    // loop through variables and build arrays
    foreach ($variables as $column => $value) {
      $columns[] = $column;
      $placeholder = ':' . $column;
      $placeholders[] = $placeholder;
      $bindings[$placeholder] = $value;
    }

      // create strings
    $columnString = implode(',', $columns);
    $placeholderString = implode(',', $placeholders);

    // prepare query
    try {
      $sql = "INSERT INTO " . $table . " (" . $columnString  . ") VALUES (" . $placeholderString  . ")";
      $query = $this->pdo->prepare($sql);
      $query->execute($bindings);
    } catch(PDOException $e) {
      return $e;
    }
  }

}

对象属性的var_dump:

array (size=6)
  'material' => string 'wood' (length=4)
  'id' => null
  'type' => string 'Furniture' (length=9)
  'title' => string 'Desk' (length=4)
  'price' => float 199.99
  'size' => string '200x100x100 cm' (length=14)

修改

var_dump($variables);var_dump($columnString);var_dump($placeholderString);返回:

QueryBuilder.php:81:
array (size=0)
  empty
QueryBuilder.php:82:string '' (length=0)
QueryBuilder.php:83:string '' (length=0)

1 个答案:

答案 0 :(得分:2)

根据您在注释中发布的错误,问题是您的数据库架构中有一个未添加到sql查询的字段。

对象属性很可能受到保护,而get_object_vars()仅返回可见属性。