从Zendframework 2中的布局调用模型中的方法 [英] Calling a method in model from layout in Zendframework 2

查看:75
本文介绍了从Zendframework 2中的布局调用模型中的方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我尝试在Zendframework 2中调用模型表单布局中的方法,以显示一些特定于用户的内容.我试图在init和onBootstrap的Module.php中做到这一点,并试图声明一些可以在layout.phtml中使用的变量,但是我失败了,没有发现任何有用的东西.

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.

推荐答案

您通常会使用视图助手作为此模型的代理

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();
    }
}

然后您可以使用getViewHelperConfig()方法将其注册到Module.php文件中的框架并将其作为工厂的辅助函数,并将其注入期望的模型,从而使其可用

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(); ?>

这篇关于从Zendframework 2中的布局调用模型中的方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆