i've created a custom service as php class ( ServiceClass ) with some functions ( generateInfo() ) and i'm looking for a way to call this function from other views
thanks for help.
i've created a custom service as php class ( ServiceClass ) with some functions ( generateInfo() ) and i'm looking for a way to call this function from other views
thanks for help.
You can create your own View Helper
namespace MyModule\View\Helper;
use Zend\View\Helper\AbstractHelper;
class MyHelper extends AbstractHelper
{
public function __invoke()
{
return $this;
}
public function render($arg1, $arg2)
{
return 'My Parametrizable Html ' . $arg1 . ' ' . $arg2;
}
public function generateInfo()
{
return 'Your HTML goes here';
}
}
Now create an entry in the module.config.php for that helper:
'view_helpers' => array(
'invokables' => array(
'myHelper' => 'MyModule\View\Helper\MyHelper',
),
),
And now you can call it in your views:
<?php echo $this->myHelper()->render($arg1, $arg2); ?>
And for calling the generateInfo():
<?php echo $this->myHelper()->generateInfo(); ?>
You can also call it from a controller:
$viewHelperManager = $this->getServiceLocator()->get('ViewHelperManager');
$myHelper = $viewHelperManager->get('myHelper');
Without View Helper
Not the best practice because this generates repeated code but, if you do not want to create a View Helper, then you can always create an instance of your service in a controller and then pass it to the View.