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);
}
}
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.
have the set function return the data by default - no harm done if you always use the data right after.
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.
The nice thing about having get_ and set_ methods is that you can make the class smarter. The view coder using your class can't set_ a variable to an invalid value, because the class knows what a valid value is and can return an error. You can add a valid_ method for each field to allow the view coder to see if the result is valid. You end up with better, more consistent data.
精彩评论