I am using a very simple template system to avoid having to work through super long html pages using "php include" as in the following:
For example, in my index.php file...
<!doctype html>
<html lang="en">
<?php include 'head.php'; ?>
<body>
<div>
<header><?php include 'nav.php'; ?></header>
<main>
<?php include 'article1.php'; ?>
<?php include 'article2.php'; ?>
<?php include 'article3.php'; ?>
</main>
<footer><?php include 'footer.php'; ?></footer>
</body>
</html>
The php components themselves (e.g., nav.php) are html files. In some cases these components, such as the footer.php will be duplicated in every main page. Is there an easy way to cache the main pages and/or their components (e.g., automatically generate static pages) on the server.
This looks hopeful, https://dzone.com/articles/how-to-create-a-simple-and-efficient-php-cache . Should I even be concern about caching? I know very little about php. I welcome your suggestions. Thanks
CodePudding user response:
If all you are doing is using include statements to wrangle templated pages, you shouldn't be too concerned about performance. The caching process outlined in the article you refer to is designed to reduce "expensive" complexity in script processing. For example, if you have to query a database and the data is not going to change often, it may be good to cache the result. Or if you have very complicated calculations, you may be able to cache common inputs to increase performance.
If you are interested in automatically generating static pages and then serving them, you can use output buffering and save the result to file. Then when someone visits the page, you check to see if the static page exists, if so, give them the contents of that, but if not, run your controller and save the results as a static page. Here is an example:
<?php
//check to see if static file exists
//if so, serve the contents and you're done.
if (file_exists('path/to/static/file/static-file.html')){
echo file_get_contents('path/to/static/file/static-file.html');
exit;
}
//call ob_start(); to begin buffering output
ob_start();
?>
<!doctype html>
<html lang="en">
<?php include 'head.php'; ?>
<body>
<div>
<header><?php include 'nav.php'; ?></header>
<main>
<?php include 'article1.php'; ?>
<?php include 'article2.php'; ?>
<?php include 'article3.php'; ?>
</main>
<footer><?php include 'footer.php'; ?></footer>
</body>
</html>
<?php
$staticFile = ob_get_contents();
file_put_contents('path/to/static/file/static-file.html', $staticFile);
?>
But remember when it comes to performance questions, it is always best to measure before you start addressing the issues. Performance bottlenecks may not be where you first suspect.
CodePudding user response:
You can use PHP built-in OPcache. You can read more about it from PHP manual.