How to automatically avoid variables in a Zend Framework 2 view

Many times in the Zend Framework 2 view, I will call $this->escapeHtml() to make sure my data is safe. Is there a way to switch this behavior from a blacklist to a white list?

PS: Read a Padraic Brady article that suggests auto-shielding is a bad idea . Additional thoughts?

+4
source share
2 answers

You can write your own ViewModel class that avoids data when variables are assigned to it.

+4
source

Thanks to Rob's comment, I expanded the ZM2 ViewModel as follows:

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

In the controller it can be used as follows:

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

Question: I would appreciate if anyone would comment on this, if this is the best practice or if there is a better one and ecp. more efficient and resource-saving way?

+1
source

Source: https://habr.com/ru/post/1433247/


All Articles