Search code examples
zend-frameworkzend-layout

Best way to show user info in zend layout


I'm trying to show information about user in my Zend Framework application. I'm using one layout script for all controllers (except login controller). And now I want to show information about logged in user (this layout is used only on controllers with logged in users).

I want to separate logic of retrieving user information into some object and view script that will render information. So that in future I could change one of these parts independently.

So the question is what is the best way to achieve this?


Solution

  • I'm using an action helper for this purpose. You can retrieve the user information and add it to the view. Something like that:

    class My_LayoutHelper extends Zend_Controller_Action_Helper_Abstract {
        /**
         * Predispatch hook.
         */
        public function preDispatch()
        {
            $view = $this->getActionController()->view;
    
            // Get the user data from wherever you have them
            $userInfo = getUserInfo();
    
            // Inject it into the view
            $view->username = $userInfo->name;
        }
    }
    

    And in the layout script, you can write

    <?php echo $this->username; ?>
    

    wherever you need to.

    More information on action helpers here: http://devzone.zend.com/article/3350

    Hope that helps...