Does PHP cache include
requests? I was wondering how to clean up my code and I thought about using a bit more includes
. Consider the following scheme.
[foreach answer] [include answer.tpl.php] [/foreach]
This would require to include answer.tpl.php
hundreds of times.
Does it cache? Will it have a worth-considering affect on performance? Is that considered a good practice? Bad?
In response to @Aaron Murray answer
No, that won't work. The mere concept of _once
is to prevent including the same file more than once. (to prevent errors caused by e.g. overwriting constant values)
Practical example would look like this:
# index.php
<?php
$array = array('a', 'b', 'c');
$output = '';
foreach($array as $e)
{
$output .= require_once 'test.php';
}
echo $output;
# test.php
<?php
return $e;
Does PHP cache
include
requests?
As far as I know, PHP does not cache includes by default. But your underlying filesystem will likely do this. So accessing the same file over and over again as in your example should be quite fast after all.
If you run into actual problems, you would first need to profile the application to find out where the actual bottleneck is. So unless you did not run into any problems yet, I would consider using the include not harmful.
Regarding the good practice, I think this is fairly well explained in this article: When Flat PHP meets Symfony.
This is no high design here, it's just to show the picture how you can start to make things more modular. You should be able to take the code 1:1 from your include file, just take care all needed template variables are passed into the function (don't use globals for that, it will stand in your way sooner or later):
# in your answer.tpl.php
function answer_template(array $vars) {
extract($vars);
... your template code ...
}
# your script
array = array('a', 'b', 'c');
$output = '';
require('answer.tpl.php');
foreach($array as $e)
{
$output .= answer_template(compact('e'));
}
echo $output;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With