NotionCommotion Posted November 4, 2016 Share Posted November 4, 2016 I have a bunch of sub classes which extend a base class. In the base class, I was planning on including a method updateValue($name, $value, $primaryKey) which would update the column specified by $name with the value $value for the primary key $primaryKey. Some column names are allowed to be changed for all sub classes, yet others are only allowed to be changed for some of the sub classes. Also, some column names might have unique requirements for all of the sub classes or even just some of them. I will definitely need to whitelist them. Any recommended design patterns to implement this? Quote Link to comment https://forums.phpfreaks.com/topic/302463-recommended-design-pattern-for-updating-namevalues/ Share on other sites More sharing options...
ginerjm Posted November 4, 2016 Share Posted November 4, 2016 Off the wall suggestion, since I'm not a class-y kind of guy. How about using the get_class() function to get the current object's class name and use that as a key to a 2D array of allowable column names? If the column name is in the array under that classname key, it's a go. Quote Link to comment https://forums.phpfreaks.com/topic/302463-recommended-design-pattern-for-updating-namevalues/#findComment-1538938 Share on other sites More sharing options...
NotionCommotion Posted November 4, 2016 Author Share Posted November 4, 2016 Thanks ginerjm, This is what I ended up doing. See any concerns? public function updateParam($params) { $rs=$this->sanitize($params,['name','value']); if($rs->error) { $rsp=\MyApp\ErrorResponse::missingValue($rs->error); } elseif ($method=$this->getUpdateMethod($rs->data['name'])) { try { $sql="UPDATE $method[table] SET $method[column]=? WHERE id=? AND accounts_id=?"; $stmt = $this->pdo->prepare($sql); $stmt->execute([$rs->data['value'],$this->id,$this->account->id]); $rsp=[null,204]; } catch(\PDOException $e){ switch($e->getCode()) { case 23000: $rsp=\MyApp\ErrorResponse::duplicatedName(); break; default: $rsp=\MyApp\ErrorResponse::customError($e->getMessage()); } } } else { $rsp=\MyApp\ErrorResponse::customError('Invalid column '.$rs->data['name']); } return $rsp; } protected function getUpdateMethod($name) { return [ 'name'=>['column'=>'name','table'=>'items'], 'price'=>['column'=>'unit_price','table'=>'items'], 'code'=>['column'=>'code','table'=>'codes'], ][$name]; } Quote Link to comment https://forums.phpfreaks.com/topic/302463-recommended-design-pattern-for-updating-namevalues/#findComment-1538944 Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.