source: branches/2.0singleton/lib/SessionCache.inc.php @ 132

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

finished /lib folder

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