over 4 years ago

Here's the canonical method of lazy loading object attribute.

The point of lazy loading is when some attribute of an object is another object, and its construction is costly. As the result, we don't want to create this another object at the time of creating the parent object. Only at the time when we really need this object.


class Lazyloader
  private $huge;
  public function getHuge()
    if (!$this->huge)
      $this->huge = $this->makeHuge();

    return $this->huge;
  public function makeHuge()
    // ... actual creation of the child object ...

It's not Haskell, of course, but this idiom is quite simple and more importantly, you can add lazyloading to any attribute, even already existing.

comments powered by Disqus