![](/img/trans.png)
[英]How can I use Zend\Di in Zend\ServiceManager in ZF2?
[英]How to use Zend\Session in zf2?
有人試過zf2嗎? 我無法理解在zf2中使用會話的新機制。 如何在新的zend框架中編寫和讀取會話?
我也在互聯網上找不到任何例子。
zf2會話使用的一些示例:
會話創建:
use Zend\Session\Container;
$session = new Container('base');
檢查會話中是否存在密鑰:
$session->offsetExists('email')
通過密鑰從會話中獲取價值:
$email = $session->offsetGet('email');
在會話中設置值:
$session->offsetSet('email', $email);
在會話中取消設置值:
$session->offsetUnset('email');
其他簡單的會話方式是:
$session = new Container('foo');
//這些都是相同目的的同等手段
$session['bar'] = 'foobar';
$session->bar = 'foobar';
$session->offsetSet('bar', 'foobar');
肯定是的,你應該使用Zend \\ Session \\ Container
Array的 Container擴展並使用ARRAY_AS_PROPS
標志進行實例化,這意味着您可以輕松地遍歷屬性並讀取/寫入它們,例如
use Zend\Session\Container as SessionContainer;
$this->session = new SessionContainer('post_supply');
$this->session->ex = true;
var_dump($this->session->ex);
第一個參數是session namespace,第二個是Manager 。 Manager
是Storage
和SaveHandler
的外觀,它配置了ConfigInterface
,以便將會話數據保存在DB或Memcache服務器中。
我目前正在使用zf2。 我找到了Sessions的用法:
Zend\\Authentication\\Storage\\Session.php
也許你可以在那里找到答案。
如果您嘗試在登錄操作中使用會話,則可以使用:“ Zend\\Authentication\\AuthenticationService
”。 它還驗證用戶和存儲會話。
getStorage()->write($contents)
將存儲會話。
這里是一個簡短的例子。 我已經實現了關於維護用戶成功認證的會話。
<?php
$registry = Zend_Registry::getInstance();
$DB = $registry['DB'];
$authAdapter = new Zend_Auth_Adapter_DbTable($DB);
$authAdapter->setTableName('user');
$authAdapter->setIdentityColumn("user_name");
$authAdapter->setCredentialColumn("user_password");
//get values
$username = $request->getParam('username');
$password = $request->getParam('password');
//set values
$authAdapter->setIdentity($username);
$authAdapter->setCredential($password);
$auth = Zend_Auth::getInstance();
//to store in session
$auth->setStorage(new Zend_Auth_Storage_Session('front'));
$authResult = $auth->authenticate($authAdapter);
if ($authResult->isValid()) {
$authAdap = $authAdapter->getResultRowObject(null, "Password");
$auth->getStorage()->write($authAdap);
$this->_redirect('/login/controlpannel');
} else {
$this->_redirect('/login/login');
}
?>
獲取值或檢查存儲在與用戶相關的會話中的數據
<?php
$auth = Zend_Auth::getInstance();
$auth->setStorage(new Zend_Auth_Storage_Session('front'));
if($auth->hasIdentity()){
$data = $auth->getStorage()->read();
print_r($data);
}else{
$this->_redirect('/login/login');
}
?>
希望這可以幫助某人
use Zend\Session\Container;
public function createAction(){
$session = new Container('name');
$session->offsetSet('session_variable', $value);
}
//the above codes are used for create session.
public function take_valuesAction(){
$session = new Container('name');
echo $value = $session->offsetGet('session_variable');
}
//the above codes are used for take values from session.
public function destroyAction(){
$session = new Container('name');
$session->getManager()->destroy();
}
//the above codes are used for destroy the session.
要開始會話,您需要使用
zend\session\container
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.