A view helper is constructed by the view helper plugin manager (or, Zend\View\HelperPluginManager
). This manager injects the view renderer object in every view helper (see getView()
/setView()
on GitHub). It enables you to call other helpers:
<?php
use Zend\View\Helper\AbstractHelper;
class ContentByKey extends AbstractHelper
{
public function __invoke($key)
{
// fetch data from database
// $text = ...
// example: translate this text via the translator
$translated = $this->getView()->translate($text);
return $translated;
}
}
It's quite a common way to do these things, so it's OK to do this. Alternatively, you could inject the view helper in your own helper. The example gets a bit skewed, as you would inject a Translator object instead of the translate view helper, but anyhow:
<?php
use Zend\View\Helper\AbstractHelper;
use Zend\I18n\View\Helper\Translate as TranslateHelper;
class ContentByKey extends AbstractHelper
{
protected $translate;
public function __construct(TranslateHelper $translate)
{
$this->translate = $translate;
}
public function __invoke($key)
{
// fetch data from database
// $text = ...
// example: translate this text via the translator
$translated = $this->translate($text);
return $translated;
}
}
You have to inject the helper this way, so you need to create a factory for your helper:
<?php
use Zend\ServiceManager\FactoryInterface;
use Zend\ServiceManager\ServiceLocatorInterface;
use MyModule\View\Helper\ContentByKey;
class ContentByKeyFactory implements FactoryInterface
{
public function createService(ServiceLocatorInterface $serviceLocator)
{
$viewManager = $serviceLocator->get('ViewHelperManager');
$translate = $viewManager->get('translate');
$helper = new ContentByKey($translate);
return $helper;
}
}