Useful tricks for zend framework



I am listing some useful tricks for zend framework here that can be used generally.

If you want to change the layout for the particular controller views you should use below code of snippet. You can use it in init() function of controller.

public function init(){
     $this->_helper->layout()->setLayout('user');
}

To check user authentication you should use it in preDispatch() function of controller, if not logged-in then redirect to login page. It will work for all actions of your controller.

function preDispatch()
{
	$auth = Zend_Auth::getInstance();
	if (!$auth->hasIdentity()) {
		$this->_redirect('index/login');
	}
}

You can assign some important variables to your view that may help you for some conditional views. Following are usually used snippet of code in preDispatch() function of controller.

$this->view->assign('auth',$auth->getStorage()->read());
$this->view->assign('controller',$this->getRequest()->getControllerName());
$this->view->assign('action',$this->getRequest()->getActionName());
$this->view->assign('params',$this->getRequest()->getParams());

To redirect to another controller or action following line can be used

$this->_redirect('index/login'); //pass url in string format 
$this->_helper->redirector('action','controller','module', array($params)); 
//well structured format you can pass parameters as an array 

Hope this will help you!