Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Object-relational mapping: What's the best way to implement getters?

Tags:

oop

php

orm

mapping

What should happen when I call $user->get_email_address()?

Option 1: Pull the email address from the database on demand

public function get_email_address() {
    if (!$this->email_address) {
        $this->read_from_database('email_address');
    }
    return $this->email_address;
}

Option 2: Pull the email address (and the other User attributes) from the database on object creation

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?

like image 682
Tom Lehman Avatar asked Dec 08 '22 09:12

Tom Lehman


1 Answers

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.

like image 173
Dylan Beattie Avatar answered Mar 13 '23 17:03

Dylan Beattie