搞了一段时间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();
}
}
引入这个类后,可以通过访问静态方法实现登陆、获取身份、退出登陆等。