2

我想让它使变量“user”对所有模块都是全局的,所以我添加了这段代码

public function onBootstrap(MvcEvent $e)
{
    $eventManager        = $e->getApplication()->getEventManager();

    $e->getViewModel()->setVariable('user',$e->getApplication()->getServiceManager()->get('auth_service')->getIdentity());
}

它适用于布局文件,这意味着如果我在 layout.phtml 中执行 var_dump($user) 它将输出预期的结果,尽管在视图中执行相同的结果

注意:未定义变量:C:\webserver\apache\htdocs 中的用户...

关于为什么会发生这种情况的任何帮助?难道我做错了什么?

4

3 回答 3

10

使用Config-Variables使应用程序范围内的东西可用。

// module.config.php
return array(
    'someVariable' => 'someValue',
    // all the other stuff
);

您所要做的就是访问配置。当然,访问权限会根据您尝试访问它的位置而有所不同,但最终它是这样完成的:

// Example for being inside any of your Controllers
$servoceLocator = $this->getServiceLocator();
$config         = $serviceLocator->get('config');
$myValue        = $config['someVariable'];

希望它足够清楚。

于 2013-08-28T20:28:51.443 回答
0

您是否尝试过 $this->user ,我认为这应该可行。

于 2014-01-29T16:46:33.250 回答
0

在 Zend Framework 2 中有一个内置的视图助手,称为“Identity”,它在所有视图中都可用。它要求您在 config.module.php 中注册服务管理器,如下所示:

'service_manager' => array(
    ...
    'invokables' => array(
        ...
        'Zend\Authentication\AuthenticationService' => 'Zend\Authentication\AuthenticationService',
    ),
)

然后在视图中,您可以像这样访问您注册的“用户”:

<?php echo $this->identity()?>

这将返回您的用户。这是zend文档的链接

于 2015-07-22T14:13:55.680 回答