我计划在未来的项目中使用 ZF2,所以我现在正在尝试 Zend Framework 2 RC1。我从身份验证步骤开始,并注意到当我为会话存储命名空间选择与“Zend_Auth”不同的名称时,我无法访问存储在会话中的对象(AuthenticationService 类的 hasIdentity 方法返回 false,尽管会话中设置了用户对象数据)。
<?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 方法返回 true。
我检查了 Zend\Authentication\AuthenticationService 和 Zend\Authentication\Storage\Session 两个类,并没有看到访问会话数据的方法,这些会话数据具有不同于默认的会话命名空间。
我需要了解的是如何访问具有不同名称空间的会话数据,如果目前没有办法,我们应该将其定义为错误吗?
如果需要任何其他信息,我可以更新问题。