如何覆盖模块的Yii登录URL模块?
这是基本应用程序的主要配置:
return array(
.........
// application components
'components'=>array(
'user'=>array(
// enable cookie-based authentication
'allowAutoLogin'=>true,
'loginUrl' => '/site/login',
),
..........
);
然后我有代理模块,我希望在这个模块中登录URL不同,登录方法也不同。
class AgentModule extends CWebModule {
public function init() {
// this method is called when the module is being created
// you may place code here to customize the module or the application
// import the module-level models and components
$this->setImport(array(
'agent.models.*',
'agent.components.*',
));
$this->defaultController = 'default';
$this->layoutPath = Yii::getPathOfAlias('agent.views.layout');
$this->components = array(
'user' => array(
'class' => 'AgentUserIdentity',
'loginUrl' => '/agent/default/login',
)
);
}
.......
但我不知道为什么这不起作用。 请帮忙......(T.T)
答案 0 :(得分:2)
使用此代码
class AgentModule extends CWebModule { public $assetsUrl; public $defaultController = 'Login'; public function init() { // this method is called when the module is being created $this->setComponents(array( 'errorHandler' => array( 'errorAction' => 'admin/login/error'), 'user' => array( 'class' => 'CWebUser', 'loginUrl' => Yii::app()->createUrl('admin/login'), ) ) ); Yii::app()->user->setStateKeyPrefix('_admin'); // import the module-level models and components $this->setImport(array( 'admin.models.*', 'admin.components.*', ) ); } public function beforeControllerAction($controller, $action) { if(parent::beforeControllerAction($controller, $action)) { // this method is called before any module controller //action is performed $route = $controller->id . '/' . $action->id; $publicPages = array( 'login/login', 'login/error', ); if (Yii::app()->user->name !== 'admin' && !in_array($route, $publicPages)) { Yii::app()->getModule('admin')->user->loginRequired(); } else { return true; } } else return false; } }
答案 1 :(得分:1)
在您的问题的第二个代码块中,您为模块user
定义了AgentModule
组件。
如果我理解正确,您在视图或控制器中的哪个位置使用Yii::app()->user->loginUrl
,对吧?要在AgentModule
中定义网址,您应该在Yii::app()->user->controller->module->user
上下文中使用AgentModule
但 。
让它与众不同的最简单方法是为模块和app定义某个登录网址,并使用此预定义网址。
在此处阅读有关模块组件的信息:http://www.yiiframework.com/wiki/27/how-to-access-a-component-of-a-module-from-within-the-module-itself/
答案 2 :(得分:0)
class WebUser extends CWebUser { public $module = array(); public function init() { parent::init(); if(isset($this->module['loginUrl'])){ if(!isset($this->module['moduleId'])){ throw new Exception('moduleId Must defined'); }else{ $moduleId = Yii::app()->controller->module->id; if($moduleId == $this->module['moduleId']){ #$this->loginUrl = Yii::app()->request->redirect(Yii::app()->createUrl($this->module['loginUrl'])); $this->loginUrl = array($this->module['loginUrl']); } } } } }
after that you need to do some changes under config file i.e return array( 'components' => array( 'user' => array( 'allowAutoLogin' => true, 'class' => 'WebUser', 'module' => array( 'loginUrl' => '/r_admin', 'moduleId' => 'r_admin' ) ), ) );