[英]How to automatically escape variables in a Zend Framework 2 view
在Zend Framework 2視圖中,很多時候我會調用$this->escapeHtml()
來確保我的數據是安全的。 有沒有辦法將這種行為從黑名單切換到白名單?
PS:請閱讀Padraic Brady的一篇文章,該文章建議自動轉義是個壞主意 。 還有其他想法嗎?
您可以編寫自己的ViewModel
類,該類在將變量分配給它時轉義數據。
感謝Robs的評論,我將ZF2 ViewModel擴展如下:
namespace Application\View\Model;
use Zend\View\Model\ViewModel;
use Zend\View\Helper\EscapeHtml;
class EscapeViewModel extends ViewModel
{
/**
* @var Zend\View\Helper\EscapeHtml
*/
protected $escaper = null;
/**
* Proxy to set auto-escape option
*
* @param bool $autoEscape
* @return ViewModel
*/
public function autoEscape($autoEscape = true)
{
$this->options['auto_escape'] = (bool) $autoEscape;
return $this;
}
/**
* Property overloading: get variable value;
* auto-escape if auto-escape option is set
*
* @param string $name
* @return mixed
*/
public function __get($name)
{
if (!$this->__isset($name)) {
return;
}
$variables = $this->getVariables();
if($this->getOption('auto_escape'))
return $this->getEscaper()->escape($variables[$name]);
return $variables[$name];
}
/**
* Get instance of Escaper
*
* @return Zend\View\Helper\EscapeHtml
*/
public function getEscaper()
{
if (null === $this->escaper) {
$this->escaper = new EscapeHtml;
}
return $this->escaper;
}
}
在控制器中,可以這樣使用:
public function fooAction()
{
return new EscapeViewModel(array(
'foo' => '<i>bar</i>'
));
//Turn off auto-escaping:
return new EscapeViewModel(array(
'foo' => '<i>bar</i>'
),['auto_escape' => false]);
}
問題:如果有最佳實踐者,或者有更好和更有效的方法,我會很感激。 更有效和節省資源的方式?
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.