views:

230

answers:

2

Hi, iam not sure if iam doing it the right way. My Goal is to display in my Layout an Login or an Navigation at the header section.

My implementation looks like this (without logic):

2 Layout scripts:

  • login.phtml
  • navigation.phtml

An FrontController Plugin:

class Plugin_Header extends Zend_Controller_Plugin_Abstract {

        /**
         * PreDispatch
         *
         * Decides wich kind of navigation is displayed in header section
         * for logged in users the menu, for guests the login box and
         * link to registration form.
         *
         * @return void
         */
        public function preDispatch(Zend_Controller_Request_Abstract $request)
        {
            $layout = Zend_Layout::getMvcInstance();
            $layout->topNavigation = $layout->render('login'); // or navigation 
        } 
}

It works fine, but is this the best way ? ;)

A: 

I use different layouts:

anonymous.phtml
authenticated.phtml

And have this in a front controller plugin's preDispatch() method:

$auth = Zend_Auth::getInstance();
if ($auth->hasIdentity()) {
    $layout = 'authenticated';
} else {
    $layout = 'anonymous';
}


// Bootstrap layouts
Zend_Layout::startMvc(array(
'layoutPath' => APPLICATION_PATH . '/layouts/scripts',
'layout' => $layout
));

Additionally I find it useful also to check for Ajax requests here ($_SERVER['HTTP_X_REQUESTED_WITH'] == 'XMLHttpRequest') , and have a third "ajax" (empty) layout.

Lance Rushing
+1  A: 

I'd suggest putting the functionality in view helper or partial. You bending layout the way it was not supposed to be bend, I guess :)

I would do this:

  • have two partials - navigation & login
  • make a view helper My_View_Helper_RenderHeader() retieving one parameter - boolean $isLoggedIn
  • based on the boolean value render navigation for $isLoggedIn = true and login partial otherwise.
  • you can also add some kind of setup (let's say for different names of partials or a different path) to make this component more reuseable

Other positive thing is that if you implement the "toString" method you can store the boolean inside the helper - setup it for some reason for ex. in index.phtml view and then render it in appropriate place in layout using echo $this->renderHeader(). Awesome, isn't it? If you're not sure, check out the head* (script, link, ...) helpers code.

Tomáš Fejfar
good idea, thanks.
ArneRie
How do you pass the $isLoggedIn to the view helper? Iam now doing it with an plugin at preDispatch ($layout->auth = $auth) ?
ArneRie
$this->renderHeader(Zend_Auth::getInstance()->hasIdentity())
Tomáš Fejfar