source: trunk/lib/SessionCache.inc.php @ 136

Last change on this file since 136 was 136, checked in by scdev, 18 years ago

Q - Merged branches/2.0singleton into trunk. Completed updating classes to use singleton methods. Implemented tests. Fixed some bugs. Changed some interfaces.

File size: 6.6 KB
Line 
1<?php
2/**
3 * Cache.inc.php
4 * code by strangecode :: www.strangecode.com :: this document contains copyrighted information
5 *
6 * Provides an API for storing a limited amount of data
7 * intended to have a short lifetime in a user's session.
8 *
9 * @author  Quinn Comendant <quinn@strangecode.com>
10 * @version 2.1
11 * @since   2001
12 */
13 
14// Flags.
15define('CACHE_IGNORE_SIZE', 1);
16
17class Cache {
18
19    var $_params = array(
20        'enabled' => true,
21        'soft_limit' => 204800,
22        'hard_limit' => 4194304,
23        'min_items' => 3,
24    );
25
26    /**
27     * This method enforces the singleton pattern for this class.
28     *
29     * @return  object  Reference to the global Cache object.
30     * @access  public
31     * @static
32     */
33    function &getInstance()
34    {
35        static $instance = null;
36
37        if ($instance === null) {
38            $instance = new Cache();
39        }
40
41        return $instance;
42    }
43
44    /**
45     * Set (or overwrite existing) parameters by passing an array of new parameters.
46     *
47     * @access public
48     * @param  array    $params     Array of parameters (key => val pairs).
49     */
50    function setParam($params)
51    {
52        $app =& App::getInstance();
53
54        if (isset($params) && is_array($params)) {
55            // Merge new parameters with old overriding only those passed.
56            $this->_params = array_merge($this->_params, $params);
57        } else {
58            $app->logMsg(sprintf('Parameters are not an array: %s', $params), LOG_ERR, __FILE__, __LINE__);
59        }
60    }
61
62    /**
63     * Return the value of a parameter, if it exists.
64     *
65     * @access public
66     * @param string $param        Which parameter to return.
67     * @return mixed               Configured parameter value.
68     */
69    function getParam($param)
70    {
71        $app =& App::getInstance();
72   
73        if (isset($this->_params[$param])) {
74            return $this->_params[$param];
75        } else {
76            $app->logMsg(sprintf('Parameter is not set: %s', $param), LOG_NOTICE, __FILE__, __LINE__);
77            return null;
78        }
79    }
80
81    /**
82     * Stores a new variable in the session cache. The $key is is md5'ed
83     * because if a variable id is a very large integer, the array_shift function
84     * will reset the key to the next largest int key. Weird behavior I can't
85     * understand. $session_cache[32341234123] will become $session_cache[0]
86     * for example. Usage warning: if the variable is too big to fit, or is
87     * old and discarded, you must provide alternative ways of accessing the data.
88     *
89     * @param str   $key        An identifier for the cached object.
90     * @param mixed $var          The var to store in the session cache.
91     * @param bool  $flags      If we have something really big that we
92     *                            still want to cache, setting this to
93     *                            CACHE_IGNORE_SIZE allows this.
94     *
95     * @return bool               True on success, false otherwise.
96     */
97    function set($key, $var, $flags=0)
98    {
99        $app =& App::getInstance();
100
101        if (!$this->getParam('enabled')) {
102            $app->logMsg(sprintf('Cache not enabled, not saving data.', null), LOG_DEBUG, __FILE__, __LINE__);
103            return false;
104        }
105
106        $key = md5($key);
107        $serialized_var = serialize($var);
108        $serialized_var_len = strlen($serialized_var);
109
110        if ($flags & CACHE_IGNORE_SIZE > 0 && $serialized_var_len >= $this->getParam('soft_limit')) {
111            $app->logMsg(sprintf('Serialized variable (%s bytes) more than soft_limit (%s bytes).', $serialized_var_len, $this->getParam('soft_limit')), LOG_NOTICE, __FILE__, __LINE__);
112            return false;
113        }
114
115        if ($serialized_var_len >= $this->getParam('hard_limit')) {
116            $app->logMsg(sprintf('Serialized variable (%s bytes) more than hard_limit (%s bytes).', $serialized_var_len, $this->getParam('hard_limit')), LOG_NOTICE, __FILE__, __LINE__);
117            return false;
118        }
119
120        if (!isset($_SESSION['_session_cache'])) {
121            $_SESSION['_session_cache'] = array();
122        } else {
123            unset($_SESSION['_session_cache'][$key]);
124            // Continue to prune the cache if it's length is too long for the new variable to fit, but keep at least MIN_ITEMS at least.
125            while (strlen(serialize($_SESSION['_session_cache'])) + $serialized_var_len >= $this->getParam('soft_limit')
126            && sizeof($_SESSION['_session_cache']) >= $this->getParam('min_items')) {
127                array_shift($_SESSION['_session_cache']);
128            }
129        }
130        $_SESSION['_session_cache'][$key] =& $serialized_var;
131
132        if ($serialized_var_len >= 1024000) {
133            $app->logMsg(sprintf('Successfully cached oversized variable (%s bytes).', $serialized_var_len), LOG_DEBUG, __FILE__, __LINE__);
134        }
135
136        return true;
137    }
138
139    /**
140     * Retrives an object from the session cache and returns it unserialized.
141     * It also moves it to the top of the stack, which makes it such that the
142     * cache flushing mechanism of putCache deletes the oldest referenced items
143     * first.
144     *
145     * @param string $key  The key for the datum to retrieve.
146     *
147     * @return mixed          The requested datum, or false on failure.
148     */
149    function get($key)
150    {
151        if (!$this->getParam('enabled')) {
152            return false;
153        }
154
155        $key = md5($key);
156        if (isset($_SESSION['_session_cache'][$key])) {
157            // Move the accessed cached datum to the top of the stack. Maybe somebody knows a better way to do this?
158            $tmp =& $_SESSION['_session_cache'][$key];
159            unset($_SESSION['_session_cache'][$key]);
160            $_SESSION['_session_cache'][$key] =& $tmp;
161            // Return the unserialized datum.
162            return unserialize($_SESSION['_session_cache'][$key]);
163        } else {
164            return false;
165        }
166    }
167
168    /**
169     * Tells you if the object is cached.
170     *
171     * @param string $key  The key of the object to check.
172     *
173     * @return bool           The return from isset().
174     */
175    function exists($key)
176    {
177        if (!$this->getParam('enabled')) {
178            return false;
179        }
180
181        $key = md5($key);
182        return isset($_SESSION['_session_cache'][$key]);
183    }
184
185    /**
186     * Tells you if the object is cached.
187     *
188     * @param string $key  The key of the object to check.
189     *
190     * @return bool           The return from isset().
191     */
192    function delete($key)
193    {
194        $key = md5($key);
195        if (isset($_SESSION['_session_cache'][$key])) {
196            unset($_SESSION['_session_cache'][$key]);
197        }
198    }
199
200// END Cache
201}
202
203?>
Note: See TracBrowser for help on using the repository browser.