4

Zend Framework 2 のビューでは$this->escapeHtml()、データが安全であることを確認するために何度も呼び出します。この動作をブラックリストからホワイトリストに切り替える方法はありますか?

PS:自動エスケープが悪い考えであることを示唆する Padraic Brady の記事を読んでください。追加の考え?

4

2 に答える 2

4

ViewModel変数が割り当てられたときにデータをエスケープする独自のクラスを作成できます。

于 2012-09-21T18:33:41.687 に答える
1

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

質問: これがベスト プラクティスなのか、それともより良い ECP があるのか​​、誰かがコメントしてくれれば幸いです。より効率的でリソースを節約する方法は?

于 2015-10-06T20:52:07.650 に答える