变量无法访问ZF2外部?

时间:2013-12-28 09:26:39

标签: php zend-framework2 bootstrapping

我的Bootstrap功能是这样的:

public function onBootstrap(MvcEvent $e)
    {
        $event = $e->getApplication()->getEventManager();
        $event->getSharedManager()
          ->attach('Zend\Mvc\Controller\AbstractActionController',
                    'dispatch',
                array($this, 'settingUpControllerVariables'), 100
        );
    }

    public function settingUpControllerVariables(MvcEvent $e)
    {
        $controller = $e->getTarget();

        //check if logged in, setting up the userid variable of controllers
        if ($e->getApplication()->getServiceManager()
                            ->get('AuthService')
                            ->hasIdentity()) {
            $users = $e->getApplication()->getServiceManager()
                            ->get('SanAuth\Model\AuthStorage')->read();

            $controller->userid = $users['id'];
            $e->getViewModel()->setVariable('user_data', $controller->userid);
        }
    }

我想检查用户是否登录,因此我在引导操作中检查它并在用户登录时分配其值。此功能与分配变量工作正常有关但当我想在布局中访问此变量的值时页面,但所有时间都返回未定义的变量。为什么?

1 个答案:

答案 0 :(得分:0)

我认为变量的设置必须在渲染事件之后发生,因为视图模型出现在该事件之后。但我可能错了。

而不是

$e->getViewModel()->setVariable('user_data', $controller->userid);

试试这个:

$eventManager = $e->getApplication()->getEventManager();
$eventManager->attach('render', function($e) use ($controller){
    $e->getViewModel()->setVariable('user_data', $controller->userid);
}

Source