2

I'm making repeated calls to a few related object instances, and I need to cache them in memory.

If I have an array of objects, like:

array('object_a' => $obj_a, 'object_b' => $obj_b);

I want to do something like:

$obj_a = getmyobj('object_a');

Where the object is created if it doesn't exist in memory already.

1

You can use drupal_static to store an array of object.

You can then define a method, lets call it 'getmyobj', to get your data like this :

function getmyobj($obj_name) {
  $objects = &drupal_static(__FUNCTION__);

  if (! isset ($objects[$obj_name])) {
    // Here you load your obejct
    $objects[$obj_name] = method_to_load_your_object($obj_name);
  }
  return $objects[$obj_name];
}

Then you will be able to get you object with the above code :

$obj_a = getmyobj('object_a');

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.