ZF2: Accessing View Helpers in Controllers
Published on July 4, 2014 by Bo Andersen
Generally speaking, view helpers should not be used within controllers, as the name suggests. Certain situations may, however, require one to do so. This article shows you just how to do that by fetching the view helper manager from the service manager. It is actually very simple.
public function someAction()
{
$userData = 'User data to escape';
$viewHelperManager = $this->getServiceLocator()->get('ViewHelperManager');
$escapeHtml = $viewHelperManager->get('escapeHtml');
$escapedData = $escapeHtml($userData);
}
The above is merely an example that uses the escapeHtml view helper. Replace the string with any other view helper that you may need to use. Notice that the $escapeHtml variable is used as a function. That is possible because the view helper implements the magic __invoke method, which is called when an object is used as a function.
Simple stuff, right? I hope this small code snippet helped someone. Thank you for reading.
Here is what you will learn:
- Understand the theory of Zend Framework in details
- How to implement an enterprise-ready architecture
- Develop professional applications in Zend Framework
- Proficiently work with databases in Zend Framework
- ... and much more!