Here is example implementation of a custom view helper script.
Step 1.
Creating Zend Framework 2 Helper.
//file : App_folder/module/Module_name/src/Module_name/View/Helper/SayHello.php
namespace Application\View\Helper;
use Zend\View\Helper\AbstractHelper;
class SayHello extends AbstractHelper{
public function __invoke($name = 'Unnamed'){
return "$name , this is Zend Framework 2 View Helper";
}
}
Step 2.
Registering the Zend Framework 2 Helper.
//file : App_folder/module/Module_name/Module.php
public function getViewHelperConfig()
{
return array(
'factories' => array(
// the array key is the name of the invoke function that is called from view
'sayHello' => function($name) {
return new SayHello($name);
},
),
);
}
Step 3.
Using in Zend Framework 2 View.
//file : App_folder/module/Module_name/view/Module_name/index/index.phtml
echo $this->sayHello('Ivan Gospodinow');
Suggestions or problems ?
Write a comment.
Hi
I am unable to call this view form phtml file
Link | June 5th, 2013 at 10:10
Hello anil,
can you be a litthe more specific because I can not understand what is the problem.
Link | July 9th, 2013 at 10:47
Line 3 needs an echo statement for it to display anything 🙂
echo $this->sayHello(‘Ivan Gospodinow’);
Link | June 18th, 2014 at 16:52
I did a small change in the step 2:
return new View\Helper\GetSiteUrl();
It works fine after that for me.
Thank you for your great post.
Link | July 21st, 2014 at 10:21
Can I pass back a partial or a file with php and html from invoke?
Link | December 10th, 2014 at 21:48