我在Module.php的引导程序中创建了一个全局变量
public function setCashServiceToView($event) {
$app = $event->getParam('application');
$cashService = $app->getServiceManager()->get('Calculator/Service/CashServiceInterface');
$viewModel = $event->getViewModel();
$viewModel->setVariables(array(
'cashService' => $cashService,
));
}
public function onBootstrap($e) {
$app = $e->getParam('application');
$app->getEventManager()->attach(\Zend\Mvc\MvcEvent::EVENT_RENDER, array($this, 'setCashServiceToView'), 100);
}
我可以在layout.phtml中使用它作为
$this->cashService;
但是我需要在我的部分导航菜单脚本中使用这个变量,我在layout.phtml中调用它:
echo $this->navigation('navigation')
->menu()->setPartial('partial/menu')
->render();
?>
如何在partial / menu.phtml中使用它?也许有更好的方法,而不是在onBootstrap函数中声明它?
感谢您的回答。我决定制作一个扩展类的\ Zend \ View \ Helper \ Navigation \ Menu来提供cashService的属性。但是我收到一个错误:'Zend \ View \ Helper \ Navigation \ PluginManager :: get无法获取或创建Calculator \ Service \ CashServiceInterface的实例'。 我需要这项服务才能显示导航菜单。看起来很奇怪,但那是真的。我使用从服务中获得的数据在其中显示一些图表。那我为什么会有这个错误呢? 我添加到module.config.php
'navigation_helpers' => array(
'factories' => array(
'mainMenu' => 'Calculator\View\Helper\Factory\MainMenuFactory'
),
MainMenuFactory:
namespace Calculator\View\Helper\Factory;
use Zend\ServiceManager\FactoryInterface;
use Zend\ServiceManager\ServiceLocatorInterface;
use Calculator\View\Helper\Model\MainMenu;
Class MainMenuFactory implements FactoryInterface {
/**
* Create service
*
* @param ServiceLocatorInterface $serviceLocator
* @return mixed
*/
public function createService(ServiceLocatorInterface $serviceLocator) {
return new MainMenu(
$serviceLocator->get('Calculator\Service\CashServiceInterface')
);
}
P.S:CashServiceInterface是CashServiceFactory的别名
答案 0 :(得分:1)
You could remove the event listener and use a custom view helper to access the service in the view.
namespace Calculator\View\Helper;
use Zend\View\Helper\AbstractHelper;
class CashService extends AbstractHelper
{
protected $cashService;
public function __construct(CashServiceInterface $cashService)
{
$this->cashService = $cashService;
}
public function __invoke()
{
return $this->cashService;
}
}
Create a factory.
namespace Calculator\View\Helper;
class CashServiceFactory
{
public function __invoke($viewPluginManager)
{
$serviceManager = $viewPluginManager->getServiceLocator();
$cashService = $serviceManager->get('Calculator\\Service\\CashServiceInterface');
return new CashService($cashService);
}
}
Register the new helper in moudle.config.php
.
'view_helpers' => [
'factories' => [
'CashService' => 'Calculator\View\Helper\CashServiceFactory',
],
],
Then you can use the plugin in all view scripts.
$cashService = $this->cashService();