0
我嘗試在Zendframework 2中調用模型表單佈局中的方法來顯示某些用戶特定的內容。我試圖在init和onBootstrap中的Module.php中做到這一點,並嘗試聲明一些將在layout.phtml中可用的變量,但是我失敗了並且沒有發現任何有用的東西。在Zendframework中調用模型中的佈局2
我嘗試在Zendframework 2中調用模型表單佈局中的方法來顯示某些用戶特定的內容。我試圖在init和onBootstrap中的Module.php中做到這一點,並嘗試聲明一些將在layout.phtml中可用的變量,但是我失敗了並且沒有發現任何有用的東西。在Zendframework中調用模型中的佈局2
你會通常使用視圖助手作爲代理模型這個
在應用程序中創建一個視圖助手,例如,
<?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功能作爲一個工廠來撰寫你的助手,並注入模型的框架內該公司預計
<?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(); ?>