I coded a small user script with PHP. I'm improving the script, learning from my mistakes. I recently learned about object oriented programming and wrote 2 big god classes (user class and message class). That didn't feel right, so read about the MVC model. I wrote a controller class to handle the big god classes while being easy to use in the views (I want to be able to rewrite the big god classes without rewriting the views).
This controller class allows me to streamline my big god classes, which is exactly what I wanted to achieve.
I'm replacing the method user_search()
with user_search_info()
. It should return a row of user information based on the given user_id or user_id. It should return false if the query fails or returns empty. When I am satisfied, I will delete user_search()
.
The new method works like I want it to, and I find it very elegant and easy to read. But is it the right approach? I'm sure there's still room for improvement.
This is from the user class file:
class user{
// new methods don't care about this anymore so this will get deleted
public $logs = array();
// ... irrelevant methods left out ...
// old method
public function user_search($db_connection, $user_id=null, $username=null){
$result = false;
if($user_id == null && $username == null)
$this->logs[] = "No information to search on has been found.";
elseif($db_connection == false)
$this->logs[] = "Something went wrong with the database.";
else{
$this->logs[] = "Searching the user in the database.";
$query_user_search = $db_connection->prepare('SELECT * FROM users WHERE user_username=:user_username OR user_id=:user_id');
$query_user_search->bindValue(':user_username', $username, PDO::PARAM_STR);
$query_user_search->bindValue(':user_id', $user_id, PDO::PARAM_STR);
$query_user_search->execute();
if($result = $query_user_search->fetch())
$this->logs[] = "We found the user.";
else
$this->logs[] = "We didn't find the user.";
}
return $result;
}
// new method
public function user_search_info($db_con, $user_id=null, $user_username=null){
$query_user_search_info = $db_con->prepare('SELECT * FROM users WHERE user_username=:user_username OR user_id=:user_id');
$query_user_search_info->bindValue(':user_id', $user_id, PDO::PARAM_STR);
$query_user_search_info->bindValue(':user_username', $user_username, PDO::PARAM_STR);
$query_user_search_info->execute();
return $query_user_search_info->fetch();
}
}
And this is from the controller class file:
public function return_user_search_info($search_user_variable, $search_user_value)
{
$user_search_info = false;
if($search_user_variable == "user_id")
$user_search_info = $this->user->user_search_info($this->db_con, $search_user_value, "");
elseif($search_user_variable == "user_username")
$user_search_info = $this->user->user_search_info($this->db_con, "", $search_user_value);
return $user_search_info;
}