2

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?

George Brighton
  • 5,131
  • 9
  • 27
  • 36
Victor Odiah
  • 1,061
  • 11
  • 14

1 Answers1

2

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.

AlexP
  • 9,906
  • 1
  • 24
  • 43
  • The answer is definitely correct! Unfortunately there currently seems to be an issue with this solution: https://github.com/zendframework/zf2/issues/4221#issuecomment-47195693 – webDEVILopers Jun 26 '14 at 07:44
  • @Webdevilopers looking at `Zend\View\Renderer\PhpRenderer::__call()` I do think this is still a bug. [You can see it adds the helper to `__pluginCache` on the first call](https://github.com/zendframework/zf2/blob/master/library/Zend/View/Renderer/PhpRenderer.php#L396), then each subsequent call is then reusing this. It should *allways* try to fetch the plugin from the `ViewHelperManager` ([just like the `plugin()` method does](https://github.com/zendframework/zf2/blob/master/library/Zend/View/Renderer/PhpRenderer.php#L377)) as this will check the `shared` variable. – AlexP Jun 26 '14 at 12:39
  • I think that is what weierophinney is looking for in the issue! Can you post it there too please? – webDEVILopers Jun 26 '14 at 14:43
  • I added your suggestion to the issue: https://github.com/zendframework/zf2/issues/4221#issuecomment-47750073 – webDEVILopers Jul 02 '14 at 08:35
  • @Webdevilopers I checked out the latest branch to apply a fix but it has already been applied; I suggest you update. – AlexP Jul 02 '14 at 11:52
  • Which branch do you mean, can you post the link? Strange because the issue is still discussed @AlexP . – webDEVILopers Jul 02 '14 at 13:25
  • @webDEVILopers An [update to this](https://github.com/zendframework/zf2/pull/6786#event-200184584) - 2.4 Should fix the issue. – AlexP Dec 01 '14 at 12:17
  • Finally! :) @samsonasik – webDEVILopers Dec 01 '14 at 12:22