Best practice for re-using active record?

What is the best/recommended practice to “cache” DAO queries or more important active records for the duration of the request/connection? Is there a build-in solution to check if an active record was already loaded? I’m not talking about a persistent cache. I’m looking for a good way to reuse a previously found active record in a different context (eg. a related model) instead of making the same database query again. Maybe a global accessible array etc…

Simple Example:

Controller loads AR "User" for validation then saves data to AR "Post" including a behavior which updates AR "User" after save.

How would you "pass" the active record "User" from the controller without losing the reusability of a model?

Thank you!

There’s no built-in support for this feature, probably because:

  1. It’s difficult to implement well.

  2. Most web applications simply don’t need it, as it’s very unlikely that active records need to be reused in a different context on the same request.

If you think you can make use of this feature in your application frequently, you may consider to integrate an ORM that implements Identity Map pattern (Propel, Doctrine).

Thank you for your reply. Identity Map might be a bit too much though.

But I have come across several situations where I need to load an active record for example in access control (controller) and need to use the same record later in a behavior or related model. Sure, I could just pass the object to the model but that doesn’t make much sense in the big picture (web services, re-usability of models, etc.). I thought of a simple active record extension (behavior?) which checks some sort of data array before performing an actual query on find(). Maybe?

Anyone?

The common pattern you will find a lot throughout the framework is like this (i call it "Cheap Cache" in lack of a better name):




// If null is a valid property value, add "=false;" (or other) 

// and check for that value below instead.

private $_someVar;


public getSomeVar() {

  if ($this->_someVar===null) {

      $this->_someVar=...your code here ...

  }

  return $this->_someVar;

}

So $object->someVar will be a property that is evaluated on first access and cached for the lifetime of the object. It’s your job, to find the right place for this pattern, since every application is different. Common places where i use this: Current controller, base controller, my custom WebUser and of course any model.