zf2如何使用AuthenticationService获取用户详细信息

时间:2014-07-10 12:40:11

标签: php zend-framework2


我创建了一个模块来验证用户身份。现在,登录后我转到索引操作,系统告诉我验证工作正常。但我想要的是从Users表中打印更多用户详细信息。当我尝试:

print_r($this->getServiceLocator()->get('AuthService')->getAdapter()->getResultRowObject());

我没有结果。我究竟做错了什么? 谢谢你的帮助。

在我的 module.php 中,我有以下代码(摘录):

public function getServiceConfig()
{
    return array(
        'abstract_factories' => array(),
        'aliases' => array(),
        'factories' => array(

            // Some more code here but removed for simplicity
            // Autentication
            'AuthService' => function ($sm) {
                $adapter = $sm->get('master_db');
                $dbAuthAdapter = new DbAuthAdapter ( $adapter, 'Users', 'email', 'password' );

                $auth = new AuthenticationService();
                $auth->setAdapter ( $dbAuthAdapter );

                return $auth;
            },
            // Some more code here but removed for simplicity

}

在我的 IndexController.php 中,我有以下内容(片段):

public function indexAction()
{

    if(!$this->getServiceLocator()->get('AuthService')->hasIdentity()){      
        return $this->redirect()->toUrl('login');
    }
    echo "hello, it works!";         
    exit;

}

public function loginAction(){
    $form = $this->getServiceLocator()->get('LoginForm');
    $viewModel = new ViewModel(array('form' =>
    $form));

        return $viewModel;
}

public function processAction(){

    // Lots of code here
    if($bcrypt->verify($loginData['password'], $userData->password))
    {

        $this->getAuthService()
            ->getAdapter()
            ->setIdentity($loginData['email'])
            ->setCredential($userData->password);
            $result = $this->getAuthService()->authenticate();  
    }

    // Lots of code here where I check if $result->isValid and route to the
    // correct action

}

public function getAuthService() {
        if(!isset($this->authservice)) {

            $this->authservice = $this->getServiceLocator()->get('AuthService');
        }

        return $this->authservice;
}

1 个答案:

答案 0 :(得分:3)

您可以简单地将用户详细信息存储在身份验证标识中(@see http://framework.zend.com/manual/2.1/en/modules/zend.authentication.intro.html),而不是引用身份验证结果对象(仅在身份验证请求中存在)。

对于您的情况,您还可以在验证存储中验证身份验证结果后立即存储用户特定的详细信息:

if ($result->isValid()) { //authentication success $resultRow = $this->authService->getAdapter()->getResultRowObject(); $this->authService->getStorage()->write(array( 'id' => $resultRow->id, 'user_agent' => $request->getServer('HTTP_USER_AGENT')) ); }

(此信息来自此身份验证教程http://samsonasik.wordpress.com/2013/05/29/zend-framework-2-working-with-authenticationservice-and-db-session-save-handler/