dmBridge PHP API
UNLVRandomSQLiteDataStore.php
00001 <?php
00002 #
00003 # UNLVRandom: a dmBridge module for random objects
00004 #
00005 # Copyright © 2011 Board of Regents of the Nevada System of Higher
00006 # Education, on behalf of the University of Nevada, Las Vegas
00007 #
00008 
00013 class UNLVRandomSQLiteDataStore extends DMSQLiteDataStore
00014 implements UNLVRandomDataStore {
00015 
00016    protected static $instance;
00017 
00023    public static function getSetupSQL() {
00024       return array(
00025          'CREATE TABLE "random_object" (
00026             "id" INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL ,
00027             "alias" VARCHAR NOT NULL,
00028             "ptr" INTEGER NOT NULL
00029          );'
00030       );
00031    }
00032 
00038    public static function getUpgradeSQL() {
00039       return array(
00040          // currently empty because there is no previous version from which
00041          // to upgrade.
00042       );
00043    }
00044 
00049    public static function getInstance() {
00050       if (!self::$instance instanceof self) {
00051          self::$instance = new self;
00052       }
00053       return self::$instance;
00054    }
00055 
00059    public function addRandomObject(DMObject $obj) {
00060       $sql = "INSERT INTO random_object(alias, ptr) VALUES(:alias, :ptr);";
00061       $params = array(
00062          ':alias' => $obj->getCollection()->getAlias(),
00063          ':ptr' => $obj->getPtr()
00064       );
00065       $this->write($sql, $params);
00066    }
00067 
00071    public function getRandomObject() {
00072       $sql = "SELECT alias, ptr FROM random_object ORDER BY RANDOM() LIMIT 1";
00073       $result = $this->read($sql, array());
00074 
00075       if (count($result)) {
00076          $collection = DMCollectionFactory::getCollection(
00077                $result[0]['alias']);
00078          $obj = DMObjectFactory::getObject($collection, $result[0]['ptr']);
00079          return $obj;
00080       }
00081       return null;
00082    }
00083 
00088    public function isRandomObject(DMObject $obj) {
00089       foreach ($this->getRandomObjects() as $ro) {
00090          if ($obj->equals($ro)) {
00091             return true;
00092          }
00093       }
00094       return false;
00095    }
00096 
00100    public function getRandomObjects() {
00101       $sql = "SELECT alias, ptr FROM random_object ORDER BY RANDOM()";
00102       $result = $this->read($sql, array());
00103 
00104       $objects = array();
00105       foreach ($result as $row) {
00106          try {
00107             $collection = DMCollectionFactory::getCollection($row['alias']);
00108             $objects[] = DMObjectFactory::getObject($collection, $row['ptr']);
00109          } catch (DMUnavailableModelException $e) {
00110             // nothing we can do; skip
00111          }
00112       }
00113       return $objects;
00114    }
00115 
00116 }
 All Data Structures Functions Variables