Back

Attribute "persistence" in models


guestisp posted 2 weeks ago

Let's assume a model with one accessor:

public function getMyAttributeValue($value) {
   <my code>
}

<mycode> is evaluated every time I access the attribute with MyModel->my_attribute

Would be possible to make this persistent? I have some accessors that make slow operations and I don't want to run these operations every time. In example, a json parsing:

public function getMyAttributeValue($value) {
   $x = json_decode($value)
   foreach ( $x as $y ) {
      do some code with $y
   }

   return "result from code above"
}

i would like to directly return the "result from code above" after the first accessor call. Is this possible ?

Should I define an ad-hoc method like doMyOperation() that will directly set the value for my_attribute ?

Firtzberg replied 1 week ago

Hi,

can you just add the calculaed value as new member to the object?

public function getMyAttributeValue($value) {
   $x = json_decode($value)
   foreach ( $x as $y ) {
      do some code with $y
   }

   $this->my_attribute = $result;
   return $result;
}

Sign in to participate in this thread!



We'd like to thank these amazing companies for supporting us