从Zendframework 2中的布局调用模型中的方法

时间:2013-04-18 12:06:54

标签: model-view-controller zend-framework2

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

1 个答案:

答案 0 :(得分:1)

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

在您的应用程序中创建一个视图助手,例如,

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

然后通过使用Module.php方法在getViewHelperConfig()文件中使用框架注册它,并使用anomyous函数作为工厂来编写帮助程序,并注入它期望的模型 p>

<?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;
                 },
             ),
        );
    }
}

最后,在您的视图(任何视图)中,您可以调用您的帮助程序,然后调用您的模型方法

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