Best Practice for Like Functionality

I work on a flash games site. I have two models: Game and User and an intermediate table in which I perform user actions, for example: "User 1 loves game 3".

  • Where is the best place for my favorite feature?
  • Is it good to use the current user ID in the Game model ? or should I pass it as a parameter?

For performance reasons, I am increasing the number of fields in the game table. Ive missed checking if the user already loves the game, just to make it simple.
Here are my options:

First version:

$user->like(12345);

class User  
{
  public function like($game_id)
  {
    $like = new User_Game();  
    $like->user_id = $this->id;  
    $like->game_id = $game_id;  
    $like->save();  

    $obj = new Game($game_id);  
    $obj->likes++;  
    $obj->save();  
  }
}  

Second version:

$game->like(); // by current user

class Game  
{  
  public function like()  
  {

    $like = new User_Game();    
    $like->user_id = $_SESSION[β€˜user_id’];    
    $like->game_id = $this->id;    
    $like->save();   

    $this->likes++;    
    $this->save();    
  }    
}    
+5
source share
1

, , . , codereview . , , " ". , , .
, , ASAP , , , .

, MVC-ish, . Game id 123456. fillGameModel(Game $gameInstance). Game . User. : likeGame(Game $game, User $user). .
, . OO-:

//controller:
$user = new User();
$user->setId($_SESSION['user_id']);
$game = new Game();
$game->setId(123456);//wherever you get this from
$service = new MainService();
$service->userLikes($game,$user);

//service:
public function userLikes(Game $game, User $user)
{
    $user = $this->_completeUser($user);
    $game = $this->_completeGame($game);
    //insert or update whatever data you need...
}

protected function _completeUser(User $user)
{
    $db = $this->_getConnection();//asuming PDO, to keep things simple
    $query = 'SELECT * FROM my_db.users WHERE id = ?';
    $stmt = $db->prepare($query);
    $row = $stmt->fetch(PDO::FETCH_ASSOC);
    foreach ($row as $field => $value)
    {//this implies getters and setters in your model
        $user->{'set'.ucfirst(strtolower($field))}($value);
    }
    return $user;
}

protected function _completeGame(Game $game)
{
    $db = $this->_getConnection();
    $query = 'SELECT * FROM my_db.games WHERE id = ?';
    $stmt = $db->prepare($query);
    $row = $stmt->fetch(PDO::FETCH_ASSOC);
    foreach ($row as $field => $value)
    {//field id becomes "setId" method, field name "setName" etc...
        $game->{'set'.ucfirst(strtolower($field))}($value);
    }
    return $game;
}

//just for show: a pseudo-overloader method, if your models all share the same
//abstract class. 
protected function _completeAny(Model_Abstract $model)
{
    $modelName = get_class($model);
    if (method_exists($this,'_complete'.$modelName))
    {
        return $this->{'_complete'.$modelName}($model);
    }
    throw new Exception('No completion method for '.$modelName.' found');
}

, , . , ; -)

+1

All Articles