ZF2: Accessing View Helpers in Controllers

Published on July 4, 2014 by

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.

Featured

Learn Zend Framework today!

Take an online course and become a ZF2 ninja!

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!
Zend Framework logo
Author avatar
Bo Andersen

About the Author

I am a back-end web developer with a passion for open source technologies. I have been a PHP developer for many years, and also have experience with Java and Spring Framework. I currently work full time as a lead developer. Apart from that, I also spend time on making online courses, so be sure to check those out!

Leave a Reply

Your e-mail address will not be published.