4

在 Zend Framework 2 视图中,我会多次调用$this->escapeHtml()以确保我的数据是安全的。有没有办法将此行为从黑名单切换到白名单?

PS:阅读 Padraic Brady 的一篇文章,该文章表明自动转义是一个坏主意。额外的想法?

4

2 回答 2

4

您可以编写自己的ViewModel类,当变量分配给它时转义数据。

于 2012-09-21T18:33:41.687 回答
1

感谢 Rob 的评论,我将 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;
}
}

在 Controller 中可以这样使用:

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]);
}

问题: 如果有人能发表评论,如果这是最佳实践或者是否有更好的和 ecp,我将不胜感激。更高效和节省资源的方式?

于 2015-10-06T20:52:07.650 回答