Reputation: 12877
I'm trying to come up with a template system that enables inheritance and extension so the final page is the result of different layers of templates written by different developers / designers. I can't think of any other way than to store the template in a variable that can be searched through and manipulated by string replacement functions. I really don't quite like this way but is there any other way to achieve this?
If I have to do it this way, that is to store templates in variables and then echo them, what's the difference performance-wise (speed and memory usage) than to include a file containing the template?
// file1.php
<?php
$string = 'abcdef';
echo $string;
// file2.php
abcdef
// file3.php
<?php
include 'file1.php';
/* Or */
include 'file2.php';
Considering a very large string in $string such as over 1MB or even larger, which approach is better in terms of performance and memory usage?
Upvotes: 2
Views: 165
Reputation: 9606
I've tried this my self and found Output Control Functions to be very useful for creating an inheritance template engine.
The actual implementation can get quite complicated so I'm not going to go into any implementation details.
Basically, you capture output using an output buffer. You can create an inheritance heirarchy by building up layers of output buffers and then keep/discard/combine the output in various ways.
Have a look through the documentation. If you have further questions, then come back and ask another specific question.
As to performance, buffering output means you can return the entire rendered output in one hit rather than each echo statement. I believe this does improve performance.
Also, consider the difference between existing template engine implementations. Engines that use string replace and eval for things like {{include template}}
vs <?php include('template') ?>
where include()
buffers the output of template.php and then inserts it into the page (which may also be the result of a similar call). I think the latter would be more efficient (though I have no proof or stats to back that up).
Upvotes: 1