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

Last change on this file since 50 was 44, checked in by scdev, 19 years ago

${1}

File size: 7.1 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        if (!isset($this) || !is_a($this, 'SessionCache')) {
47            $this =& SessionCache::getInstance();
48        }
49
50        if (isset($params) && is_array($params)) {
51            // Merge new parameters with old overriding only those passed.
52            $this->_params = array_merge($this->_params, $params);
53        } else {
54            App::logMsg(sprintf('Parameters are not an array: %s', $params), LOG_ERR, __FILE__, __LINE__);
55        }
56    }
57
58    /**
59     * Return the value of a parameter, if it exists.
60     *
61     * @access public
62     * @param string $param        Which parameter to return.
63     * @return mixed               Configured parameter value.
64     */
65    function getParam($param)
66    {
67        if (!isset($this) || !is_a($this, 'SessionCache')) {
68            $this =& SessionCache::getInstance();
69        }
70
71        if (isset($this->_params[$param])) {
72            return $this->_params[$param];
73        } else {
74            App::logMsg(sprintf('Parameter is not set: %s', $param), LOG_DEBUG, __FILE__, __LINE__);
75            return null;
76        }
77    }
78
79    /**
80     * Stores a new variable in the session cache. The $var_id is is md5'ed
81     * because if a variable id is a very large integer, the array_shift function
82     * will reset the key to the next largest int key. Weird behaviour I can't
83     * understand. $session_cache[32341234123] will become $session_cache[0]
84     * for example. Usage warning: if the variable is too big to fit, or is
85     * old and discarded, you must provide alternative ways of accessing the data.
86     *
87     * @param mixed $var          The var to store in the session cache.
88     * @param str   $var_id       An identifyer for the cached object.
89     * @param bool  $force_it_in  If we have something really big that we
90     *                            still want to cache, setting this true
91     *                            allows this.
92     *
93     * @return string        The $var_id, or false if the object was too big to cache.
94     */
95    function putCache($var, $var_id, $force_it_in=false)
96    {
97        if (!isset($this) || !is_a($this, 'SessionCache')) {
98            $this =& SessionCache::getInstance();
99        }
100
101        if (!$this->getParam('enabled')) {
102            App::logMsg(sprintf('SessionCache not enabled, not saving data.', null), LOG_DEBUG, __FILE__, __LINE__);
103            return false;
104        }
105
106        $var_id = md5($var_id);
107        $serialized_var = serialize($var);
108        $serialized_var_len = strlen($serialized_var);
109
110        if ($serialized_var_len >= $this->getParam('soft_limit') && !$force_it_in) {
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'][$var_id]);
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'][$var_id] =& $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 $var_id;
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 $var_id  The identifyer for the datum to retrieve.
146     *
147     * @return mixed          The requested datum, or false on failure.
148     */
149    function getCache($var_id)
150    {
151        if (!isset($this) || !is_a($this, 'SessionCache')) {
152            $this =& SessionCache::getInstance();
153        }
154
155        if (!$this->getParam('enabled')) {
156            return false;
157        }
158
159        $var_id = md5($var_id);
160        if (isset($_SESSION['_session_cache'][$var_id])) {
161            // Move the accessed cached datum to the top of the stack. Maybe somebody knows a better way to do this?
162            $tmp =& $_SESSION['_session_cache'][$var_id];
163            unset($_SESSION['_session_cache'][$var_id]);
164            $_SESSION['_session_cache'][$var_id] =& $tmp;
165            // Return the unserialized datum.
166            return unserialize($_SESSION['_session_cache'][$var_id]);
167        } else {
168            return false;
169        }
170    }
171
172    /**
173     * Tells you if the object is cached.
174     *
175     * @param string $var_id  The ID of the object to check.
176     *
177     * @return bool           The return from isset().
178     */
179    function isCached($var_id)
180    {
181        if (!isset($this) || !is_a($this, 'SessionCache')) {
182            $this =& SessionCache::getInstance();
183        }
184
185        if (!$this->getParam('enabled')) {
186            return false;
187        }
188
189        $var_id = md5($var_id);
190        return isset($_SESSION['_session_cache'][$var_id]);
191    }
192
193    /**
194     * Tells you if the object is cached.
195     *
196     * @param string $var_id  The ID of the object to check.
197     *
198     * @return bool           The return from isset().
199     */
200    function breakCache($var_id)
201    {
202        $var_id = md5($var_id);
203        if (isset($_SESSION['_session_cache'][$var_id])) {
204            unset($_SESSION['_session_cache'][$var_id]);
205        }
206    }
207
208// END SessionCache
209}
210
211?>
Note: See TracBrowser for help on using the repository browser.