Cache.php 11.7 KB
Newer Older
zYne's avatar
zYne committed
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
<?php
/*
 *  $Id$
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
 * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 *
 * This software consists of voluntary contributions made by many individuals
 * and is licensed under the LGPL. For more information, see
 * <http://www.phpdoctrine.com>.
 */
21
Doctrine::autoload('Doctrine_EventListener');
zYne's avatar
zYne committed
22 23 24 25 26 27 28 29 30 31 32 33
/**
 * Doctrine_Cache
 *
 * @package     Doctrine
 * @subpackage  Doctrine_Cache
 * @author      Konsta Vesterinen <kvesteri@cc.hut.fi>
 * @license     http://www.opensource.org/licenses/lgpl-license.php LGPL
 * @category    Object Relational Mapping
 * @link        www.phpdoctrine.com
 * @since       1.0
 * @version     $Revision$
 */
34
class Doctrine_Cache extends Doctrine_EventListener implements Countable, IteratorAggregate
zYne's avatar
zYne committed
35
{
zYne's avatar
zYne committed
36 37 38
    /**
     * @var array $_options                         an array of general caching options
     */
zYne's avatar
zYne committed
39 40 41 42 43 44
    protected $_options = array('size'                  => 1000,
                                'lifeTime'              => 3600,
                                'addStatsPropability'   => 0.25,
                                'savePropability'       => 0.10,
                                'cleanPropability'      => 0.01,
                                'statsFile'             => '../data/stats.cache',
zYne's avatar
zYne committed
45
                                );
zYne's avatar
zYne committed
46 47 48
    /**
     * @var array $_queries                         query stack
     */
zYne's avatar
zYne committed
49
    protected $_queries = array();
zYne's avatar
zYne committed
50 51 52
    /**
     * @var Doctrine_Cache_Interface $_driver       the cache driver object
     */
zYne's avatar
zYne committed
53
    protected $_driver;
zYne's avatar
zYne committed
54 55 56
    /**
     * @var array $data                             current cache data array
     */
57
    protected $_data = array();
zYne's avatar
zYne committed
58 59 60 61
    /**
     * @var boolean $success                        the success of last operation
     */
    protected $_success = false;
zYne's avatar
zYne committed
62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78
    /**
     * constructor
     *
     * @param Doctrine_Cache_Interface|string $driver       cache driver name or a driver object
     * @param array $options                                cache driver options
     */
    public function __construct($driver, $options = array())
    {
    	if (is_object($driver)) {
    	   if ( ! ($driver instanceof Doctrine_Cache_Interface)) {
    	       throw new Doctrine_Cache_Exception('Driver should implement Doctrine_Cache_Interface.');
    	   }
    	   
    	   $this->_driver = $driver;
    	   $this->_driver->setOptions($options);
        } else {
            $class = 'Doctrine_Cache_' . ucwords(strtolower($driver));
zYne's avatar
zYne committed
79
    
zYne's avatar
zYne committed
80 81 82 83 84 85 86 87 88 89 90 91 92 93
            if ( ! class_exists($class)) {
                throw new Doctrine_Cache_Exception('Cache driver ' . $driver . ' could not be found.');
            }
    
            $this->_driver = new $class($options);
        }
    }
    /**
     * getDriver
     * returns the current cache driver
     *
     * @return Doctrine_Cache_Driver
     */
    public function getDriver()
zYne's avatar
zYne committed
94
    {
zYne's avatar
zYne committed
95 96 97 98 99 100 101 102 103 104 105 106 107 108 109
        return $this->_driver;
    }
    /**
     * setOption
     *
     * @param mixed $option     the option name
     * @param mixed $value      option value
     * @return boolean          TRUE on success, FALSE on failure
     */
    public function setOption($option, $value)
    {
    	// sanity check (we need this since we are using isset() instead of array_key_exists())
    	if ($value === null) {
            throw new Doctrine_Cache_Exception('Null values not accepted for options.');
    	}
zYne's avatar
zYne committed
110

zYne's avatar
zYne committed
111 112 113
    	if (isset($this->_options[$option])) {
            $this->_options[$option] = $value;
            return true;
zYne's avatar
zYne committed
114
        }
zYne's avatar
zYne committed
115
        return false;
zYne's avatar
zYne committed
116
    }
zYne's avatar
zYne committed
117 118 119 120 121 122 123
    /**
     * getOption
     * 
     * @param mixed $option     the option name
     * @return mixed            option value
     */
    public function getOption($option)
zYne's avatar
zYne committed
124
    {
zYne's avatar
zYne committed
125 126 127 128 129
        if ( ! isset($this->_options[$option])) {
            throw new Doctrine_Cache_Exception('Unknown option ' . $option);
        }

        return $this->_options[$option];
zYne's avatar
zYne committed
130
    }
zYne's avatar
zYne committed
131
    /**
zYne's avatar
zYne committed
132 133
     * add
     * adds a query to internal query stack
zYne's avatar
zYne committed
134
     *
zYne's avatar
zYne committed
135 136
     * @param string|array $query           sql query string
     * @param string $namespace             connection namespace
zYne's avatar
zYne committed
137 138
     * @return void
     */
zYne's avatar
zYne committed
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
    public function add($query, $namespace = null)
    {
    	if (isset($namespace)) {
            $this->_queries[$namespace][] = $query;
        } else {
            $this->_queries[] = $query;
        }
    }
    /**
     * getQueries
     *
     * @param string $namespace     optional query namespace
     * @return array                an array of sql query strings
     */
    public function getAll($namespace = null)
    {
        if (isset($namespace)) {
            if( ! isset($this->_queries[$namespace])) {
                return array();
            }

            return $this->_queries[$namespace];
        }
        
        return $this->_queries;
    }
    /**
     * pop
     *
     * pops a query from the stack
     * @return string
     */
    public function pop()
zYne's avatar
zYne committed
172
    {
zYne's avatar
zYne committed
173 174
        return array_pop($this->_queries);
    }
zYne's avatar
zYne committed
175 176 177 178 179 180 181 182 183 184
    /**
     * reset
     *
     * removes all queries from the query stack
     * @return void
     */
    public function reset()
    {
        $this->_queries = array();
    }
zYne's avatar
zYne committed
185 186 187
    /**
     * count
     *
zYne's avatar
zYne committed
188
     * @return integer          the number of queries in the stack
zYne's avatar
zYne committed
189 190 191
     */
    public function count() 
    {
zYne's avatar
zYne committed
192 193 194 195 196 197 198 199 200 201
        return count($this->_queries);
    }
    /**
     * getIterator
     *
     * @return ArrayIterator    an iterator that iterates through the query stack
     */
    public function getIterator()
    {
        return new ArrayIterator($this->_queries);
zYne's avatar
zYne committed
202
    }
zYne's avatar
zYne committed
203 204 205 206 207 208 209
    /**
     * @return boolean          whether or not the last cache operation was successful
     */
    public function isSuccessful() 
    {
        return $this->_success;
    }
zYne's avatar
zYne committed
210 211 212 213 214
    /**
     * save
     *
     * @return boolean
     */
zYne's avatar
zYne committed
215
    public function clean()
zYne's avatar
zYne committed
216
    {
zYne's avatar
zYne committed
217
        $rand = (mt_rand() / mt_getrandmax());
zYne's avatar
zYne committed
218

zYne's avatar
zYne committed
219
    	if ($rand <= $this->_options['cleanPropability']) {
zYne's avatar
zYne committed
220
            $queries = $this->readStats();
zYne's avatar
zYne committed
221

zYne's avatar
zYne committed
222 223 224 225 226 227 228 229
            $stats   = array();
    
            foreach ($queries as $query) {
                if (isset($stats[$query])) {
                    $stats[$query]++;
                } else {
                    $stats[$query] = 1;
                }
zYne's avatar
zYne committed
230
            }
zYne's avatar
zYne committed
231 232 233 234 235 236 237
            sort($stats);
    
            $i = $this->_options['size'];
    
            while ($i--) {
                $element = next($stats);
                $query   = key($stats);
zYne's avatar
zYne committed
238

zYne's avatar
zYne committed
239 240
                $hash = md5($query);

zYne's avatar
zYne committed
241
                $this->_driver->delete($hash);
zYne's avatar
zYne committed
242 243 244
            }
        }
    }
zYne's avatar
zYne committed
245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260
    /**
     * readStats
     *
     * @return array
     */
    public function readStats() 
    {
    	if ($this->_options['statsFile'] !== false) {
    	   $content = file_get_contents($this->_options['statsFile']);
           
           $e = explode("\n", $content);
           
           return array_map('unserialize', $e);
    	}
    	return array();
    }
zYne's avatar
zYne committed
261
    /**
zYne's avatar
zYne committed
262
     * appendStats
zYne's avatar
zYne committed
263 264 265 266
     *
     * adds all queries to stats file
     * @return void
     */
zYne's avatar
zYne committed
267
    public function appendStats()
zYne's avatar
zYne committed
268
    {
zYne's avatar
zYne committed
269
    	if ($this->_options['statsFile'] !== false) {
zYne's avatar
zYne committed
270

zYne's avatar
zYne committed
271 272 273
            if ( ! file_exists($this->_options['statsFile'])) {
                throw new Doctrine_Cache_Exception("Couldn't save cache statistics. Cache statistics file doesn't exists!");
            }
zYne's avatar
zYne committed
274 275
            
            $rand = (mt_rand() / mt_getrandmax());
zYne's avatar
zYne committed
276

zYne's avatar
zYne committed
277
            if ($rand <= $this->_options['addStatsPropability']) {
zYne's avatar
zYne committed
278
                file_put_contents($this->_options['statsFile'], implode("\n", array_map('serialize', $this->_queries)));
zYne's avatar
zYne committed
279
            }
zYne's avatar
zYne committed
280 281 282
        }
    }
    /**
283 284
     * preQuery
     * listens on the Doctrine_Event preQuery event
zYne's avatar
zYne committed
285 286 287 288 289 290
     *
     * adds the issued query to internal query stack
     * and checks if cached element exists
     *
     * @return boolean
     */
291
    public function preQuery(Doctrine_Event $event)
292
    {
zYne's avatar
zYne committed
293
        $query = $event->getQuery();
zYne's avatar
zYne committed
294 295

        $data  = false;
zYne's avatar
zYne committed
296
        // only process SELECT statements
297
        if (strtoupper(substr(ltrim($query), 0, 6)) == 'SELECT') {
zYne's avatar
zYne committed
298

zYne's avatar
zYne committed
299
            $this->add($query, $event->getInvoker()->getName());
zYne's avatar
zYne committed
300

zYne's avatar
zYne committed
301
            $data = $this->_driver->fetch(md5(serialize($query)));
zYne's avatar
zYne committed
302

zYne's avatar
zYne committed
303 304
            $this->success = ($data) ? true : false;

zYne's avatar
zYne committed
305
            if ( ! $data) {
zYne's avatar
zYne committed
306
                $rand = (mt_rand() / mt_getrandmax());
zYne's avatar
zYne committed
307 308

                if ($rand < $this->_options['savePropability']) {
zYne's avatar
zYne committed
309
                    $stmt = $event->getInvoker()->getAdapter()->query($query);
zYne's avatar
zYne committed
310 311 312 313 314

                    $data = $stmt->fetchAll(Doctrine::FETCH_ASSOC);

                    $this->success = true;

zYne's avatar
zYne committed
315
                    $this->_driver->save(md5(serialize($query)), $data);
zYne's avatar
zYne committed
316 317
                }
            }
318 319
            if ($this->success)
            {
320
                $this->_data = $data;
321 322
                return true;
            }
zYne's avatar
zYne committed
323
        }
324
        return false;
zYne's avatar
zYne committed
325
    }
zYne's avatar
zYne committed
326
    /**
327 328
     * preFetch
     * listens the preFetch event of Doctrine_Connection_Statement
zYne's avatar
zYne committed
329 330 331 332 333 334
     *
     * advances the internal pointer of cached data and returns 
     * the current element
     *
     * @return array
     */
335
    public function preFetch(Doctrine_Event $event)
zYne's avatar
zYne committed
336
    {
zYne's avatar
zYne committed
337 338 339
        $ret = current($this->_data);
    	next($this->_data);
        return $ret;
zYne's avatar
zYne committed
340
    }
zYne's avatar
zYne committed
341
    /**
342 343
     * preFetch
     * listens the preFetchAll event of Doctrine_Connection_Statement
zYne's avatar
zYne committed
344 345 346 347 348
     *
     * returns the current cache data array
     *
     * @return array
     */
349
    public function preFetchAll(Doctrine_Event $event)
zYne's avatar
zYne committed
350 351 352
    {
        return $this->_data;
    }
zYne's avatar
zYne committed
353
    /**
354 355
     * preExecute
     * listens the preExecute event of Doctrine_Connection_Statement
zYne's avatar
zYne committed
356 357 358 359 360 361
     *
     * adds the issued query to internal query stack
     * and checks if cached element exists
     *
     * @return boolean
     */
362
    public function preExecute(Doctrine_Event $event)
zYne's avatar
zYne committed
363
    {
zYne's avatar
zYne committed
364
        $query = $event->getQuery();
zYne's avatar
zYne committed
365 366 367

        $data  = false;

zYne's avatar
zYne committed
368
        // only process SELECT statements
369
        if (strtoupper(substr(ltrim($query), 0, 6)) == 'SELECT') {
zYne's avatar
zYne committed
370

zYne's avatar
zYne committed
371
            $this->add($query, $event->getInvoker()->getDbh()->getName());
zYne's avatar
zYne committed
372

zYne's avatar
zYne committed
373 374
            $data = $this->_driver->fetch(md5(serialize(array($query, $event->getParams()))));

zYne's avatar
zYne committed
375 376
            $this->success = ($data) ? true : false;

zYne's avatar
zYne committed
377
            if ( ! $data) {
zYne's avatar
zYne committed
378
                $rand = (mt_rand() / mt_getrandmax());
zYne's avatar
zYne committed
379

zYne's avatar
zYne committed
380 381 382 383 384
                if ($rand <= $this->_options['savePropability']) {

                    $stmt = $event->getInvoker()->getStatement();

                    $stmt->execute($event->getParams());
zYne's avatar
zYne committed
385 386 387 388 389 390 391 392

                    $data = $stmt->fetchAll(Doctrine::FETCH_ASSOC);

                    $this->success = true;

                    $this->_driver->save(md5(serialize(array($query, $event->getParams()))), $data);
                }
            }
393 394
            if ($this->success)
            {
395
                $this->_data = $data;
396 397
                return true;
            }
zYne's avatar
zYne committed
398
        }
399
        return false;
zYne's avatar
zYne committed
400
    }
zYne's avatar
zYne committed
401
}