$object = new myClass($name(;
如果我使用"new"在应用程序中创建一个新对象以保存到数据库,那么我应该使用什么方法从数据库中检索现有对象?
是否有处理真正新对象与从数据库中获取现有对象的标准过程?
编辑:
拥有一个根据参数更改的构造函数会是一个坏主意吗?
即
__construct($param) {
if(is_numeric($param)) {
// get existing data from DB
} else {
// set name for new object
$this->name = $param;
}
}
通常,您需要一个集合类来实例化新对象。
因为每条记录一个数据库查询是浪费的。
因此,您将拥有一个模拟数据库记录的类和一个模拟记录列表的类。
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)
}
}