March 20, 2012

Refer a friend functionallity for a website in OOP

Question by JamesG

I am trying to get to grips with OOP, and just want a little advice on how to approach a problem.

I am making a refer a freind system on my online shop, so when a user registers they will enter an email address of a friend that refered them. This already existing friend then gets a certain amount of points (currency) in their online account.

I have made most of my system just using functions and procedural programming in PHP, but was wondering if anyone could point me in the right direction to making the refer a friend system in OOP, or even if it is worth building in OOP?

I do understand the basic principles of OOP, but not quite sure how to fully build a program from start to finish using it.

Answer by Starx

Ok, this is what i would do

Class User {
    // ....

    public function newUser(array $params, $isRefer = false, $referal = null) {
             // $params Parameters for new user, like name, address etc
             // $isRefer boolean value to trigger referal
             // $referal Email of the referer
        $newUser = new user_model($params); 
             //Create a DBO of user, as per the new parameters
        if(isReferal) { $referer = $this -> getUserIdByEmail($referal); } 
            //If is referal, get his id, based on email
        $status = $this -> add($newUser); //Add the user
            //Add the user
        if($status) {
             //Once it is success
             $referer = new User($referer); //Create a object of referer
             $referer -> addPoints(50); // Give bonus point

        }
        return true; //Indicate the success
    }

    public fucntion __construct($id = null) {
        if($id) {
           //create the object
           $this -> id = $id;
        }
        // ....
    }

    protected function getUserIdByEmail($email) {
        //get the id
        return $id;
    }

    protected function addPoints($points) {
        //add the points on database table
        return true;
    }
}

The DBO class might be something similar to this

class UserDBO {
   protected $name;
   protected $address;

   public function __construct(array $params) {
      $this -> name = $params['name'];
      $this -> address = $params['address'];
   }

}

Usage:

$userObj = new User();
$userObj -> newUser(array("name", address"), true, "referal@email.com");

Author: Nabin Nepal (Starx)

Hello, I am Nabin Nepal and you can call me Starx. This is my blog where write about my life and my involvements. I am a Software Developer, A Cyclist and a Realist. I hope you will find my blog interesting. Follow me on Google+

...

Please fill the form - I will response as fast as I can!