zend framework2 - Calling a method in model from layout in Zendframework 2 -
i try in zendframework 2 call method in model form layout show user specific things. have tried in module.php in init , onbootstrap , tried declare variables available in layout.phtml, failed , have not found usefull.
you'd typically use view helper proxy model this
create view helper in application, eg.,
<?php namespace application\view\helper; use zend\view\helper\abstracthelper; class mymodelhelper extends abstracthelper { protected $model; public function __construct($model) { $this->model = $model; } public function mycoolmodelmethod() { return $this->model->method(); } }
you make available registering framework in module.php
file using getviewhelperconfig()
method , anomyous function factory compose helper, , inject model it's expecting
<?php namespace application; class module { public function getviewhelperconfig() { return array( 'factories' => array( 'mymodelhelper' => function($sm) { // either create new instance of model $model = new \fqcn\to\model(); // or, if model in servicemanager, fetch there //$model = $sm->getservicelocator()->get('modelservice') // create new instance of helper, injecting model uses $helper = new \application\view\helper\mymodelhelper($model); return $helper; }, ), ); } }
finally, in view (any view), can call helper, in turn calls models methods
// view.phtml <?php echo $this->mymodelhelper()->mycoolmodelmethod(); ?>
Comments
Post a Comment