Webdesign aus Witten » LONG RUN INTERNATIONAL LTD.

28. August 2009

Zend Framework: (2) Switch Layouts by Auth status

Filed under: Two fisted Competition — Stefan Klose @ 20:33

In my second post on Zend Framework, i will discuss a quick (but not anyway dirty) way to switch the layout provided by Zend_Layout depending on the auth status provided by Zend_Auth. This is a very short, but quite useful tip:

We start with the Bootstrap.php file. Any protected function in this file named “_initMyName()” will be automatically called in the same order as placed in the bootstrap. We will use this advantage to provide the right layout before we go in any controller. Just add a new function:

protected function _initAuthState()
{

}

Let’s say we have an layout for all the users logged out (e.g. without a navigation bar and any personal / user-related data) and one for all users logged in (adapted to the fact that user-related data will be displayed). So if we implement Zend_Auth for login in one of our controllers and use it, we can differentiate between an user not logged in and one logged in. This is available via the Zend_Auth->hasIdentity()-method. To call that one, we first have to get an instance of Zend_Auth via Zend_Auth::getInstance().

Zend Framework uses the Singleton Design Pattern for Zend_Auth (and more libraries). Therefore we won’t (and can’t) initiate a new object of Zend_Auth, but will have to get an instance of it.

Zend_Auth::getInstance()->hasIdentity()

This function returns a Boolean whether a visitor is logged in or not. So if we create an if-statement on that, we just need to switch the layout based on the result of the statement. To switch the layout, we have to get the layout resource via $this->getResource(‘layout’).

$layout = $this->getResource(‘layout’)

The layout resource supports a function named setLayout(). It takes the name of the layout php file (without ending .phtml) and searches for it in the layoutPath. This layoutPath has been set in the application.ini-file:

resources.layout.layoutPath         = APPLICATION_PATH “/layouts”

So we create our layouts, e.g. “layout_external.phtml” and “layout_internal.phtml”, in the folder /application/layouts/. This contains our individual content. Don’t forget that each one has to have $this->layout()->content in it to display any content from the controllers.

Last step:

if (Zend_Auth::getInstance()->hasIdentity()):
// Logged in.
$layout->setLayout(‘layout_internal’);
else:
// Not Logged in.
$layout->setLayout(‘layout_external’);
endif;

That’s it. Placed in the _initAuthState() function, the bootstrap will automatically choose the right layout for your needs based on the user auth state.

Keine Kommentare »

Noch keine Kommentare

RSS Feed für Kommentare zu diesem Artikel. TrackBack URL

Hinterlasse einen Kommentar

Powered by WordPress