搞了一段時間ZF,發現中文的資料很少,相對來說就是那個ZF中文手機較為全面一些,但還是有些關鍵的東西沒有提高。今天琢磨了一天,終於把這個理論實踐了一下,發現ZF比想象中的複雜,當然也強大的多。
這裡就討論一下,資料庫認證及身份持久,手冊中把持久的過程寫的相對較細,可對持久後身份的擷取只是提了一下,也怪自己不細心,沒太注意看。於是寫出來,希望對其他人能有所協助。晚上的時候把這個認證與持久寫了一個Class,如下:
class Active_Auth
{
public static $name = 'adminlogin';
public static function login($username, $password)
{
$auth = Zend_Auth::getInstance ();
$auth->setStorage ( new Zend_Auth_Storage_Session ( Active_Auth::$name ) );
$db = Zend_Registry::get ( 'db' );
$authAdapter = new Zend_Auth_Adapter_DbTable ( $db, 'zf_admin', 'ausername', 'apassword', 'md5(?)' );
$authAdapter->setIdentity ( $username );
$authAdapter->setCredential ( $password );
$result = $auth->authenticate ( $authAdapter );
if ($result->isValid ()) {
$storage = $auth->getStorage ();
$storage->write ( $authAdapter->getResultRowObject () );
return true;
} else {
return false;
}
}
public static function isValid()
{
$auth = Zend_Auth::getInstance();
$auth->setStorage(new Zend_Auth_Storage_Session(Active_Auth::$name));
return $auth->hasIdentity();
}
public static function getIdentity()
{
$auth = Zend_Auth::getInstance();
$auth->setStorage(new Zend_Auth_Storage_Session(Active_Auth::$name));
return $auth->getIdentity();
}
public static function logout()
{
$auth = Zend_Auth::getInstance();
$auth->setStorage(new Zend_Auth_Storage_Session(Active_Auth::$name));
$auth->clearIdentity();
}
}
引入這個類後,可以通過訪問靜態方法實現登陸、擷取身份、退出登陸等。