Calling a method in model from layout in Zendframe

2019-03-04 16:11发布

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条回答
放我归山
2楼-- · 2019-03-04 17:04

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(); ?>
查看更多
登录 后发表回答