php - Zend Framework 2 设置全局模块变量

标签 php view zend-framework2 global-variables

我想让变量“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) 它将输出预期的结果,尽管在 View 中执行相同的结果

注意: undefined variable :用户在 C:\webserver\apache\htdocs...

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

最佳答案

使用 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'];

希望它足够清楚。

关于php - Zend Framework 2 设置全局模块变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18495870/

相关文章:

php - 什么?解析错误: syntax error, unexpected T_STRING in/file/path

php - 未定义索引 php if ($_SERVER ['REQUEST_METHOD' ] == 'POST' ){ 找不到答案?

php - 将信息模式列注释返回到 php 数组中

php - 提交表单时Symfony 2表单错误 "This form should not contain extra fields."

mysql - 消除 MySQL View 中的重复问题

php - ZF2 如何在 View 中使用全局变量

c# - 如何在 PropertyGrid 中查看对象属性?

MySQL Workbench 6.2 在创建 View 后删除了我的所有评论

php - Zend Framework 2 + Doctrine 2 框架应用程序

php - Zend框架2 : Debugging Plugin