views:

114

answers:

3

hi everybody, i've been creating functions for too long without taking my code to 'classes'.

I learn well through example and I just wanted to convert this simple function into a class so I can compare something I know with something I don't...

Take the following function:

function affiliateName($affiliateID) {

$sql = 'SELECT * FROM affiliates WHERE uID="' . $affiliateID . '" ';

$res = mysql_query($sql);

$row = mysql_fetch_array($res);

$affiliateName = $row['firstName'] . ' ' . $row['lastName'];

return $affiliateName;

}

And how would I make that a class?

+3  A: 
<?php
class AffiliateModel
{
    public function first($id)
    {
        $sql = 'SELECT *, CONCAT(firstName, ' ', lastName) AS qualifiedName FROM affiliates WHERE uID="' . $id . '" LIMIT 1';
        $res = mysql_query($sql);

        return mysql_fetch_object($res);
    }
}

$model = new AffiliateModel();
$a = $model->first($id);
echo $a->qualifiedName;
?>
w35l3y
+2  A: 

Hope it helps

<?php
class affiliate{

  // fields or properties
  public $name = '';
  public $id = 0;

  // constructor
  public function affiliate($id = 0){
     $this->set_ID($id);
  }

  // methods
  public function set_ID($id){
    return $this->id = $id;
  }

  public function get_Name(){

    if($this->name != ""){
      $sql = 'SELECT * FROM affiliates WHERE uID="' . $this->id . '" ';
      $res = mysql_query($sql);
      $row = mysql_fetch_array($res);
      return $this->name = $row['firstName'] . ' ' . $row['lastName'];
    }else{
      return $this->name;
    }
  }
}

// Example:

  $currentAffiliate = new affiliate(153);
  echo $currentAffiliate->name;
?>
thephpdeveloper
Thanks Mauris.
cosmicbdog
no problem! at all!
thephpdeveloper
+1  A: 

I prefer the following design as it is the simplest to use:

class affiliates {
    static function load($id) {
        return new self(intval($id));
    }
    private function __construct($id) {
        $query = "SELECT * FROM affiliates WHERE id = " . intval($id);
        $result = mysql_query($query);
        // TODO: make sure query worked
        foreach(mysql_fetch_assoc($result) as $field => $value)
            $this->$field = $value;
    }
    // composite fields - made by combining and/or re-formatting other fields
    function qualifiedName() {
        return $this->firstName . ' ' . $this->lastName;
    }
    function properName() {
        return $this->lastName . ', ' . $this->firstName;
    }
}

$a = affiliates::load(22);
// all db fields are available as properties:
echo $a->id; // 22
echo $a->firstName; // Fred
echo $a->lastName; // Smith
// composite fields are methods
echo $a->qualifiedName(); // Fred Smith
echo $a->properName(); // Smith, Fred
// to get a single field from a particular person
echo affiliates::load(72)->qualifiedName();
too much php