pandorafms/pandora_console/include/rest-api/models/CachedModel.php

105 lines
2.7 KiB
PHP
Raw Normal View History

2019-05-20 15:15:54 +02:00
<?php
declare(strict_types=1);
namespace Models;
use Models\Model;
/**
* This class should be extended to add functionalities to
* fetch, clear and save item cache.
*/
2019-05-27 12:10:05 +02:00
abstract class CachedModel extends Model
2019-05-20 15:15:54 +02:00
{
/**
* Used to decide if the cache should also be indexed by user or not.
*
* @var boolean
*/
protected static $indexCacheByUser = false;
2019-05-20 15:15:54 +02:00
/**
* Obtain a data structure from the database using a filter.
*
* @param array $filter Filter to retrieve the modeled element.
*
* @return array The modeled element data structure stored into the DB.
* @throws \Exception When the data cannot be retrieved from the DB.
*
* @abstract
*/
abstract protected static function fetchCachedData(array $filter);
/**
* Stores the data structure obtained.
*
* @param array $filter Filter to retrieve the modeled element.
* @param array $data Data to store in cache.
2019-05-20 15:15:54 +02:00
*
* @return array The modeled element data structure stored into the DB.
* @throws \Exception When the data cannot be retrieved from the DB.
*
* @abstract
*/
2019-05-27 12:10:05 +02:00
abstract protected static function saveCachedData(
array $filter,
array $data
): bool;
2019-05-20 15:15:54 +02:00
/**
* Deletes previous data that are not useful.
*
* @param array $filter Filter to retrieve the modeled element.
*
* @return array The modeled element data structure stored into the DB.
* @throws \Exception When the data cannot be retrieved from the DB.
*
* @abstract
*/
abstract protected static function clearCachedData(array $filter): int;
/**
* Obtain a model's instance from the database using a filter.
*
* @param array $filter Filter to retrieve the modeled element.
*
* @return self A modeled element's instance.
*
* @overrides Model::fromDB.
*/
2020-03-26 12:29:38 +01:00
public static function fromDB(array $filter, ?float $ratio=0): Model
2019-05-20 15:15:54 +02:00
{
global $config;
2020-02-20 13:25:56 +01:00
$save_cache = false;
2020-03-26 12:29:38 +01:00
if ($ratio == 0 && $filter['cache_expiration'] > 0) {
2020-02-20 13:25:56 +01:00
$data = static::fetchCachedData($filter);
$save_cache = true;
}
if (isset($data) === false) {
2020-03-26 12:29:38 +01:00
$data = static::fetchDataFromDB($filter, $ratio);
2020-02-20 13:25:56 +01:00
} else {
// Retrieved from cache.
$save_cache = false;
}
if ($save_cache === true) {
// Rebuild cache.
if (static::saveCachedData($filter, $data) !== true) {
throw new \Exception(
$config['dbconnection']->error
2019-05-20 15:15:54 +02:00
);
}
}
return static::fromArray($data);
2019-05-20 15:15:54 +02:00
}
}