php – 在多个表中将相同的元数据插入相同的列时,如何减少重复代
我的目标:
>遵循数据库规范化. 为了实现这一点,我选择了像这个答案中描述的数据库设计: StackOverflow: Is there a MySQL option/feature to track history of changes to records? 但是,当用户更新多个字段时,必须将相同的元数据插入到包含相同列的多个表中,并且我的代码变得重复. 例: 用户通过HTML表单提交数据. 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,$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,$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']); ?> (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |