Question

I have implemented a Zend View Helper called contentByKey which renders some HTML in my CMS engine. I would like to implement it so that this View Helper is the only helper called within my markup (passed a key to find content in DB). When it attempts to build the HTML content, it needs to be able to dispatch another View Helpers render within the View Helper Class. My class implements AbstractHelper. See below:

class ContentByKey extends AbstractHelper{

public function __invoke($key){
    /* 1. Fetch content from DB and check type */

    /* 2. Content type = "foo";*/

    /* 3. NEEDED LOGIC - Invoke fooHelper here (needs to process additional logic before rendering so simply rendering a different script isnt enough) */
}

Should this not be the best method to implement what I need, I'd gladly accept any other suggestions.

Was it helpful?

Solution

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;
    }
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top