コントローラーからカスタム ビュー ヘルパーにデータを渡す必要があります。2つの方法でやろうとしましたが、残念ながらうまくいきません。
module.config.php にヘルパーを登録しました
コントローラーからヘルパーに変数を渡そうとした最初の方法
:
私のコントローラーでは:
public function indexAction()
{
$this->data = $this->getApplicationTable()->getTypes();
$helper = new TestHelper();
$helper->setVariables($this->data);
}
これが私のヘルパーです:
class TestHelper extends AbstractHelper {
public $data;
public function __invoke()
{
var_dump($this->data); // output null
return $this->getView()->render('helper-view.phtml', $this->data);
}
public function setVariables($var)
{
if($var){
$this->data = $var;
var_dump($this->data) // output array with correct data
}
}
}
レイアウトでは、次のように表示します。
<?php echo $this->testHelper(); ?>
そして、変数が空であるという helper-view.phtml からエラーが発生しました。
私が試した2番目の方法は、依存性注入に基づいています
私のmodule.php:
public function getServiceConfig()
{
return array(
'factories' => array(
'Application\Model\ApplicationTable' => function($sm) {
$tableGateway = $sm->get('ApplicationTableGateway');
$table = new ApplicationTable($tableGateway);
return $table;
},
'ApplicationTableGateway' => function ($sm) {
$dbAdapter = $sm->get('Zend\Db\Adapter\Adapter');
return new TableGateway('tableName', $dbAdapter);
},
),
);
}
public function getViewHelperConfig()
{
return array(
'factories' => array(
'TestHelper' => function ($helperPluginManager) {
$sm = $helperPluginManager->getServiceLocator();
$tableGateway = $sm->get('Application\Model\ApplicationTable');
$viewHelper = new TestHelper();
$viewHelper->setTableGateway($tableGateway);
return $viewHelper;
}
),
);
}
私のヘルパー:
class TestHelper extends AbstractHelper {
public $tableGateway;
public function __invoke()
{
$data = $this->tableGateway->getTypes();
return $this->getView()->render('helper-view.phtml', $data);
}
public function setTableGateway($tableGateway)
{
$this->tableGateway = $tableGateway;
}
}
最初の方法と同じエラーが発生しました。
どんな助けにも感謝します。