If I want to get a customer’s email address from a database, the following is bad, because $row will contain an element for every single field in the customer table:
$result = mysqli_query ('SELECT * FROM customer WHERE custid = 1');
$row = mysqli_fetch_array ($result, MYSQLI_ASSOC);
This is considered better, because $row will contain a single element for the email address, which is all we need:
$result = mysqli_query ('SELECT email FROM customer WHERE custid = 1');
$row = mysqli_fetch_array ($result, MYSQLI_ASSOC);
I am trying to apply the same logic to objects. If a “customer” object has say 50 properties/fields, is it common to populate all 50 properties when you only need to access one?
Below is a basic example of a customer class and object which is resource hungry if all we want to do is get a customer’s email address, and not all their other details (in this example a “customer” object has 5 properties but in reality there could be many more):
class Customer {
private $custid;
private $firstname;
private $lastname;
private $email;
private $dateadded;
public function getCustomer ($id) {
$result = mysql_queryi ('SELECT * FROM customer WHERE custid = ' . $id);
$row = mysqli_fetch_array ($result, MYSQLI_ASSOC);
foreach ($row as $key => $value) {
if (isset ($this->$key)) {
$this->$key = $value;
}
}
}
}
$customer = new Customer ();
$customer->getCustomer (1); // All I wanted is the email address, but now I have everything :-(
You could make a second argument to your
getCustomerfunction that accepts an array of fields to queryUsage
Bonus:
I’d recommend storing your fields a little differently in your model
This way you can get rid of all the statically defined instance variables; e.g.,
private $custid;,private $firstname;,private ...Instead, all fields will be stored in
$this->_dataprivate associative array.What’s sweet about this is you don’t even have to change the way your
getCustomerfunction is written.Learn more about PHP magic methods