$user->get_email_address()
?public function get_email_address() {
if (!$this->email_address) {
$this->read_from_database('email_address');
}
return $this->email_address;
}
public function __construct(..., $id = 0) {
if ($id) {
$this->load_all_data_from_db($id);
}
}
public function get_email_address() {
return $this->email_address;
}
My basic question is whether it's best to minimize the number of database queries, or whether it's best to minimize the amount of data that gets transferred from the database.
Another possibility is that it's best to load the attributes that you'll need the most / contain the least data at object creation and everything else on demand.
A follow-up question: What do ORM abstraction frameworks like Activerecord do?
There really isn't a correct answer for this. Depends on how many users you're loading at once, how many text/blob fields are in your User table, whether your user table loads any associated child objects. As aaronjensen says, this pattern is called lazy loading - and the opposite behaviour (loading everything up front just in case you need it) is known as eager loading.
That said, there is a third option you might want to consider, which is lazy-loading the entire User object when any of its properties are accessed:
public function get_email_address() {
if (!$this->email_address) {
$this->load_all_data_from_db($this->id)
}
return $this->email_address;
}
Advantages of this approach are that you can create a collection of users (e.g. a list of all users whose passwords are blank, maybe?) based on their IDs only, without the memory hit of fully loading every single user, but then you only require a single database call for each user to populate the rest of the user fields.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With