0

$object = new myClass($name);

如果我使用“new”在应用程序中创建一个新对象以保存到数据库,那么我使用什么方法从数据库中检索现有对象?

是否有处理真正的新对象与从数据库中获取现有对象的标准程序?

编辑:

拥有一个根据参数更改的构造函数会是一个坏主意吗?

IE

__construct($param) {
  if(is_numeric($param)) {
    // get existing data from DB
  } else {
    // set name for new object
    $this->name = $param;
  }
}
4

1 回答 1

1

通常你会想要一个 Collection 类来实例化你的新对象。

因为每条记录一个数据库查询是浪费的。

因此,您将拥有一个模拟数据库记录的类和一个模拟记录列表的类。

 class collection {
     protected $filters = array('ids' => array(), 'published' => true, 'name' => '');
     protected $records = array();
     public function __construct($filters) {
         // validate $filters content here
         $this->filters = array_merge($this->filters, $filters);
         $query = $this->generateQueryUsing($this->filters);
         $pdos = $pdo->query($query);

         foreach($pdos->fetch(PDO::FETCH_CLASS, 'Record', array(NULL, FALSE)) AS $item)
            $this->records[] = $item;

         foreach($pdos->fetch() AS $item)
            $this->records[] = new Record($item, FALSE); // Record::__construct($data, $is_new = TRUE)


     }
 }
于 2012-05-20T06:44:56.147 回答