I try in Zendframework 2 to call a method in model form layout to show some user specific things. I have tried to do it in Module.php in init and onBootstrap and tried to declare some variables that will be available in layout.phtml, but I failed and have not found anything usefull.
可以将文章内容翻译成中文,广告屏蔽插件可能会导致该功能失效(如失效,请关闭广告屏蔽插件后再试):
问题:
回答1:
You'd typically use a view helper as a proxy to your model for this
Create a view helper in your 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 then make it available by registering it with the framework in your Module.php
file using the getViewHelperConfig()
method and an anomyous function as a factory to compose your helper, and inject the model it's expecting
<?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, which in turn calls your models methods
// view.phtml
<?php echo $this->myModelHelper()->myCoolModelMethod(); ?>