ZF2: Accessing View Helpers in Controllers

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.

Be First to Comment

Leave a Reply

Your email address will not be published. Required fields are marked *