1. <?php
  2. /**
  3. * Configuration Loader for Scheduled Tasks.
  4. * Loads configuration from files, allowing for easy modification
  5. * without code changes.
  6. */
  7. class ConfigLoader
  8. {
  9. /**
  10. * Loads configuration from a file.
  11. *
  12. * @param string $filePath Path to the configuration file.
  13. * @return array|null An associative array representing the configuration,
  14. * or null if the file cannot be loaded.
  15. */
  16. public static function loadConfig(string $filePath): ?array
  17. {
  18. if (file_exists($filePath)) {
  19. $config = file_get_contents($filePath);
  20. if ($config !== false) {
  21. $config = json_decode($config, true); // Decode as associative array
  22. if (json_last_error() === JSON_ERROR_NONE) {
  23. return $config;
  24. } else {
  25. error_log("Error decoding JSON from file: " . json_last_error_msg());
  26. return null;
  27. }
  28. } else {
  29. error_log("Error reading file: " . $filePath);
  30. return null;
  31. }
  32. } else {
  33. error_log("Configuration file not found: " . $filePath);
  34. return null;
  35. }
  36. }
  37. /**
  38. * Gets a configuration value.
  39. *
  40. * @param array $config The configuration array.
  41. * @param string $key The key of the value to retrieve.
  42. * @param mixed $defaultValue The default value to return if the key
  43. * is not found.
  44. * @return mixed The value associated with the key, or the default
  45. * value if the key is not found.
  46. */
  47. public static function get(array $config, string $key, $defaultValue = null)
  48. {
  49. if (array_key_exists($key, $config)) {
  50. return $config[$key];
  51. } else {
  52. return $defaultValue;
  53. }
  54. }
  55. }
  56. // Example Usage (in your scheduled task script)
  57. // Load the configuration
  58. $config = ConfigLoader::loadConfig('config.json');
  59. if ($config) {
  60. // Access configuration values
  61. $startTime = ConfigLoader::get($config, 'start_time');
  62. $interval = ConfigLoader::get($config, 'interval', 60); // Default interval is 60 seconds
  63. $logFile = ConfigLoader::get($config, 'log_file', 'scheduled_task.log');
  64. $enabled = ConfigLoader::get($config, 'enabled', true);
  65. //Your scheduled task logic here, using the config values
  66. if ($enabled) {
  67. echo "Scheduled task started.\n";
  68. // ... your task code ...
  69. file_put_contents($logFile, date('Y-m-d H:i:s') . " - Task executed.\n", FILE_APPEND);
  70. } else {
  71. echo "Scheduled task is disabled.\n";
  72. }
  73. } else {
  74. echo "Failed to load configuration. Exiting.\n";
  75. }
  76. ?>

Add your comment