我正在开发一个Web应用程序,要求用户在看到或执行任何操作之前登录。如果没有登录,则无法访问此应用程序的任何部分。(当然,登录控制器除外)
目前我正在使用会话来处理身份验证,我已在init()函数中的每个控制器中放置代码以检查其会话是否有效。
这是一个临时的解决方法,但它是多余的,效率低下。
我希望我的init()函数类似于以下内容,但我不确定如何实现它:
public function init()
{
// If user not logged in redirect to login controller
$myLibrary = Zend_Library_MyLibrary();
$myLibrary->CheckAuth();
}
所以我的问题实际上有两个部分:
感谢。
答案 0 :(得分:3)
http://zendframework.com/manual/en/zend.controller.plugins.html
注册前端控制器插件并挂钩到调度过程的早期部分是我的工作方式。
$front = Zend_Controller_Front::getInstance();
$front->registerPlugin(new Zend_Controller_Plugin_AuthCheck());
将它放在index.php。
中class AuthCheck extends Zend_Controller_Plugin_Abstract {
public function preDispatch($request){
// Check Auth
}
}
答案 1 :(得分:3)
跨多个控制器重用的代码最好放在ActionHelper中。但是,对于您的情况,我建议写一个Controller plugin。那些挂钩到Dispatch process at various stages:
public function dispatchLoopStartup(Zend_Controller_Request_Abstract $request)
{
if(!Zend_Auth::getInstance()->hasIdentity())
{
$request->setControllerName('auth');
$request->setActionName('login');
// Set the module if you need to as well.
}
}
以上假设您使用的是Zend_Auth
authenticate and manage your user identities。
你想要一个帮助器上的插件,因为检查用户是否已登录应该是自动发生的,而不必在某处调用checkAuth()
方法。当然,没有什么能阻止你添加一个ActionHelper,例如。
class My_Helper_CheckAuth extends Zend_Controller_Action_Helper_Abstract
{
public function checkAuth()
{
return Zend_Auth::getInstance()->hasIdentity();
}
public function direct()
{
return $this->checkAuth();
}
}
在引导程序中注册助手后,您可以在每个控制器中使用它来检查用户是否已经过身份验证:
if ( $this->_helper->checkAuth() === FALSE) {
// do something
}
另见这些教程:
答案 2 :(得分:0)
尽管如此,对于这个特殊的例子,你最好的选择是(可能)使用Front Controller插件,你也可以通过扩展Zend_Controller_Action
来重用代码。如果你一直在使用Zend_Auth,下面是一个人为的例子。这将放在library/Application/Controller
中并命名为Action.php
。如果您使用的是不同的命名空间,则应交换Application目录的名称(library / [namespace] /Controller/Action.php)并相应地重命名该类。
class Application_Controller_Action extends Zend_Controller_Action
{
protected $_loggedIn;
protected $_username;
protected $_flashMessenger = null;
public function init()
{
$auth = Zend_Auth::getInstance();
$this->_loggedIn = $auth->hasIdentity();
if($this->_loggedIn)
{
$user = $auth->getIdentity();
$this->_username = $this->view->escape($user->username);
}
$this->_flashMessenger = $this->_helper->getHelper('FlashMessenger');
$this->initView();
}
...
}