Calling a method in a model from a layout in Zendframework 2

I am trying in Zendframework 2 to call a method in a model form layout to show some user-specific things. I tried to do this in Module.php in init and onBootstrap and tried to declare some variables that would be available in layout.phtml, but I failed and did not find anything useful.

0
source share
1 answer

Usually you use the view helper as a proxy for your model for

Create a view helper in the application, for example.

<?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 can then make it available by registering it with the framework in your Module.php file using the getViewHelperConfig() method and an anomalous function like factory to compose your helper and enter a model that expects

 <?php namespace Application; class Module { public function getViewHelperConfig() { return array( 'factories' => array( 'myModelHelper' => function($sm) { // either create a new instance of your model $model = new \FQCN\To\Model(); // or, if your model is in the servicemanager, fetch it from there //$model = $sm->getServiceLocator()->get('ModelService') // create a new instance of your helper, injecting the model it uses $helper = new \Application\View\Helper\MyModelHelper($model); return $helper; }, ), ); } } 

Finally, in your view (any view) you can call your helper, who, in turn, calls the methods of your models.

  // view.phtml <?php echo $this->myModelHelper()->myCoolModelMethod(); ?> 
+1
source

Source: https://habr.com/ru/post/944966/


All Articles