5

我正在尝试在模块内创建一个小部件,然后从模块的“外部”加载该小部件。更具体地说,我正在使用其他人编写的用户模块。我不想有一个单独的页面来显示登录表单,因此我尝试制作一个 CPortlet/widget(混淆)来显示登录表单。基本上,我已经将代码从 LoginController 移到了那个小部件中。然后我尝试在一些随机页面上显示小部件

<?php $this->widget('user.components.LoginForm'); ?>

但是,我收到一个错误

CWebApplication does not have a method named "encrypting".

在这一行的 UserIdentity 类中:

else if(Yii::app()->controller->module->encrypting($this->password)!==$user->password)

发生这种情况是因为我基本上是在尝试在应用程序而不是模块的上下文中执行此代码。因此,“Yii::app()->controller->module”技巧并没有按预期工作。

  1. 我究竟做错了什么:-\
  2. 有没有更好的方法来实现这一点。即在其他页面中显示该登录表单,这通常通过访问用户模块(用户/登录)中的登录控制器来显示,还是小部件是正确的做法?

谢谢。

4

2 回答 2

9

快速解决方案

好的,所以我只是结束了

Yii::app()->getModule('user')->encrypting($this->password)

代替

Yii::app()->controller->module->encrypting($this->password)

请注意,现在该模块必须在主配置中称为“用户”,但我认为这允许更大的灵活性。即我们并不一定只能在模块中使用模块功能。

关于在模块范围之外显示小部件的其他见解

在玩了更多之后,这就是我所做的。在 UserModule.php 我创建了一个方法

public static function id() {
    return 'user';
}

然后在我需要我使用的模块的任何地方

Yii::app()->getModule(UserModule::id())->encrypting($this->password)

我不喜欢与模块相关的许多导入,例如:

'application.modules.user.models.*',
'application.modules.user.components.*',

因为我们已经在 UserModule.php 中有这些导入:

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(
        'user.models.*',
        'user.components.*',
    ));
}

因此,当您知道某些功能将在模块之外使用时,确保模块已加载很重要。例如,在我试图在其中一个模块控制器中显示 NOT 的 LoginForm 小部件中,我有这行代码:

$model = new UserLogin;

然而,UserLogin 是 User 模块内部的一个模型,为了能够自动加载这个模型,我们首先必须确保模块已经初始化:

$module = Yii::app()->getModule(UserModule::id());
$model = new UserLogin;

如果您像我一样被整个模块概念所困扰,我希望这会有所帮助。 http://www.yiiframework.com/forum/index.php?/topic/6449-access-another-modules-model/很有用但很难找到 =)

于 2010-04-14T18:13:58.397 回答
1

您最好将该 encrypting() 移动到扩展 CUserIdentity 的 MyUserIdentiy 类中。无论您使用什么代码,他们将方法放在控制器中都是一个坏主意,因此您无法重用该代码。

登录表单仍应发布到用户/登录控制器,但我猜他们使用 Yii 的标准登录代码,您可能需要修改它以使用 MyUserIdentity。

于 2010-06-12T06:10:02.937 回答