我打算在未來的項目中使用ZF2,所以我現在嘗試使用Zend Framework 2 RC1。我開始使用身份驗證步驟,並注意到當我爲會話存儲名稱空間選擇了不同於'Zend_Auth'的名稱時,我無法訪問存儲在會話中的對象(AuthenticationService類'hasIdentity方法返回false,儘管會話中的數據集設置了會話)。使用不同的會話命名空間和Zend Framework 2身份驗證組件
<?php
namespace Application\Controller;
use Zend\Authentication\Adapter\DbTable as AuthAdapter;
use Zend\Authentication\AuthenticationService;
use Zend\Authentication\Storage\Session as SessionStorage;
use Zend\Mvc\Controller\AbstractActionController;
use Zend\View\Model\ViewModel;
use Application\Model\User;
use Application\Form\LoginForm;
class LoginController extends AbstractActionController
{
public function indexAction()
{
$auth = new AuthenticationService();
if ($auth->hasIdentity()) {
return $this->redirect()->toRoute('application');
}
$form = new LoginForm();
return array('form' => $form);
}
public function loginAction()
{
$auth = new AuthenticationService();
$form = new LoginForm();
$form->get('submit')->setAttribute('value', 'Add');
$request = $this->getRequest();
if ($request->isPost()) {
$user = new User();
$form->setInputFilter($user->getInputFilter('login'));
$form->setData($request->getPost());
if ($form->isValid()) {
$data = $form->getData();
// Configure the instance with constructor parameters...
$sm = $this->getServiceLocator();
$dbAdapter = $sm->get('db-adapter');
$authAdapter = new AuthAdapter($dbAdapter, 'users', 'username', 'password');
$authAdapter
->setIdentity($data['username'])
->setCredential(sha1($data['password']));
// Use 'users' instead of 'Zend_Auth'
$auth->setStorage(new SessionStorage('users'));
$result = $auth->authenticate($authAdapter);
if ($result->isValid()) {
// store the identity as an object where only the username and
// real_name have been returned
$storage = $auth->getStorage();
// store the identity as an object where the password column has
// been omitted
$storage->write($authAdapter->getResultRowObject(
null,
'password'
));
// Redirect to list of application
return $this->redirect()->toRoute('application');
}
}
}
// processed if form is not valid
return array('form' => $form);
}
}
在該代碼中,當我改變了下面線,
$auth->setStorage(new SessionStorage('users'));
這樣的:
$auth->setStorage(new SessionStorage());
hasIdentity方法返回真。
我檢查了兩個類Zend \ Authentication \ AuthenticationService和Zend \ Authentication \ Storage \ Session,但沒有看到訪問具有不同於默認會話名稱空間的會話數據的方法。
我需要了解的是如何訪問具有不同命名空間的會話數據,並且如果現在沒有辦法執行此操作,應該將其定義爲一個錯誤嗎?
我可以更新問題是否需要其他信息。
安託萬hedgecock,對不起,我遲到的答覆。我嘗試和接收用戶身份的代碼是indexAction代碼。是的,當我嘗試使用不同的名稱空間時,我沒有傳遞SessionStorage對象。現在我想我們必須傳遞SessionStorage對象才能使用與默認_Zend_Auth_命名空間不同的名稱空間(正如您在答案中所述),這是真的嗎?有沒有其他簡單的方法來做到這一點,也許將名字空間字符串傳遞給AuthenticationService類? – azer 2012-08-07 07:35:48