Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Classes with basic data and then more, and more data - loading partially?

I really have no idea what to title this so someone PLEASE feel free to edit once you get my drift...

For my example, we have user and book classes.

Each user is one line in our user_data table, each book one line in our book_data table, and each user's collection can be queried from the one-to-many user_book_collection table.

When I load a user object, I am certain I want all the basic data (name, age, location) but I may or may not want to know the user's book collection. I probably don't want to know all the basic data for each book in that collection, but occasionally I might.

But I want all of this available if need be...

RELATIONSHIP MAP

User
  |-- name
  |-- age
  |-- location
  |-- book collection (ARRAY)
        |-- Great Gatsby
        |-- Grapes of Wrath
        |-- Catch-22
        |-- Huckleberry Finn
              |-- author
              |-- edition
              |-- publisher
              |-- price

My current approach is to load the first "tier" of data via the user's constructor. And then if I need to know his collection for something, I have a method pair like this:

public function getBookCollection() {
    if (empty($this->_Books)) {
        self::loadBookCollection();
    }
    return $this->_Books;
}

private function loadBookCollection() {
    // query dbase with user's ID
    // load results into $this->_Books array
}

The empty() check is to avoid repetitive trips to the database to get data for the $_Books array by different methods in the class.

I figured this was better than loading the entire massive tree of data whenever I want to just initialize a user object...

This is a simple example, but I think it's clear enough.

My questions are:

1) is this the normal way of handling such things? I can imagine situations where this sort of data overlap could just go on and on and on...

2) is there a better way?

Thank you, and someone please take a crack at my title!

like image 653
Drew Avatar asked Apr 10 '26 05:04

Drew


1 Answers

What you're doing is generally called "Lazy Loading" or "Lazy Initialization" and is a commonly used programming design to help increase performance by delaying the loading of data until your program needs it (if it does at all). So yes, you're doing it in a sane fashion ;)

like image 199
jprofitt Avatar answered Apr 11 '26 19:04

jprofitt