PHP Classes

PHP Preemptive Cache: Cache a limited amount of data records in memory

Recommend this page to a friend!
  Info   View files Example   View files View files (18)   DownloadInstall with Composer Download .zip   Reputation   Support forum (1)   Blog (2)    
Ratings Unique User Downloads Download Rankings
Not enough user ratingsTotal: 284 This week: 1All time: 7,559 This week: 560Up
Version License PHP version Categories
preemptive-cache 1.1MIT/X Consortium ...5.3PHP 5, Cache
Description 

Author

This class can cache a limited amount of data records in memory.

It takes a callable function as parameter that will be used to retrieve data records to be cached.

When the application needs to fetch a data record, the class will call the given callable function if the record with a given id is not yet cached in memory in class array.

The class will maintain up to a given limit of cached data records in memory.

Innovation Award
PHP Programming Innovation award nominee
September 2015
Number 2
Some algorithms need to access information records multiple times during the execution of the algorithm.

For this type of algorithm it more efficient to keep the most frequently accessed records of information memory.

This class implements a caching method that does that. It retrieves data records into a cache array up to a limited amount of records so it avoids using too much memory.

The use of configurable callback function allows it to be used to retrieve cached records from virtually any type of data source.

Manuel Lemos
Picture of Joseluis Laso
  Performance   Level  
Name: Joseluis Laso <contact>
Classes: 16 packages by
Country: Spain Spain
Age: 56
All time rank: 92519 in Spain Spain
Week rank: 106 Up5 in Spain Spain Up
Innovation award
Innovation award
Nominee: 6x

Winner: 2x

Example

<?php

$startTime
= intval(date("U"));

require_once
__DIR__.'/../vendor/autoload.php';

use
JLaso\ToolsLib\ProgressBar;
use
JLaso\ToolsLib\PreEmptiveCache;

$options = getopt("h::u::p::d::");

$host = isset($options['h']) ? $options['h'] : 'localhost';
$user = isset($options['u']) ? $options['u'] : 'root';
$password = isset($options['p']) ? $options['p'] : '';
$database = isset($options['d']) ? $options['d'] : 'test';

$conn = mysqli_connect($host, $user, $password, $database);

if (!
$conn){
    die(
mysqli_error($conn));
}

$nRecords = mysqli_query($conn, 'SELECT COUNT(*) AS `qty` FROM `data`;')
    ->
fetch_object()
    ->
qty;

$xml = new DOMDocument("1.0");
$xml->formatOutput = true;
$xml->encoding = 'UTF-8';

$root = $xml->appendChild(new DOMElement('records'));

$debug = false;

if (!
$debug) {
   
$pBar = new ProgressBar($nRecords);
}

$familyCache = new PreEmptiveCache(function($id) use ($conn){
    return
mysqli_query(
       
$conn,
       
sprintf(
           
'SELECT `p`.`name` AS `product_name`, `p`.`ratio` AS `product_ratio`, '.
           
'`p`.`family_id` AS `family_id`, `f`.`name` AS `family_name`, `f`.`ratio` AS `family_ratio` ' .
           
'FROM `product` as `p` '.
           
'LEFT JOIN `family` AS `f` ON `p`.`family_id`=`f`.`id` '.
           
'WHERE `p`.`id`= %d',
           
$id
       
)
    )->
fetch_assoc();
}, array(
   
'maxRecordsCached' => 99999,
   
'mode' => PreEmptiveCache::LESS_OLDEST_MODE,
   
'debug' => $debug,
));

$totalCost = 0;
$offset = 0;
while (
$offset < $nRecords){

   
$record = mysqli_query($conn, 'SELECT * FROM `data` LIMIT 1 OFFSET '.$offset)->fetch_assoc();

   
$xmlRecord = $root->appendChild(new DOMElement('record'));
   
$xmlRecord->setAttribute('id', $record['id']);
   
$xmlRecord->appendChild(new DOMElement('family', $record['product_id']));
   
$xmlRecord->appendChild(new DOMElement('cost', $record['cost']));

   
$product = $familyCache->fetch($record['product_id']);

   
$productRatio = isset($product['product_ratio']) ? $product['product_ratio'] : 0;
   
$familyRatio = isset($product['family_ratio']) ? $product['family_ratio'] : 0;
   
$realCost = $record['cost'] * $productRatio * $familyRatio;

   
$xmlRecord->appendChild(new DOMElement('relative_cost', $realCost));
   
$xmlRecord->appendChild(new DOMElement('product', $product['product_name']));

   
$totalCost += $realCost;
   
$offset++;

    if (!
$debug){
       
$pBar->updateValue($offset);
    }
}

print
"\n";

$xml->appendChild(new DOMElement('total_cost', $totalCost));
print
$xml->saveXML();

print
sprintf("this script lasted %d seconds !\n", intval(date("U")-$startTime));


Details

PreEmptiveCache

A little class to help improve our scripts that access to a large quantity of data.

A class to document the article I published on PHPClasses.

Once the repo is in your drive run `composer dumpautoload` in order to generate the appropriate autoload files.


  Files folder image Files  
File Role Description
Files folder imageexample (3 files, 1 directory)
Files folder imagesrc (3 files, 1 directory)
Files folder imagevendor (1 file, 1 directory)
Accessible without login Plain text file composer.json Data Auxiliary data
Accessible without login Plain text file LICENSE Lic. License text
Accessible without login Plain text file README.md Doc. Documentation

  Files folder image Files  /  example  
File Role Description
Files folder imagesample-db (2 files)
  Accessible without login Plain text file sample-analysis.php Aux. Sample analysys script
  Accessible without login Plain text file sample-optimized.php Example Sample optimized script
  Accessible without login Plain text file sample-unoptimized.php Aux. Sample unoptimized script

  Files folder image Files  /  example  /  sample-db  
File Role Description
  Accessible without login Plain text file create-sample-data.php Aux. Example script
  Accessible without login Plain text file creation.sql Data Auxiliary data

  Files folder image Files  /  src  
File Role Description
Files folder imagewords (1 file)
  Accessible without login Plain text file PreEmptiveCache.php Class Class source
  Accessible without login Plain text file ProgressBar.php Class Class source
  Accessible without login Plain text file RandomTokenizer.php Class Class source

  Files folder image Files  /  src  /  words  
File Role Description
  Accessible without login Plain text file words.txt Data Auxiliary data

  Files folder image Files  /  vendor  
File Role Description
Files folder imagecomposer (5 files)
  Accessible without login Plain text file autoload.php Aux. Auxiliary script

  Files folder image Files  /  vendor  /  composer  
File Role Description
  Accessible without login Plain text file autoload_classmap.php Aux. Auxiliary script
  Accessible without login Plain text file autoload_namespaces.php Aux. Auxiliary script
  Accessible without login Plain text file autoload_psr4.php Aux. Auxiliary script
  Accessible without login Plain text file autoload_real.php Aux. Auxiliary script
  Accessible without login Plain text file ClassLoader.php Aux. Auxiliary script

 Version Control Unique User Downloads Download Rankings  
 100%
Total:284
This week:1
All time:7,559
This week:560Up