[英]How do I reduce repetitive code when inserting the same metadata into identical columns over multiple tables?
我的目标:
为了实现这一点,我选择了像这个答案中描述的数据库设计:
StackOverflow:是否有MySQL选项/功能来跟踪记录更改的历史记录?
但是,当用户更新多个字段时,必须将相同的元数据插入到包含相同列的多个表中,并且我的代码变得重复。
例:
用户通过HTML表单提交数据。 在Propel ORM的帮助下,PHP处理如下数据。
function insertEvent($name, $venueId, $user, $date, $id = 0) {
//validation and formatting..
//if id == 0, new event,
//else, this is an update, archive the old database row on successful processing and maintain a common id as a parent
//...
$event = new Event();
$event->setName($name);
$event->setVenueId($venueId);
$event->setUser($user); //1
$event->setValidFrom($date); //1
$event->setValidUntil(null); //1
$event->save();
// ...
}
function insertEventPhonenumber($phonenumber, $pid, $user, $date, $id = 0) {
//...
$event_phonenumber = new EventPhonenumber();
$event_phonenumber->setPid($pid); //2
$event_phonenumber->setPhonenumber($phonenumber);
$event_phonenumber->setUser($user); //2
$event_phonenumber->setValidFrom($date); //2
$event_phonenumber->setValidUntil(null); //2
$event_phonenumber->save();
// ...
}
function insertEventArtistId($artistId, $pid, $user, $date, $id = 0) {
//...
$event_artistId = new EventArtistId();
$event_artistId->setPid($pid); //3
$event_artistId->setArtistId($artistId);
$event_artistId->setUser($user); //3
$event_artistId->setValidFrom($date); //3
$event_artistId->setValidUntil(null); //3
$event_artistId->save();
// ...
}
我的问题:
在我的完整代码中,受影响的表比示例中的三个更多。
标记为// 1,// 2和// 3,您会看到通常相同的数据输入。
在我的肚子里,我不喜欢这个。 我一直在尝试搜索引擎,例如“SQL插入查询多个表中的常用列”和措辞的变体,而没有找到与我的问题直接相关的任何内容。
这种不好的做法对我来说感觉如何吗?
如何最小化代码中的重复?
你想摆脱所有这些功能吗? 如果是这样,您可以使用call_user_func来消除大部分代码。
<?php
class MyApp {
static function insert($name, $params) {
$ob = new $name();
foreach($params as $k=>$v) {
$op = array($ob,"set".ucfirst($k));
//if (is_callable($op)) {
call_user_func($op,$v);
//}
}
$ob->save();
}
}
MyApp::insert(
"EventArtistId",
array(
"pid"=>$_REQUEST['pid'],
"artistId"=>$_REQUEST['artistId'],
"user" => $_REQUEST['user'],
"validFrom" => $_REQUEST['date'], // may need to convert date
"validUntil" => isset($_REQUEST['validUntil']) ? $_REQUEST['validUntil'] : null,
)
);
// More cool
// MyApp::insert($_REQUEST['action'],$_REQUEST['params']);
?>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.