Zend framework2 ZF2:如何判断用户是否在layout.phtml文件中使用ZfcUser登录

Zend framework2 ZF2:如何判断用户是否在layout.phtml文件中使用ZfcUser登录,zend-framework2,Zend Framework2,我正在使用ZfcUser进行身份验证。当前正在尝试告诉用户是否使用 <? if ($this->zfcUserAuthentication()->hasIdentity()): ?> 我猜我需要向应用程序配置文件添加一些路径?我不知道这是否是“正确”的方法,但您可以将标识添加为布局的ViewModel变量。将以下内容放入模块类中: public function init(Manager $moduleManager) { $events = $module

我正在使用ZfcUser进行身份验证。当前正在尝试告诉用户是否使用

<? if ($this->zfcUserAuthentication()->hasIdentity()): ?>


我猜我需要向应用程序配置文件添加一些路径?

我不知道这是否是“正确”的方法,但您可以将标识添加为布局的ViewModel变量。将以下内容放入模块类中:

public function init(Manager $moduleManager)
{
    $events = $moduleManager->events();
    $sharedEvents = $events->getSharedCollections();
    $sharedEvents->attach('bootstrap', 'bootstrap', array($this, 'initializeView'), 100);
}

public function initializeView($e)
{
    $app = $e->getParam('application');  
    $viewModel = $app->getMvcEvent()->getViewModel();
    $viewModel->myLayoutVariable = 'myLayoutVariable';                
}

您可以使用ZfcUser提供的视图帮助器(即您在问题中引用的视图帮助器,mtbikemike)。通过在模块(module.config.php)的配置中添加以下内容,使用动态注入加载视图帮助器。当然,您可能需要将下面的代码与module.config.php的任何现有内容集成

return array(
    'di' => array(
        'instance' => array(
            'Zend\View\HelperLoader' => array(
                'parameters' => array(
                'map' => array(
                        'zfcUserIdentity' => 'ZfcUser\View\Helper\ZfcUserIdentity',
                        'zfcUserLoginWidget' => 'ZfcUser\View\Helper\ZfcUserLoginWidget',
                    ),
                ),
            ),
        ),
    ),
);

这将加载两个视图帮助程序,因此如果您只需要ZfcuseIdentity帮助程序,那么您可以始终删除对zfcUserLoginWidget的引用。

我是Zend Framework 2(和ZfcUser)的新手,因此我不知道在发布问题时它是如何工作的。现在,它非常简单:

<?php if ( $this->zfcUserIdentity() ) { ?>

它是在ZfcUser的Module.php中的getViewHelperConfig()函数中定义的。如果用户已登录,它将返回ZfcUserDoctrineORM\Entity\user的实例,否则返回false。

一些视图帮助程序示例:



有趣的是,我在发布这篇文章几小时后遇到了相同的代码。这似乎不是一个优雅的解决方案。我想一定有办法使用插件或服务…如果你愿意,你可以写一个视图助手。但是,您仍然必须将标识注入视图帮助器。$this->zfcUserAuthentication()是对ActionController中插件的调用。您需要将其传递给viewScript,或者只使用viewHelper,正如@Mark T在其回答中所写的那样。我将其放到了我的layout.phtml中,效果非常好:
<!-- Test if the User is connected -->
<?php IF(!$this->zfcUserIdentity()): ?>
    <!-- display the login form -->
    <?php echo $this->zfcUserLoginWidget(array('redirect'=>'application')); ?>
<?php ELSE: ?>
    <!-- display the 'display name' of the user -->
    <?php echo $this->zfcUserIdentity()->getDisplayname(); ?>
<?php ENDIF ?>