【发布时间】:2014-08-01 03:09:03
【问题描述】:
我正在用 PHP 构建一个 Web 应用程序。通常,对象将与数据库中的特定行相关。我想编写一些类来允许操作这些行。以这个为例:
编辑:我认为这总结了我正在尝试做的事情,只是在 PHP http://martinfowler.com/eaaCatalog/dataMapper.html 中寻找一个实际的例子@
// Create a new company record in the database
$data = array(
'name' => 'My Test Company';
);
try {
$companyId = Company_Common::create($data);
} catch (Exception $e) {
exit('Error: ' . $e->getMessage() . "\n");
}
// Load the record from the database
try {
$company = new Company($companyId);
} catch (Exception $e) {
exit('Error: ' . $e->getMessage() . "\n");
}
// Rename the company
$company->name = 'Company Name New';
$company->save();
class Company_Common {
function create($data) {
// add code here to check required fields, insert company record into database, then return row id
}
}
class Company {
public function __construct($id) {
// add code here to load database row from company table based on id
// throw exception if id not found in database table
if (mysql_num_rows($result) < 1) { // something like this depending on database
throw new Exception('Company Not Found');
}
// dynamically set properties from database row
$row = mysql_fetch_assoc($result);
foreach($row as $key => $value) {
$this->{$key} = $value;
$this->original->{$key} = $value;
}
}
function save() {
// load another copy from database
$original = new Company($this->id);
// add code here to compare $this with $original, build update query, and update any fields that have changed
}
function delete() {
// add code here to delete company record from database
}
}
除此之外,上面的类将包括 getContactIds 之类的函数,它会根据公司 ID 从联系人表中检索一堆行 ID。
我真的只是在获得一些关于其他人对这种方法的看法的反馈,以及应该或可以以不同的方式/更有效地做些什么。谢谢。
【问题讨论】:
-
你可以使用 PDO_FETCH_OBJ
-
您应该考虑停止使用已弃用的 mysql_* 函数,特别是因为与 mysql 相比,PDO 提供了如此多的乐趣。还有更多的oop