Dependency of database fields
I currently have this method:
public function getUser($id) {
$user = $this->db->getSingleRecord("SELECT user_id, user_login, user_email FROM users WHERE user_id = ?", $id);
return $user;
}
I think it's pretty obvious what this does. $user is an associative array, so $user['user_id'], $user['user_login'] and $user['user_email'] will exist. This will be passed to a Smarty template and in that file, these keys will be used:
login: {$user['user_login']|escape} <br />
This made me wondering... is this fine? If the database field changes, I would need to edit 2 files now. I could change the method to something like this:
public function getUser($id) {
$user = $this->db->getSingleRecord("SELECT user_id, user_login, user_email FROM users WHERE user_id = ?", $id);
if (empty($user))
// return empty array
return $user;
else
return array('user_id' => $user['user_id'开发者_运维问答], 'user_login' => $user['user_login'], 'user_email' => $user['user_email']);
}
If the database field changes, I would only need to edit one file (this method) now. My first thought is that this approach is much better.
On the other hand, should you really take care of these things? Normally, you don't change these fields.
What is the best approach for this?
Thanks
Consider the correspondence of database fields and $user
structure required by the template a coincidence. Use the one you currently use. If the database schema changes, switch to the alternative one (you will have to modify the method anyway, to change the query).
精彩评论