Point system class and db

Not for 'how-to' coding questions but PHP theory instead, this forum is here for those of us who wish to learn about design aspects of programming with PHP.

Moderator: General Moderators

Post Reply
pinehead
Forum Newbie
Posts: 14
Joined: Sat Oct 13, 2012 11:51 am

Point system class and db

Post by pinehead »

I'm designgin a point system for my app. Basically whenever an "action" takes place I'd like to call the class that adds points to their db.
such as $achievement->completed_task('task_name')

and have points added based off task_name.

So two questions, how would you suggest handling this in the db? increase a row per action completed with the number of points they received then for their score add all the rows? That way actions/points can be tracked/logged?


For the class i was thinking it might go something like this.. Thouhts?

Code: Select all

class Achievements {

  public function completed_task($task) {
    case($task)
         scored:
             +15pts
         break;
         quit:
           -10pts
         break; 
}  

}

Thoughts?

Thanks,
User avatar
requinix
Spammer :|
Posts: 6617
Joined: Wed Oct 15, 2008 2:35 am
Location: WA, USA

Re: Point system class and db

Post by requinix »

It's okay to break normalization a bit for things like post counts or user points. If you want a log of activity then keep that, but you can update a field in a table with the new value too. So yes the number of points is actually stored in two places.

But I wouldn't put in code the number of points for a task. Store that in the database too. You can even store a date range for each row, allowing you to change the number of points for a task for some time (eg, a special bonus).
User avatar
Christopher
Site Administrator
Posts: 13596
Joined: Wed Aug 25, 2004 7:54 pm
Location: New York, NY, US

Re: Point system class and db

Post by Christopher »

pinehead wrote:So two questions, how would you suggest handling this in the db? increase a row per action completed with the number of points they received then for their score add all the rows? That way actions/points can be tracked/logged?
The way you have shown it, it looks like the points are kept in the same place. So a single record per user might be fine. Do you need to track the history of scores or just their current score?

Also, unless this class also defines the list of tasks then I would prefer a method per task like:

Code: Select all

class Achievements {
  protected $db;
  protected $userId;

  public function __construct($db, $userId) {
         $this->db = $db;
         $this->userId = $userId;
  }

  public function completedScored() {
         $this->db->query("UPDATE scores SET score=score+15 WHERE id='{$this->userId}'");
  }

  public function completedQuit() {
         $this->db->query("UPDATE scores SET score=score-10 WHERE id='{$this->userId}'");
  }

}
(#10850)
Post Reply