gpt4 book ai didi

php - 如何使用 zend_auth 作为插件

转载 作者:可可西里 更新时间:2023-10-31 23:09:44 26 4
gpt4 key购买 nike

我正在处理我在 Zend Framework 中的第一次用户登录,但我对 Zend_Auth 有点困惑。我阅读的所有关于它的文章都直接在 Controller 中使用它。但对我来说,作为插件工作更有意义大家怎么看?

最佳答案

您可以将它用作插件,唯一的缺点是如果您在 Bootstrap 中初始化插件,那么插件将为每个 Controller 和操作执行,因为它必须在您的 Controller 之前运行。

你可以扩展 Zend_Auth 并添加额外的方法来设置 auth 适配器和管理存储,然后你可以调用 Your_Custom_Auth::getInstance() 来获取 auth 实例,然后你可以在 preDispatcth( ) 需要授权的 Controller 部分。

这样你就可以用更少的代码在多个地方轻松地使用 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
}

希望对您有所帮助。

关于php - 如何使用 zend_auth 作为插件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7459761/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com