7
* This source file is subject to the new BSD license that is bundled
8
* with this package in the file LICENSE.txt.
9
* It is also available through the world-wide-web at this URL:
10
* http://framework.zend.com/license/new-bsd
11
* If you did not receive a copy of the license and are unable to
12
* obtain it through the world-wide-web, please send an email
13
* to license@zend.com so we can send you a copy immediately.
15
* @package Zend_Memory
16
* @copyright Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
17
* @license http://framework.zend.com/license/new-bsd New BSD License
20
/** Zend_Memory_Container_Movable */
21
require_once 'Zend/Memory/Container/Movable.php';
23
/** Zend_Memory_Container_Locked */
24
require_once 'Zend/Memory/Container/Locked.php';
26
/** Zend_Memory_AccessController */
27
require_once 'Zend/Memory/AccessController.php';
33
* This class encapsulates memory menagement operations, when PHP works
34
* in limited memory mode.
38
* @package Zend_Memory
39
* @copyright Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
40
* @license http://framework.zend.com/license/new-bsd New BSD License
42
class Zend_Memory_Manager
45
* Object storage backend
47
* @var Zend_Cache_Backend_Interface
49
private $_backend = null;
53
* Default value is 2/3 of memory_limit php.ini variable
54
* Negative value means no limit
58
private $_memoryLimit = -1;
61
* Minimum value size to be swapped.
62
* Default value is 16K
63
* Negative value means that memory objects are never swapped
67
private $_minSize = 16384;
70
* Overall size of memory, used by values
74
private $_memorySize = 0;
77
* Id for next Zend_Memory object
84
* List of candidates to unload
86
* It also represents objects access history. Last accessed objects are moved to the end of array
89
* <id> => <memory container object>,
95
private $_unloadCandidates = array();
98
* List of object sizes.
100
* This list is used to calculate modification of object sizes
102
* array( <id> => <size>, ...)
106
private $_sizes = array();
109
* Last modified object
111
* It's used to reduce number of calls necessary to trace objects' modifications
112
* Modification is not processed by memory manager until we do not switch to another
114
* So we have to trace only _first_ object modification and do nothing for others
116
* @var Zend_Memory_Container_Movable
118
private $_lastModified = null;
121
* Unique memory manager id
128
* Tags array, used by backend to categorize stored values
135
* This function is intended to generate unique id, used by memory manager
137
private function _generateMemManagerId()
141
* uniqid() php function doesn't really garantee the id to be unique
142
* it should be changed by something else
143
* (Ex. backend interface should be extended to provide this functionality)
145
$this->_managerId = uniqid('ZendMemManager', true);
146
$this->_tags = array($this->_managerId);
147
$this->_managerId .= '_';
152
* Memory manager constructor
154
* If backend is not specified, then memory objects are never swapped
156
* @param Zend_Cache_Backend $backend
157
* @param array $backendOptions associative array of options for the corresponding backend constructor
159
public function __construct($backend = null)
161
if ($backend === null) {
165
$this->_backend = $backend;
166
$this->_generateMemManagerId();
168
$memoryLimitStr = trim(ini_get('memory_limit'));
169
if ($memoryLimitStr != '') {
170
$this->_memoryLimit = (integer)$memoryLimitStr;
171
switch (strtolower($memoryLimitStr[strlen($memoryLimitStr)-1])) {
173
$this->_memoryLimit *= 1024;
174
// Break intentionally omitted
176
$this->_memoryLimit *= 1024;
177
// Break intentionally omitted
179
$this->_memoryLimit *= 1024;
186
$this->_memoryLimit = (int)($this->_memoryLimit*2/3);
187
} // No limit otherwise
193
* Clean up backend storage
195
public function __destruct()
197
if ($this->_backend !== null) {
198
$this->_backend->clean(Zend_Cache::CLEANING_MODE_MATCHING_TAG, $this->_tags);
203
* Set memory grow limit
205
* @param integer $newLimit
206
* @throws Zend_Exception
208
public function setMemoryLimit($newLimit)
210
$this->_memoryLimit = $newLimit;
216
* Get memory grow limit
220
public function getMemoryLimit()
222
return $this->_memoryLimit;
226
* Set minimum size of values, which may be swapped
228
* @param integer $newSize
230
public function setMinSize($newSize)
232
$this->_minSize = $newSize;
236
* Get minimum size of values, which may be swapped
240
public function getMinSize()
242
return $this->_minSize;
246
* Create new Zend_Memory value container
248
* @param string $value
249
* @return Zend_Memory_Container_Interface
250
* @throws Zend_Memory_Exception
252
public function create($value = '')
254
return $this->_create($value, false);
258
* Create new Zend_Memory value container, which has value always
261
* @param string $value
262
* @return Zend_Memory_Container_Interface
263
* @throws Zend_Memory_Exception
265
public function createLocked($value = '')
267
return $this->_create($value, true);
271
* Create new Zend_Memory object
273
* @param string $value
274
* @param boolean $locked
275
* @return Zend_Memory_Container_Interface
276
* @throws Zend_Memory_Exception
278
private function _create($value, $locked)
280
$id = $this->_nextId++;
282
if ($locked || ($this->_backend === null) /* Use only memory locked objects if backend is not specified */) {
283
return new Zend_Memory_Container_Locked($value);
286
// Commit other objects modifications
289
$valueObject = new Zend_Memory_Container_Movable($this, $id, $value);
291
// Store last object size as 0
292
$this->_sizes[$id] = 0;
293
// prepare object for next modifications
294
$this->_lastModified = $valueObject;
296
return new Zend_Memory_AccessController($valueObject);
300
* Unlink value container from memory manager
302
* Used by Memory container destroy() method
306
* @return Zend_Memory_Container
308
public function unlink(Zend_Memory_Container_Movable $container, $id)
310
if ($this->_lastModified === $container) {
311
// Drop all object modifications
312
$this->_lastModified = null;
313
unset($this->_sizes[$id]);
317
if (isset($this->_unloadCandidates[$id])) {
318
unset($this->_unloadCandidates[$id]);
321
$this->_memorySize -= $this->_sizes[$id];
322
unset($this->_sizes[$id]);
326
* Process value update
329
* @param Zend_Memory_Container_Movable $container
332
public function processUpdate(Zend_Memory_Container_Movable $container, $id)
335
* This method is automatically invoked by memory container only once per
336
* "modification session", but user may call memory container touch() method
337
* several times depending on used algorithm. So we have to use this check
338
* to optimize this case.
340
if ($container === $this->_lastModified) {
344
// Remove just updated object from list of candidates to unload
345
if( isset($this->_unloadCandidates[$id])) {
346
unset($this->_unloadCandidates[$id]);
349
// Reduce used memory mark
350
$this->_memorySize -= $this->_sizes[$id];
352
// Commit changes of previously modified object if necessary
355
$this->_lastModified = $container;
359
* Commit modified object and put it back to the loaded objects list
361
private function _commit()
363
if (($container = $this->_lastModified) === null) {
367
$this->_lastModified = null;
369
$id = $container->getId();
371
// Calculate new object size and increase used memory size by this value
372
$this->_memorySize += ($this->_sizes[$id] = strlen($container->getRef()));
374
if ($this->_sizes[$id] > $this->_minSize) {
375
// Move object to "unload candidates list"
376
$this->_unloadCandidates[$id] = $container;
379
$container->startTrace();
385
* Check and swap objects if necessary
387
* @throws Zend_MemoryException
389
private function _swapCheck()
391
if ($this->_memoryLimit < 0 || $this->_memorySize < $this->_memoryLimit) {
392
// Memory limit is not reached
397
// walk through loaded objects in access history order
398
foreach ($this->_unloadCandidates as $id => $container) {
399
$this->_swap($container, $id);
400
unset($this->_unloadCandidates[$id]);
402
if ($this->_memorySize < $this->_memoryLimit) {
403
// We've swapped enough objects
408
throw new Zend_Memory_Exception('Memory manager can\'t get enough space.');
413
* Swap object data to disk
414
* Actualy swaps data or only unloads it from memory,
415
* if object is not changed since last swap
417
* @param Zend_Memory_Container_Movable $container
420
private function _swap(Zend_Memory_Container_Movable $container, $id)
422
if ($container->isLocked()) {
426
if (!$container->isSwapped()) {
427
$this->_backend->save($container->getRef(), $this->_managerId . $id, $this->_tags);
430
$this->_memorySize -= $this->_sizes[$id];
432
$container->markAsSwapped();
433
$container->unloadValue();
437
* Load value from swap file.
440
* @param Zend_Memory_Container_Movable $container
443
public function load(Zend_Memory_Container_Movable $container, $id)
445
$value = $this->_backend->load($this->_managerId . $id, true);
447
// Try to swap other objects if necessary
448
// (do not include specified object into check)
449
$this->_memorySize += strlen($value);
452
// Add loaded obect to the end of loaded objects list
453
$container->setValue($value);
455
if ($this->_sizes[$id] > $this->_minSize) {
456
// Add object to the end of "unload candidates list"
457
$this->_unloadCandidates[$id] = $container;