The Solution:
class AuthenticationController extends Zend_Controller_Action
{
public function init()
{
/* Initialize action controller here */
}
public function indexAction()
{
// action body
}
public function loginAction()
{
$this->view->title='Login';
if(Zend_Auth::getInstance()->hasIdentity())
{$this->_redirect();}
$request=$this->getRequest();
$form=new Form_LoginForm();
if($request->isPost())
{if($form->isValid($this->_request->getPost())){
$authAdapter =$this->getAuthAdapter();
$username=$form->getValue('username');
$password=$form->getValue('password');
$authAdapter->setIdentity($username)
->setCredential(md5($password));
$auth=Zend_Auth::getInstance();
$result=$auth->authenticate($authAdapter);
if($result->isValid())
{ $doctrine = $this->getDoctrineContainer();
$em = $doctrine->getEntityManager();
$identity = $em->getRepository('\ZC\Entity\Users')
->find($authAdapter->getIdentity());
$authStorage=$auth->getStorage();
$authStorage->write($identity);
$this->redirect($_SERVER['HTTP_REFERER']);
}else{
$this->view->errorMessage='Username or password is wrong';
}
}
}
$this->view->form=$form;
}
public function logoutAction()
{
Zend_auth::getInstance()->clearIdentity();
$this->_redirect();
}
public function getDoctrineContainer()
{
return $this->getInvokeArg('bootstrap')->getResource('doctrine');
}
private function getAuthAdapter() {
$doctrine = $this->getDoctrineContainer();
$em = $doctrine->getEntityManager();
$authAdapter = new Doctrine\Auth\doctrine2($em);
$authAdapter->getIdentity();
$authAdapter->setEntityClassName('ZC\Entity\users')
->setIdentityField('username')
->setCredentialField('password');
return $authAdapter;
}
}