Skip to content

Instantly share code, notes, and snippets.

@msabramo
Created March 6, 2012 17:04
Show Gist options
  • Select an option

  • Save msabramo/1987527 to your computer and use it in GitHub Desktop.

Select an option

Save msabramo/1987527 to your computer and use it in GitHub Desktop.
Playing with an abstraction for random number generators called IIntegerSource
<?php
interface IDebuggable
{
function setDebugLevel($debugLevel);
}
interface IIntegerSource
{
function __construct($min, $max);
function getInteger();
}
abstract class BaseDebuggable implements IDebuggable
{
public function setDebugLevel($debugLevel)
{
$this->debugLevel = $debugLevel;
}
protected $debugLevel = 0;
}
abstract class BaseIntegerSource
extends BaseDebuggable
implements IIntegerSource, IDebuggable
{
public function __construct($min, $max)
{
$this->min = $min;
$this->max = $max;
}
public function getInteger()
{
$integer = $this->_getInteger();
if ($this->debugLevel > 0)
{
print __FILE__ . ":" . __LINE__ . " - \$integer = $integer\n";
}
return $integer;
}
/**
* Template method; override this in subclasses
*
* Should return an integer in the range ($this->min, $this-max) inclusive.
*/
abstract public function _getInteger();
protected $min;
protected $max;
}
class RangeIntegerSource extends BaseIntegerSource implements IIntegerSource, IDebuggable
{
public function __construct($min, $max)
{
parent::__construct($min, $max);
$this->integer = $this->min;
}
/**
* Template method called by BaseIntegerSource.
*
* Should return an integer in the range ($this->min, $this-max) inclusive.
*/
public function _getInteger()
{
$integer = $this->integer;
$this->increment();
return $integer;
}
protected function increment()
{
$this->integer++;
if ($this->integer > $this->max)
{
$this->integer = $this->min;
}
}
protected $integer;
}
class MTRandomIntegerSource extends BaseIntegerSource implements IIntegerSource, IDebuggable
{
public function setSeed($seed)
{
mt_srand($seed);
}
/**
* Template method called by BaseIntegerSource.
*
* Should return an integer in the range ($this->min, $this-max) inclusive.
*/
public function _getInteger()
{
return mt_rand($this->min, $this->max);
}
}
$integerSource = new MTRandomIntegerSource(1, 10);
$integerSource = new RangeIntegerSource(1, 10);
$integerSource->setDebugLevel(1);
foreach (range(0, 12) as $i)
{
$num = $integerSource->getInteger();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment