Search code examples
zend-frameworkzend-navigation

How to swap Login for Logout after a user logs in using Zend_Navigation?


I'm using an XML config file to populate my navigation using Zend_Navigation.

I have Login and Logout in the navigation, but obviously I should only display the 1 action that makes sense.

I believe I can do something like $navigation->removePage() but... How do I get the $navigation variable in a Controller after it was previously created in Bootstrap.php?


Solution

  • The easiest way is to create ACL with apropriate privilages for logged and not logged users, then in config file:

    resources.navigation.pages.login.resource = "user"
    resources.navigation.pages.login.privilege = "login"
    

    (this is the ini format for simplicity, you may do this in XML as well)

    Privilages will limit displaying login/logout links for specified group.

    However… This is good for static navigation labels. I'd like to have login link named: Login, and logout named: Logout (+ username), so the user sees his identity all the time.

    In this case I'd create a front controller plugin which retrieves actual navigation container, finds login page container and replaces label and route (or URI or module,controller and action if you are using MVC page containers).

    Updated:

    Try something like this:

    if (Zend_Auth::getInstance()->hasIdentity()) {
        Zend_Registry::set('role',
        Zend_Auth::getInstance()->getStorage()->read()->role);
    } else {
        Zend_Registry::set('role', 'guest');
    }
    
    $this->_acl = new My_Model::Acl;
    $this->_auth = Zend_Auth::getInstance();
    
    $front = Zend_Controller_Front::getInstance();
    $front->registerPlugin(new Plugin_AccessCheck($this->_acl));
    
    $view->navigation()->setAcl($this->_acl)->setRole(Zend_Registry:get('role'));