5

I have earlier asked this question, and I got good answers there. However, that was for beta4, and no longer works.

So where and how do I add my own view helpers to ZF2?

2 Answers 2

17

You should add them to your module.config.php under view_helpers like this:

'view_manager' => array(
    'template_path_stack' => array(
        'ModuleName' => __DIR__ . '/../view',
    ),
),

'view_helpers' => array(
    'factories' => array(
        'showmessages' => function($sm) {
            $helper = new ModuleName\Helper\MessageShower();
            // do stuff with $sm or the $helper
            return $helper;           
        },
    ),
    'invokables' => array(
        'selectmenu' => 'ModuleName\Helper\SelectMenu',   
        'prettyurl'  => 'ModuleName\Helper\PrettyUrl',
    ),  
),

Here I show two ways of creating the helpers. If all they need to do is to be instantiated, just add their name (including namespace) as invokables. If you need to do stuff with them or the ServiceManager, create them through the factories keyword.

Sign up to request clarification or add additional context in comments.

Comments

1

The beta5 had a BC regarding the servicemanager. This applies for the view helper manager as well. Have a look here - there's even an example for view helpers a bit down too.

1 Comment

Thanks. I knew about the BC break, but couldn't find out how to add helpers. This was what I needed to make it work. Will probably post a working example as an answer for others to see.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.