In PHP, how do I cache objects in vanilla PHP?

In vanilla PHP, you can cache objects using various strategies. One common method is to use file-based caching, where you serialize the object and store it in a file for later retrieval. This improves performance by reducing the need to recreate the object every time it's needed. Here’s a simple example of how to implement caching in PHP.

<?php // Caching function function cacheObject($key, $object) { $cacheFile = __DIR__ . '/cache/' . md5($key) . '.cache'; file_put_contents($cacheFile, serialize($object)); } // Retrieving cached object function getCachedObject($key) { $cacheFile = __DIR__ . '/cache/' . md5($key) . '.cache'; if (file_exists($cacheFile)) { return unserialize(file_get_contents($cacheFile)); } return null; } // Example object class SampleObject { public $name; public $value; public function __construct($name, $value) { $this->name = $name; $this->value = $value; } } // Usage $obj = new SampleObject('Test', 123); cacheObject('sample_key', $obj); $cachedObj = getCachedObject('sample_key'); if ($cachedObj) { echo "Object restored from cache: " . $cachedObj->name . " with value " . $cachedObj->value; } else { echo "No cached object found."; } ?>

caching php file-cache object-cache performance