Note. I use the Zend Framework, but I think most of them relate to PHP coding in general.
I'm trying to choose a strategy for writing view scripts, possibly using a template engine. Motives: clarity and security . I'm just not happy with writing .phtml scripts. This syntax is horribly detailed to do the most often required thing - the output of a variable:
<?php echo $this->escape($this->myVariable); ?>
In addition to the duration of the IMHO code, the template author does not need to remember (and disturb) the evacuation call record every time he / she wants to output a variable. Forgetting a call will almost certainly lead to an XSS vulnerability.
I have two possible solutions to this problem:
Solution 1: automatic screening template engine
I think that at least Smarty has the ability to automatically escape html objects when outputting variables. There are points against Smarty , but perhaps at least some of them are considered in the upcoming 3.0 - I have not tested it yet.
XML-based mechanisms such as PHPTAL will also delete any default data. However, they may seem strange to a beginner. Maybe worth a try?
Solution 2: avoid data in the model
Of course, another option would be to avoid the necessary data already in the Model (or even the controller?). The model should already know the type of content (mostly plain text or HTML text) for each field, so it would be logical to avoid the data. A view can view all data as safe HTML. This would allow, for example. changing the field data type from plain text to HTML without touching the script view - only by changing the model.
But then again, this does not seem like good MVC practice. In addition, there are problems with this approach:
- sometimes the view only wants to print the first n characters, and we don’t want to finish trimming the data
foo & bar like foo &am (first ran away from it like foo & bar ) - Perhaps the view wants to build a URL with varName = $ varName in querystring - again, escaping in the Model will be bad.
(These problems can be solved by providing two versions of the data or by canceling it in the template. It seems bad to me.)
Ideas? Am I missing something? What do you consider "best practice"?
PS. This article focuses on finding a common solution for any custom text data that may contain < or > or any other characters. Thus, filtering data before storing it in the database is not a solution.
Update:
Thanks for all the comments. I have done some more research and will be evaluating Twig and possibly the Open Power Pattern . Both seem interesting: Twig looks very simple, but the project is young. On the XML side, the OPT syntax looks a little better than PHPTAL. Both Twig and OPT are well documented.