Sqlite.php 7.34 KB
Newer Older
doctrine's avatar
doctrine committed
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265
<?php
class Doctrine_Cache_Sqlite {
    /**
     * STATS_FILE constant
     * the name of the statistics file
     */
    const STATS_FILE = "stats.cache";
    /**
     * SELECT constant
     * used as a base for SQL SELECT queries
     */
    const SELECT     = "SELECT object FROM %s WHERE id %s";
    /**
     * INSERT constant
     * used as a base for SQL INSERT queries
     */
    const INSERT     = "REPLACE INTO %s (id, object) VALUES (?, ?)";
    /**
     * DELETE constant
     * used as a base for SQL DELETE queries
     */
    const DELETE     = "DELETE FROM %s WHERE id %s";
    /**
     * @var Doctrine_Table $table
     */
    private $table;
    /**
     * @var PDO $dbh
     */
    private $dbh;
    /**
     * @var array $fetched          an array of fetched primary keys
     */
    private $fetched = array();

    public function __construct(Doctrine_Table $table) {
        $this->table = $table;
        $dir = $this->table->getSession()->getAttribute(Doctrine::ATTR_CACHE_DIR);


        if( ! is_dir($dir))
            mkdir($dir, 0777);

        $this->path = $dir.DIRECTORY_SEPARATOR; 
        $this->dbh  = $this->table->getSession()->getCacheHandler();
        
        try {
            $this->dbh->query("CREATE TABLE ".$this->table->getTableName()." (id INTEGER UNIQUE, object TEXT)");
        } catch(PDOException $e) {

        }
        /**
         * create stats file
         */
        if( ! file_exists($this->path.self::STATS_FILE))
            touch($this->path.self::STATS_FILE);

    }
    /*
     * stores a Doctrine_Record into cache
     * @param Doctrine_Record $record           record to be stored
     * @return boolean                          whether or not storing was successful
     */
    public function store(Doctrine_Record $record) {
        if($record->getState() != Doctrine_Record::STATE_CLEAN)
            return false;
            
        $clone = clone $record;
        $id    = $clone->getID();
        
        $stmt  = $this->dbh->query(sprintf(self::INSERT,$this->table->getTableName()));
        $stmt->execute(array($id, serialize($clone)));
        

        return true;
    }
    /**
     * fetches a Doctrine_Record from the cache
     * @param mixed $id
     * @return mixed        false on failure, Doctrine_Record on success
     */
    public function fetch($id) {
        $stmt  = $this->dbh->query(sprintf(self::SELECT,$this->table->getTableName(),"= ?"));
        $stmt->execute(array($id));
        $data = $stmt->fetch(PDO::FETCH_NUM);

        if($data === false)
            throw new InvalidKeyException();
            
        $this->fetched[] = $id;
        
        $record = unserialize($data[0]);

        if(is_string($record)) {
            $this->delete($id);
            throw new InvalidKeyException();
        }

        return $record;
    }
    /**
     * fetches multiple records from the cache
     * @param array $keys
     * @return mixed        false on failure, an array of Doctrine_Record objects on success
     */
    public function fetchMultiple(array $keys) {
        $count = (count($keys)-1);
        $keys  = array_values($keys);
        $sql   = sprintf(self::SELECT,$this->table->getTableName(),"IN (".str_repeat("?, ",$count)."?)");
        $stmt  = $this->dbh->query($sql);

        $stmt->execute($keys);

        while($data = $stmt->fetch(PDO::FETCH_NUM)) {
            $array[] = unserialize($data[0]);
        }

        $this->fetched = array_merge($this->fetched, $keys);

        if( ! isset($array))
            return false;

        return $array;
    }
    /**
     * deletes all records from cache
     * @return void
     */
    public function deleteAll() {
        $stmt = $this->dbh->query("DELETE FROM ".$this->table->getTableName());
        return $stmt->rowCount();
    }
    /**
     * @param mixed $id
     * @return void
     */
    public function delete($id) {
        $stmt  = $this->dbh->query(sprintf(self::DELETE,$this->table->getTableName(),"= ?"));
        $stmt->execute(array($id));
        
        if($stmt->rowCount() > 0)
            return true;

        return false;
    }
    /**
     * count
     * @return integer
     */
    public function count() {
        $stmt = $this->dbh->query("SELECT COUNT(*) FROM ".$this->table->getTableName());
        $data = $stmt->fetch(PDO::FETCH_NUM);

        // table has two columns so we have to divide the count by two
        return ($data[0] / 2);
    }
    /**
     * @param array $keys
     * @return integer
     */
    public function deleteMultiple(array $keys) {
        if(empty($keys))
            return 0;

        $keys  = array_values($keys);
        $count = (count($keys)-1);
        $sql   = sprintf(self::DELETE,$this->table->getTableName(),"IN (".str_repeat("?, ",$count)."?)");
        $stmt  = $this->dbh->query($sql);
        $stmt->execute($keys);

        return $stmt->rowCount();
    }
    /**
     * getStats
     * @return array            an array of fetch statistics, keys as primary keys
     *                          and values as fetch times
     */
    public function getStats() {
        $f = file_get_contents($this->path.self::STATS_FILE);

        // every cache file starts with a ":"

        $f = substr(trim($f),1);
        $e = explode(":",$f);
        return array_count_values($e);
    }
    /**
     * clean
     * @return void
     */
    public function clean() {
        $stats = $this->getStats();

        asort($stats);
        $size  = $this->table->getAttribute(Doctrine::ATTR_CACHE_SIZE);

        $count = count($stats);

        if($count <= $size)
            return 0;

        $e     = $count - $size;

        $keys = array();
        foreach($stats as $id => $count) {
            if( ! $e--)
                break;

            $keys[] = $id;
        }
        return $this->deleteMultiple($keys);
    }
    /**
     * saves statistics
     * @return boolean
     */
    public function saveStats() {
        if( ! empty($this->fetched)) {
            $fp    = fopen($this->path.self::STATS_FILE,"a");
            fwrite($fp,":".implode(":",$this->fetched));
            fclose($fp);
            $this->fetched = array();
            return true;
        }
        return false;
    }
    /**
     * autoClean
     * $ttl is the number of page loads between each cache cleaning
     * the default is 100 page loads
     *
     * this means that the average number of page loads between
     * each cache clean is 100 page loads (= 100 constructed Doctrine_Managers)
     * @return boolean
     */
    public function autoClean() {
        $ttl = $this->table->getAttribute(Doctrine::ATTR_CACHE_TTL);

        $l1 = (mt_rand(1,$ttl) / $ttl);
        $l2 = (1 - 1/$ttl);

        if($l1 > $l2) {
            $this->clean();
            return true;
        }
        return false;
    }
    /**
     * @param mixed $id
     */
    public function addDelete($id) {
        $this->delete[] = $id;
    }
    /**
     * destructor
     * the purpose of this destructor is to save all the fetched
     * primary keys into the cache stats and to clean cache if necessary
     *
     */
    public function __destruct() {
        $this->saveStats();
        $this->autoClean();
    }
}
?>