<?php
/**
* Configuration Loader for Scheduled Tasks.
* Loads configuration from files, allowing for easy modification
* without code changes.
*/
class ConfigLoader
{
/**
* Loads configuration from a file.
*
* @param string $filePath Path to the configuration file.
* @return array|null An associative array representing the configuration,
* or null if the file cannot be loaded.
*/
public static function loadConfig(string $filePath): ?array
{
if (file_exists($filePath)) {
$config = file_get_contents($filePath);
if ($config !== false) {
$config = json_decode($config, true); // Decode as associative array
if (json_last_error() === JSON_ERROR_NONE) {
return $config;
} else {
error_log("Error decoding JSON from file: " . json_last_error_msg());
return null;
}
} else {
error_log("Error reading file: " . $filePath);
return null;
}
} else {
error_log("Configuration file not found: " . $filePath);
return null;
}
}
/**
* Gets a configuration value.
*
* @param array $config The configuration array.
* @param string $key The key of the value to retrieve.
* @param mixed $defaultValue The default value to return if the key
* is not found.
* @return mixed The value associated with the key, or the default
* value if the key is not found.
*/
public static function get(array $config, string $key, $defaultValue = null)
{
if (array_key_exists($key, $config)) {
return $config[$key];
} else {
return $defaultValue;
}
}
}
// Example Usage (in your scheduled task script)
// Load the configuration
$config = ConfigLoader::loadConfig('config.json');
if ($config) {
// Access configuration values
$startTime = ConfigLoader::get($config, 'start_time');
$interval = ConfigLoader::get($config, 'interval', 60); // Default interval is 60 seconds
$logFile = ConfigLoader::get($config, 'log_file', 'scheduled_task.log');
$enabled = ConfigLoader::get($config, 'enabled', true);
//Your scheduled task logic here, using the config values
if ($enabled) {
echo "Scheduled task started.\n";
// ... your task code ...
file_put_contents($logFile, date('Y-m-d H:i:s') . " - Task executed.\n", FILE_APPEND);
} else {
echo "Scheduled task is disabled.\n";
}
} else {
echo "Failed to load configuration. Exiting.\n";
}
?>
Add your comment