我想知道如何在zend框架中使用
PHP会话变量
这是我到目前为止的代码: –
public function loginAction() { $this->view->title = 'Login'; if(Zend_Auth::getInstance()->hasIdentity()){ $this->_redirect('index/index'); } $request = $this->getRequest(); $form = new Default_Form_LoginForm(); if($request->isPost()){ if($form->isValid($this->_request->getPost())){ $authAdapter = $this->getAuthAdapter(); $username = $form->getValue('username'); $password = $form->getValue('password'); $authAdapter->setIdentity($username) ->setCredential($password); $auth = Zend_Auth::getInstance(); $result = $auth->authenticate($authAdapter); if($result->isValid()){ $identity = $authAdapter->getResultRowObject(); print_r($authAdapter->getResultRowObject()); $authStorage = $auth->getStorage(); $authStorage->write($identity); echo $authAdapter->getIdentity() . "\n\n"; // $this->_redirect('index/index'); } else { $this->view->errorMessage = "User name or password is wrong."; } } } $this->view->form = $form; }
echo“welcome,”.$this-> username;我可以做什么 ?
您可以存储自定义对象或模型,而不是将$identity写入$authStorage.
这是一个例子:
<?PHP class Application_Model_UserSession implements Zend_Acl_Role_Interface { public $userId; public $username; /** @var array */ protected $_data; public function __construct($userId,$username) { $this->userId = $userId; $this->username = $username; } public function __set($name,$value) { $this->_data[$name] = $value; } public function __get($name) { if (array_key_exists($name,$this->_data)) { return $this->_data[$name]; } else { return null; } } public function updateStorage() { $auth = Zend_Auth::getInstance(); $auth->getStorage()->write($this); } public function getRoleId() { // TODO: implement $role = 'guest'; return $role; } public function __isset($name) { return isset($this->_data[$name]); } public function __unset($name) { unset($this->_data[$name]); } }
现在在您的登录控制器中,您可以:
if($result->isValid()){ $identity = new Application_Model_UserSession(0,$username); // 0 for userid // You can also store other data in the session,e.g.: $identity->account = new Account_Model($authAdapter->getResultRowObject()); $identity->updateStorage(); // update Zend_Auth identity with the UserSession object
通常,我有一个帐户对象,我也存储在UserSession对象中,并通过公共属性轻松访问用户名和userId.
现在您可以随时获取对象:
$identity = Zend_Auth::getInstance()->getIdentity(); // Application_Model_UserSession
只是不要忘记确保它是Application_Model_UserSession.