2011-12-02 58 views
0

我试图通过阅读一本书来了解zend框架。到目前为止,其中的所有代码都能正常工作,但现在我无法验证用户身份。本书建议通过行动助手和学说2的实体经理来做到这一点。Doctrine 2实体管理器对象上的非对象错误

这里是我使用这个

我的身份验证助手类的代码...

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;     
    } 
    } 
} 

实体库函数...

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();  

}

在页面视图中,我使用以下代码来检查用户是否已登录:

<?php 
if($this->user){ 
    ?>Welcome back, <a href="/user/"><?php echo $this->user->fname; ?></a> &bull; <a href="/user/logout/">Logout</a><?php 
} ?> 

if条件在我登录时通过,但不会打印用户的名称。

这里的错误消息,我得到它:

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 

谁能帮助我解决这个问题?

回答

1

我认为问题的一部分是在这里:

if (isset($identity)) {  
    $user = $em->getRepository('Entities\User')->findOneByEmail($identity); 
    Zend_Layout::getMvcInstance()->getView()->user = $user;     
} 

它看起来像findOneByEmail预计该电子邮件地址作为参数,但整个标识对象被传递。

这可能会导致return $query->getResult();返回null或false,因此$view->user不是一个对象并且没有属性fname。

我认为在findOneByEmail中,您需要执行类似于$user = $em->getRepository('Entities\User')->findOneByEmail($identity->email);的地方,其中$identity->email是包含电子邮件地址的属性。

+0

我仔细检查过。 $ identity是一个字符串,只是电子邮件地址。 – liz

+0

好的,在这种情况下,对函数的返回值尝试'var_export'以确保'$ query-> getResult();'返回正确的数据。 – drew010

+0

从helper:array(0 => Entities \ User :: __ set_state(array('id'=> 1,'fname'=>'Liz','lname'=> NULL'email')的$ user的var_export =>'[email protected]','password'=> NULL,'phone'=> NULL,'active'=> NULL,'role'=> NULL,'created'=> NULL,'updated'=> NULL,'inactive'=> NULL,)),) – liz

相关问题