Lets say you show a random statement per page request and use a function to return a random object like:
Statement::get()->sort("RAND()")->limit("1");
But now in the template you want to reference it twice in different places but it should be the same statement and not a randomly different one. How would you make sure to get the same random object per page request?
What about defining a function with a static variable that remembers the object?
public function rndObj() {
static $obj = null;
if(!isset($obj)){
$obj = Statement::get()->sort("RAND()")->limit("1")->first();
}
return $obj;
}
and then use rndObj
in the template.
One way to do this is to fetch the random statement in the controller init
function and assign this to a private variable. We add a getRandomStatement function to fetch the random statement:
class Page_Controller extends ContentController {
private $randomStatement;
public function init() {
parent::init();
$this->randomStatement = Statement::get()->sort('RAND()')->limit(1)->first();
}
public function getRandomStatement() {
return $this->randomStatement;
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With