如何在zend框架中使用PHP会话变量
发布时间:2020-12-13 16:00:48 所属栏目:PHP教程 来源:网络整理
导读:我想知道如何在zend框架中使用 PHP会话变量 这是我到目前为止的代码: – public function loginAction() { $this-view-title = 'Login'; if(Zend_Auth::getInstance()-hasIdentity()){ $this-_redirect('index/index'); } $request = $this-getRequest(); $
我想知道如何在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() . "nn"; // $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. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |