Random Page Request Using SilverStripe

Suppose you show a request for an arbitrary application for a page and use a function to return a random object, for example:

Statement::get()->sort("RAND()")->limit("1"); 

But now in the template you want to refer to it twice in different places, but it should be the same operator, but not random. How can you get the same random page request?

+6
source share
2 answers

How to define a function with a static variable that remembers an 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.

+4
source

One way to do this is to get a random instruction in the init controller function and assign it to a private variable. We add the getRandomStatement function to retrieve a random instruction:

 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; } } 
+1
source

All Articles