What are some best practices for caching templates in PHP to optimize speed?

Caching templates in PHP can significantly improve the speed of your application by reducing the time needed to render the same template multiple times. One common approach is to store the compiled template in a cache file and check if it needs to be recompiled on each request. This way, you can avoid the overhead of parsing and compiling the template each time it is requested.

// Check if the cached template exists and is still valid
$cachedTemplate = 'path/to/cache/template.php';
if (file_exists($cachedTemplate) && filemtime($cachedTemplate) > filemtime('path/to/original/template.php')) {
    include $cachedTemplate;
} else {
    ob_start();
    // Render the original template
    include 'path/to/original/template.php';
    $renderedTemplate = ob_get_clean();
    
    // Save the rendered template to the cache file
    file_put_contents($cachedTemplate, $renderedTemplate);
    
    echo $renderedTemplate;
}