4

I wanted the functionalities of view files to run in controller file also.

For example, I wanted $this->escapeHtml() which runs in view file alone to run in controller through some means like $this->...->escapeHtml()

Is this possible? Kindly help.

Wilt
  • 41,477
  • 12
  • 152
  • 203
Beniston
  • 542
  • 1
  • 8
  • 17
  • 3
    Try `$vhm = $sm->get('viewhelpermanager')`, then `$escaper = $vhm->get('escapehtml')` and at last `$myString = $escaper('string to escape')` – Sam Apr 05 '13 at 09:45
  • @Sam brief and accurate as always :) – Stoyan Dimov Apr 05 '13 at 10:01
  • Thank you Sam and Stoyan Dimov. One query: will there by any issues with case sensitivity? For example, Sam has used 'viewhelpermanager' (no caps) and Stoyan used 'ViewHelperManager' (camelcased) – Beniston Apr 05 '13 at 10:19
  • 1
    @Beniston No, internally all names will be normalized into lowercase, no-special-char, strings. So: `ViewHelperManager` equals `viewhelpermanager` equales `view-helper-manager`equals `View\Helper\Manager`. See https://github.com/zendframework/zf2/blob/master/library/Zend/ServiceManager/ServiceManager.php#L103 and https://github.com/zendframework/zf2/blob/master/library/Zend/ServiceManager/ServiceManager.php#L704 and https://github.com/zendframework/zf2/blob/master/library/Zend/ServiceManager/ServiceManager.php#L413 – Sam Apr 05 '13 at 11:03

1 Answers1

24

You need to get the ViewHelperManager and extract the EscapeHtml helper. This is a one example how to do it from the controller:

$viewHelperManager = $this->getServiceLocator()->get('ViewHelperManager');
$escapeHtml = $viewHelperManager->get('escapeHtml'); // $escapeHtml can be called as function because of its __invoke method       
$escapedVal = $escapeHtml('string');

Note that it is recommended to escape and display the output in the view scripts and not in the controller.

Stoyan Dimov
  • 5,250
  • 2
  • 28
  • 44