【问题标题】:CodeIgniter: Update public variable in MY_Controller from modelCodeIgniter:从模型更新 MY_Controller 中的公共变量
【发布时间】:2013-12-04 18:07:11
【问题描述】:

我正在使用 CodeIgniter 开发一个项目。我用自定义的 MY_Controller 扩展了 CI 的基本 Controller 类。 MY_Controller 有一个身份验证标志变量$auth = FALSE。在需要身份验证的页面上,我调用我的auth_model->runAuth() 函数来运行检查,如果所有检查都通过,这个标志应该更新为TRUE。由于某种原因,我无法使用$this->auth = TRUE 直接从auth_model 更新MY_Controller 中的$auth 变量,但我必须先将检查结果传回页面控制器,然后再更新MY_Controller 中的$auth 变量。任何想法如何直接从模型更新 MY_Controller 中的$auth 标志而不通过控制器?非常感谢您!

【问题讨论】:

  • 更新:MY_Controller 中的 $auth 变量是公开的

标签: php codeigniter this codeigniter-2


【解决方案1】:

最好的办法是直接通过这样的方法调用来分配标志

$this->auth = $this->auth_model->runAuth();

在 MY_Controller 类中!方法runAuth()不需要大改:

不要调用$auth = TRUEFALSE,而是像这样返回真或假:

public function runAuth()
{
    // do stuff
    return true; // or false depending on success.
}

希望对您有所帮助。否则,您将需要以某种方式引用 MY_Controller 对象。例如:

$this->auth_model->runAuth($this);

现在在你的方法中:

public function runAuth(MY_Controller $myctrl)
{
    // do stuff
    $myctrl->auth = true; // or false

}

另一种选择是使用静态字段:

class MY_Controller extends Controller
{
    public static $auth = false;
    // the other stuff
}

现在您可以在没有对象引用的情况下更新它:

public function runAuth()
{
    // do stuff
    MY_Controller::$auth = true;
}

在您的模型中,您可以像这样访问它:

if (static::$auth) echo "Boo Yeah!";

【讨论】:

  • 非常感谢克里斯蒂安的帮助。我选择了您的第一个选项,直接通过 $this->auth 分配结果。但是了解其他几个选项也很有帮助。再次感谢! (Grüsse aus Raleigh nach Hamburg)
  • PS:使用 static::$auth(最后一个或您的选项)调用变量的状态在控制器和模型中可以正常工作,但不能直接在视图中。因此我决定选择选项 A。干杯。
  • 从视图中你必须再次这样调用:MY_Controller::$auth! (Viele Grüße zurück :D)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-07-03
  • 2020-08-02
  • 1970-01-01
  • 1970-01-01
  • 2012-05-08
相关资源
最近更新 更多