tags:

views:

38

answers:

3

I have created a basic class for a customer.

I haven't done this before and want to know the best way to access the data.

Should I have a get() method for every field in the customer array or should I simply pass the customer array back and access with the page.

i.e. Just return the array

class Customer {

  protected $id;
  protected $customer;

  public function __construct($customer_id) {
    $this->id = $customer_id;
    $this->set_customer();
  }

  protected function set_customer() {
    $query = mysql_query("SELECT * FROM customer WHERE id = '$this->id'");
    $this->customer = mysql_fetch_row($query);
  }

  public function get_customer() {
    return $this->customer;
  }
}

versus create a method for each item in the array

class Customer {

  protected $id;
  protected $customer;

  public function __construct($customer_id) {
    $this->id = $customer_id;
    $this->set_customer();
  }

  protected function set_customer() {
    $query = mysql_query("SELECT * FROM customer WHERE id = '$this->id'");
    $this->customer = mysql_fetch_row($query);
  }

  public function get_customer_name() {
    return $this->customer->customer_name;
  }

  ...

  ...
}

versus option 3 based on Tobias' feedback: (not sure if syntax is correct)

class Customer {

  protected $id;
  protected $customer;

  public function __construct($customer_id) {
    $this->id = $customer_id;
    return $this->set_customer();
  }

  protected function set_customer() {
    $query = mysql_query("SELECT * FROM customer WHERE id = '$this->id'");
    return mysql_fetch_row($query);
  }
}
A: 

have the set function return the data by default - no harm done if you always use the data right after.

Tobias
Tobias, being a class newbie, can I achieve what your suggesting by just changing the following lines?old: $this->set_customer();new: return $this->set_customer();ANDold: $this->customer = mysql_fetch_row($query);new: return mysql_fetch_row($query);
php-b-grader
yep, that should work :)
Tobias
A: 

In my view the later approach is better, you get all info about the customer from within the class unlike the first approach where you just return the customer row and there by using that row all around your project to get more details of the customer.

Sarfraz
A: 

I'd say it's best to just return an array of all data instead of just making logic for every field. It will probably happen often that you need more then one field, and calling different methods for that will be annoying.

Younes