Using PHP templating has a significant drawback of being unable to automatically escape your variables when they are being displayed. So if you had avariable like “Fairy
I struggled to find a nice solution for this for a while, because obviously it had to be something short but I also wanted to stick to OOP as much as possible. The solution was to add a \View\Helper class with its instance being passed to each view. Methods of that class may also be aliased to shorter variables. The first method is output () and its alias $_()that will escape and print out a string. For example:
1
2
3
4
5
6
7
8
9
// inside a view
<!-- Old way -->
<div><?php echo $fairy->name; ?></div>
<!-- Using a helper. Rather long-->
<div><?php $helper->output($fairy->name);></div>
<!-- Using a shortcut -->
<div><?php $_($fairy->name); ?></div>
To add your own methods to the helper just extend the \PHPixie\View\Helper class.
Helper shortcuts are nothing special really, they are just variables that are autoassigned into your view (yes, $_ is a valid PHP variable name ). If you add your own methods to the Helper class you can assign them any alises you like. E.g.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
// /classes/App/View/Helper
namespace App\View;
class Helper extends \PHPixie\View\Helper{
protected $aliases = array(
'_' => 'output',
'_r' => 'repeat'
);
public function repeat($str, $times) {
for($i = 0;$i<$times; $i++)
echo $str;
}
}
Now you will be able to use the alias inside the view:
1
2
<!-- Will print <br/> 3 times -->
<?php $_r('<br/>',3) ?>
Hope you’ll like this new feature and enjoy the added security benefit of outputting filtered variables =]