php – 如何使用zend_auth作为插件
发布时间:2020-12-13 17:08:53 所属栏目:PHP教程 来源:网络整理
导读:我正在研究我在Zend Framework中的第一个用户登录,但我对Zend_Auth有点困惑.我读到的所有文章都直接在控制器中使用它.但对我来说,作为一个插件工作更有意义 你们有什么感想? 解决方法 您可以将它用作插件,唯一的缺点是如果您在引导程序中初始化插件,那么将
我正在研究我在Zend Framework中的第一个用户登录,但我对Zend_Auth有点困惑.我读到的所有文章都直接在控制器中使用它.但对我来说,作为一个插件工作更有意义
你们有什么感想? 解决方法
您可以将它用作插件,唯一的缺点是如果您在引导程序中初始化插件,那么将为每个控制器和操作执行插件,因为它必须在您的控制器之前运行.
您可以扩展Zend_Auth并添加额外的方法来设置auth适配器并管理存储,然后您可以调用Your_Custom_Auth :: getInstance()来获取auth实例,然后您可以在preDispatcth()部分中检查auth.您需要身份验证的控制器. 这样,您可以使用更少的代码轻松地在多个位置使用zend_auth <?php class My_User_Authenticator extends Zend_Auth { protected function __construct() {} protected function __clone() {} public static function getInstance() { if (null === self::$_instance) { self::$_instance = new self(); } return self::$_instance; } // example using zend_db_adapter_dbtable and mysql public static function getAdapter($username,$password) { $db = Zend_Controller_Front::getInstance() ->getParam('bootstrap') ->getResource('db'); $authAdapter = new Zend_Auth_Adapter_DbTable($db,'accounts','username','password'); $authAdapter->setIdentity($username) ->setCredential($password) ->setCredentialTreatment( 'SHA1(?)' ); return $authAdapter; } public static function updateStorage($storageObject) { self::$_instance->getStorage()->write($storageObject); } } // in your controllers that should be fully protected,or specific actions // you could put this in your controller's preDispatch() method if (My_User_Authenticator::getInstance()->hasIdentity() == false) { // forward to login action } // to log someone in $auth = My_User_Authenticator::getInstance(); $result = $auth->authenticate( My_User_Authenticator::getAdapter( $form->getValue('username'),$form->getValue('password')) ); if ($result->isValid()) { $storage = new My_Session_Object(); $storage->username = $form->getValue('username'); // this object should hold the info about the logged in user,e.g. account details My_User_Authenticator::getInstance()->updateStorage($storage); // session now has identity of $storage // forward to page } else { // invalid user or pass } 希望有所帮助. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |