I’m trying to learn the zend framework by reading through a book. So far all the code in it has worked, but now I’m having trouble authenticating users. The book suggests doing this through an action helper and doctrine 2’s entity managers.
here’s the code i’m using for this
my authenticate helper class…
public function init()
{
// Initialize the errors array
Zend_Layout::getMvcInstance()->getView()->errors = array();
$auth = Zend_Auth::getInstance();
$em = $this->getActionController()->getInvokeArg('bootstrap')->getResource('entityManager');
if ($auth->hasIdentity()) {
$identity = $auth->getIdentity();
if (isset($identity)) {
$user = $em->getRepository('Entities\User')->findOneByEmail($identity);
Zend_Layout::getMvcInstance()->getView()->user = $user;
}
}
}
the entity repository function…
public function findOneByEmail($email)
{
$rsm = new ResultSetMapping;
$rsm->addEntityResult('Entities\User', 'a');
$rsm->addFieldResult('a', 'id', 'id');
$rsm->addFieldResult('a', 'email', 'email');
$rsm->addFieldResult('a', 'fname', 'fname');
$query = $this->_em->createNativeQuery(
'SELECT a.id, a.fname, a.email FROM users a
WHERE a.email = :email',
$rsm
);
$query->setParameter('email', $email);
return $query->getResult();
}
On the page view, i’m using the following code to check that the user is logged in:
<?php
if($this->user){
?>Welcome back, <a href="/user/"><?php echo $this->user->fname; ?></a> • <a href="/user/logout/">Logout</a><?php
} ?>
the if condition passes when i’m logged in, but it won’t print the user’s name.
here’s the error message I get on it:
Notice: Trying to get property of non-object in C:\Program Files (x86)\Zend\Apache2\htdocs\dev.test.com\application\views\scripts\user\index.phtml on line 3
Can anyone help me fix this?
I think part of the problem is here:
It looks like findOneByEmail expects the email address as the parameter but the whole identity object is being passed.
That probably causes
return $query->getResult();to return null or false so$view->useris not an object and has no property fname.I think in findOneByEmail you need to do something like
$user = $em->getRepository('Entities\User')->findOneByEmail($identity->email);where$identity->emailis the property that contains the email address.