<?php
/**
* Caches web form results for internal tooling.
*
* This function takes form data and stores the results in a cache
* for later retrieval. This avoids redundant processing of
* the same form data, improving performance.
*
* @param array $formData The form data as an associative array.
* @param string $cacheKey A unique key for the cache entry.
* @param int $cacheExpiryTime Time to live for the cache entry in seconds. Defaults to 3600 (1 hour).
* @param callable $resultCallback A function that takes the form data and returns the result.
* @return array|null The result of the resultCallback or null if the data is not cached.
*/
function cacheFormResults(array $formData, string $cacheKey, int $cacheExpiryTime = 3600, callable $resultCallback): ?array
{
// Define the cache store (using a simple array for demonstration. Consider using a more robust cache system like Redis or Memcached in production).
static $cache = [];
// Check if the data is already in the cache.
if (isset($cache[$cacheKey])) {
// Data found in cache, and it hasn't expired.
$cachedResult = $cache[$cacheKey];
// Check if the cache entry has expired.
if ($cachedResult['expiry'] > time()) {
// Cache entry is valid.
return $cachedResult['result'];
} else {
// Cache entry has expired. Remove it.
unset($cache[$cacheKey]);
}
}
// If data not found in cache or expired, calculate the result.
$result = $resultCallback($formData);
// Store the result in the cache with an expiry time.
$cache[$cacheKey] = [
'result' => $result,
'expiry' => time() + $cacheExpiryTime,
];
return $result;
}
/**
* Example usage: Simulates a form submission and retrieves the result.
*/
function processForm(array $formData): array
{
// Simulate some form processing.
sleep(1); // Simulate a time-consuming operation
// Example: Check if a required field is present.
if (empty($formData['name'])) {
return ['error' => 'Name is required'];
}
// Simulate some calculation.
$result = [
'message' => 'Form processed successfully!',
'data' => $formData,
];
return $result;
}
// Example usage:
$form_data = [
'name' => 'John Doe',
'email' => 'john.doe@example.com',
'age' => 30,
];
$cache_key = 'form_result_' . md5(json_encode($form_data)); //Generate a unique key based on the form data
$result = cacheFormResults($form_data, $cache_key, 60, 'processForm'); //Cache for 60 seconds
if ($result !== null) {
echo "Result: " . json_encode($result) . "\n";
} else {
echo "No result found in cache.\n";
}
//Demonstrate retrieving the cached result
$form_data2 = [
'name' => 'John Doe',
'email' => 'john.doe@example.com',
'age' => 30,
];
$cache_key2 = 'form_result_' . md5(json_encode($form_data2)); //Generate a unique key based on the form data
$result2 = cacheFormResults($form_data2, $cache_key2, 60, 'processForm'); //Retrieve the result from the cache
if ($result2 !== null) {
echo "Result from cache: " . json_encode($result2) . "\n";
} else {
echo "No result found in cache.\n";
}
?>
Add your comment