Calling a method in model from layout in Zendframework 2
Asked Answered
C

1

0

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.

Candlenut answered 18/4, 2013 at 12:6 Comment(0)
M
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(); ?>
Mlle answered 18/4, 2013 at 12:24 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.