PHP: faking templates
In PHP, how to use templates without a template engine?
Well, the nice way would be to use a template engine, like Twig for instance.
But let’s say you don’t want to use a template engine (for some reason), but you still want to avoid spaghetti code where the controller and view parts are mixed up…
I have an idea for this. Maybe it’s a stupid thing, but I’d share it here. So, without a template engine you can still separate the controller and the view. However, this separation will be in the same PHP file :) On the top you’ll have the controller, where you collect the necessary data, and right below it you will have the view, where you simply use the variables defined in the controller. Let’s see two examples:
<?php $c = array( 'name' => 'PHP', ); ?> <!DOCTYPE html> Hello <?= $c['name'] ?>!
Here, similarly to Twig, all data are collected in a hash. Now I call the hash simply “
c” instead of “
If you don’t want to use a hash, use simple variables. To make the variables that you want to use in the view part more visible, start their names with an underscore.
<?php $_name = 'PHP'; ?> <!DOCTYPE html> Hello <?= $_name ?>!
What is gained? The controller and the view are not mixed. Although they are still in the same file, they are separated (top and bottom part of the source).
It can be an easy way to avoid spaghetti code. However, as mentioned before, the ideal solution would be to use a real template engine.
We could call it the poor man’s templating system :)