1. <?php
  2. /**
  3. * Serializes API response objects for temporary storage with graceful failure handling.
  4. *
  5. * @param mixed $obj The object to serialize.
  6. * @param string $filename The filename to store the serialized data.
  7. * @return bool True on success, false on failure.
  8. */
  9. function serializeApiResponse(mixed $obj, string $filename): bool
  10. {
  11. try {
  12. // Serialize the object.
  13. $serializedData = serialize($obj);
  14. // Write the serialized data to the file.
  15. $result = file_put_contents($filename, $serializedData);
  16. // Check if the file write was successful.
  17. if ($result === false) {
  18. // Handle file write failure.
  19. error_log("Failed to write to file: " . $filename);
  20. return false;
  21. }
  22. return true;
  23. } catch (Exception $e) {
  24. // Handle any other exceptions.
  25. error_log("Serialization or file write error: " . $e->getMessage());
  26. return false;
  27. }
  28. }

Add your comment