In This Article
Introduction
zend-memory assists with managing data in an environment with limited memory.
Memory objects (memory containers) are generated by the memory manager at yourrequest and transparently swapped/loaded when necessary.
For example, if creating or loading a managed object would cause the totalmemory usage to exceed the limit you specify, some managed objects are copied tocache storage outside of memory. In this way, the total memory used by managedobjects does not exceed the limit you need to enforce. To provide thisfunctionality, the memory manager can composezend-cache storage adaptersas storage providers.
Usage
Instantiate the memory manager class:
use Zend\Memory\MemoryManager;// No caching backend:$memoryManager = new MemoryManager();Optionally, you can create a cache storage adapter, and pass it to theMemoryManager constructor:
use Zend\Cache\StorageFactory;use Zend\Memory\MemoryManager;// Use a filesystem adapter, placing memory blocks in the tmp directory// under which the application is running.$cache = StorageFactory::factory([ 'adapter' => [ 'name' => 'filesystem', 'options' => ['cache_dir' => './tmp/'], ],]);$memoryManager = new MemoryManager($cache);Once you have aMemoryManager instance, you can start pushing values to it andpulling values from it.
$loadedFiles = [];for ($count = 0; $count < 10000; $count++) { $f = fopen($fileNames[$count], 'rb'); $data = fread($f, filesize($fileNames[$count])); $fclose($f); $loadedFiles[] = $memoryManager->create($data);}echo $loadedFiles[$index1]->value;$loadedFiles[$index2]->value = $newValue;$loadedFiles[$index3]->value[$charIndex] = '_';Theory of Operation
zend-memory operates with the following concepts:
- Memory manager
- Memory container
- Locked memory object
- Movable memory object
Memory manager
The memory manager generates memory objects (locked or movable) by request ofthe application, and returns them wrapped into a memory container object.
Memory container
The memory container has a virtual or actualvalue attribute of typestring.This attribute contains the data value specified at memory object creation time.
You can operate with thisvalue attribute as an object property:
$memObject = $memoryManager->create($data);echo $memObject->value;$memObject->value = $newValue;$memObject->value[$index] = '_';echo ord($memObject->value[$index1]);$memObject->value = substr($memObject->value, $start, $length);Locked memory
Locked memory objects are always stored in memory. Data stored in locked memoryare never swapped to the cache backend.
Movable memory
Movable memory objects are transparently swapped and loaded to/from the cachebackend by theMemoryManager when necessary.
The memory manager does not swap objects with size less than the specifiedminimum, due to performance considerations. Seethe settings sectionfor more details.
Found a mistake or want to contribute to the documentation? Edit this page on GitHub!