当前位置: 动力学知识库 > 问答 > 编程问答 >

zend framework2 - ZF2 custom view helper shares variable across multiple elements - shared service issue?

问题描述:

I successfully added a custom view helper with the following configuration:

https://gist.github.com/webdevilopers/b22f7471fd2b8d60cdea#file-module-php

The view helper has a custom variable named foo:

https://gist.github.com/webdevilopers/b22f7471fd2b8d60cdea#file-abstractformautocomplete-php

As I mentioned this setup works fine as long as I have only a single element using the view helper.

As soon as I add more than one form element the setFoo method gets only called once and the foo variable remains set throughout the following elements.

https://gist.github.com/webdevilopers/b22f7471fd2b8d60cdea#file-autocompleteform-php

I read about Shared Services in ZF2 - is this such a case? How can I prevent this behaviour?

Introduction to the Zend Framework 2 ServiceManager

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.

网友答案:

You've basically answered your own question here. Services are shared by default, so the initial instance of your view helper is reused for subsequent calls unless you configure it otherwise. To do this, add the shared parameter to your view helper config (untested):

public function getViewHelperConfig()
{
    return array(
        'invokables' => array(
            'formelement'                  => 'Application\Form\View\Helper\FormElement',
            'formautocompletehidden'       => 'Application\Form\View\Helper\FormAutocompleteHidden'
        ),
        'shared' => array(
            'formelement' => false,
            'formautocompletehidden' => false
        ),
    );
}

Edit: as mentioned in the comments, this doesn't currently work for view helpers due to a bug in ZF2.

分享给朋友:
您可能感兴趣的文章:
随机阅读: