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

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

Option 1: pull email from database on request

 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 other user attributes) from the database when creating the object

 public function __construct(..., $id = 0) { if ($id) { $this->load_all_data_from_db($id); } } public function get_email_address() { return $this->email_address; } 

My main question is: is it best to minimize the number of queries to the database or is it best to minimize the amount of data that is transferred from the database.

Another possibility is that it is best to load the attributes that you need most / contain the least data when creating the object and everything else on request.

The next question is: what do ORM abstraction frameworks like Activerecord do?

+4
source share
3 answers

In fact, there is no right answer for this. Depending on how many users you load right away, how many text / blob fields are in your User table, whether your user table loads any related child objects. As aaronjensen says, this template is called lazy loading , and the opposite behavior (loading everything to the forefront if you need it) is called impatient loading .

However, there is a third option that you might want to consider, which is lazy loading the entire User object when accessing any of its properties:

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

The advantages of this approach are that you can create a collection of users (for example, a list of all users whose passwords are empty, maybe?) Only based on their identifiers, without a memory patch that completely loads each individual user, but then you only need one a database call for each user to fill in the remaining user fields.

+9
source

Minimize the number of requests. The optimal number of requests is 0, but if you need to request because it is not cached, then it is 1. Requesting each property is a reliable way to a system that will never scale, has serious discussion problems and will cause more headaches than its value.

I should mention that there is value for lazy loading (which you talk about in step 1) if you are unlikely to need lazy data. If you can, but it’s best to be explicit and get exactly or almost what you need. The less time you spend on queries, the less time it takes to open a connection and the more scalable your system.

+6
source

I agree with aaronjensen, unless the amount of data you pull is so large that you start to use excessive amounts of memory. I think there are 3 text fields in the line that are big enough, and all you need is an ID field.

0
source

Source: https://habr.com/ru/post/1277464/


All Articles