Domanda

How do I instantiate multiple instances of a view helper plugin in Zend 2?

I want to return a new instance every time I call $this->pluginName(); from the view.

How do I return a new instance of the view plugin?

È stato utile?

Soluzione

Add the service name to the getViewHelperConfig() shared configuration key in Module.php and set this value to false

Module.php

function getViewHelperConfig()
{
  return array(
    'shared' => array(
      'MyViewHelper' => false,
    ),
    'factories' => array(
      'MyViewHelper' => 'App\View\Helper\MyViewHelperFactory',
    )
  );
}

By adding 'MyViewHelper' => false, the service manager (or View Helper plugin manager) will create a new instance of that service each time it is used.

The documentation states

shared An array of service name/boolean pairs, indicating whether or not a service should be shared. By default, the ServiceManager assumes all services are shared, but you may specify a boolean false value here to indicate a new instance should be returned.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top