Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Random object per page request with SilverStripe

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?

like image 841
munomono Avatar asked Apr 03 '13 20:04

munomono


2 Answers

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.

like image 67
Terje D. Avatar answered Oct 10 '22 00:10

Terje D.


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;
    }
}
like image 1
3dgoo Avatar answered Oct 10 '22 00:10

3dgoo