0

In one of my extbase models, I want to initialize some properties derived from the properties that are saved in the database. The computation of these virtual properties is time consuming, so I'd like to cache them. Thus my program flow should look somehow like this:

  1. Load the domain object as usual from the database
  2. Check if the virtual property is available in cache. If so, fetch it from there, otherwise compute and cache it.

I first thought the method "initializeObject" is what I need, but it is not: It is called before any property is initialized from the database. So I came up with two other ways:

  1. I can call an initialization-method manually from the repository after fetching the object, but that seems weird and would break if someone adds another find* method to the general repository.
  2. Another idea is to add a boolean "virtualPropertiesInitialized" to the model, query it whenever one of the virtual properties is accessed and initialize the virtual properties if needed. Also seems weird, but would not break if someone adds another "find"-method to the generic repository.

My question is:

Is there a default/best-practice how to do what I want to do?

Jost
  • 5,948
  • 8
  • 42
  • 72

1 Answers1

1

If reading the final value from disk or database is less computationally intensive, then store the value using the TYPO3 caching framework or by your own caching method of a static class and restore it in the getter of the virtual property. Doing it in the getter method public mixed getYourPropery() will give you the feature that the value is only get from the cache when you call it.

On the second call, just return the value you stored previously:

private $myValue = NULL;

public function getMyValue() {
    if($this->myValue != NULL) return $this->myValue;

    $this->myValue = "test";
    return $this->myValue;
}
Merec
  • 2,751
  • 1
  • 14
  • 21
  • That's about the same thing I proposed as second solution above (with the flag). The flag is needed to prevent the caching framework from generating a SQL query every time the cache status is queried, which would result in many SQL queries per page rendering. I think I'll leave it at that for now, unless points me to a better way. – Jost Nov 24 '13 at 23:01
  • Instead of defining a property like ``virtualPropertiesInitialized``, I would add a member variable that holds the value. If this value is null, get from cache, else return the holder. I will append this to my answwer. – Merec Nov 24 '13 at 23:09
  • Thats a good way to reuse the property as flag, but won't work in my case: The property might be `null`. – Jost Nov 24 '13 at 23:49