簡體   English   中英

在多個表中將相同的元數據插入相同的列時,如何減少重復代碼?

[英]How do I reduce repetitive code when inserting the same metadata into identical columns over multiple tables?

我的目標:

  • 遵循數據庫規范化。
  • 能夠跟蹤表格中的變化。
  • 能夠從給定時間點恢復我的數據庫狀態,例如上個月。
  • 分離處理數據的代碼,以便輸入可以來自HTML表單或另一種語言的腳本(Ruby / perl)。

為了實現這一點,我選擇了像這個答案中描述的數據庫設計:

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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM