gpt4 book ai didi

php - 如何在 CodeIgniter 中销毁和重新加载模型?

转载 作者:行者123 更新时间:2023-12-02 04:38:28 24 4
gpt4 key购买 nike

假设我的 Controller 中某处有一个循环:

$continue = true;
while ($continue == true) {
$this->load->model('foo');
$this->foo->doSomething();
if ($this->foo->someCondition() == true) $continue = false;
unset($this->foo); //not working
//if not continue to do it
}

在这个 while 循环中,我需要创建这个 foo 模型的实例,它将继续运行,直到满足某些条件($continue 将是设置为 false)

为了确保我在这个循环中每次都创建一个 foo 的实例,我尝试使用 unset() 方法(或设置 $this-> foo = null) 来破坏 foo 模型,不幸的是它不起作用(错误消息:Call to a member function doSomething on a non-object)

最佳答案

通常这不是问题,因为 CI 将模型用作静态类,但在单元测试时我发现如果我创建了一个模型方法的模拟,之后我需要重新加载模型。

首先,在文件 application/core/MY_Loader.php 中使用 MY_Loader 扩展 CI_Loaded

class MY_Loader extends CI_Loader
{

/**
* Returns true if the model with the given name is loaded; false otherwise.
*
* @param $name
* @return bool
*/
public function is_model_loaded($name): bool
{
return in_array($name, $this->_ci_models, TRUE);
}

/**
* removes the model from the list of models
* @param $model
*/
public function unload_model($model)
{
if ($this->is_model_loaded($model))
{
$this->_ci_models = array_diff($this->_ci_models, array($model));
}
}
}

之后,您可以在单元测试代码中取消设置 CI 模型。通过从 _ci_models 数组中删除它,CI 在尝试加载时将找不到它。因此,单元测试设置将如下所示:

public function setUp()
{
$this->CI = &get_instance();
$this->CI->assets_model=NULL;
unset($this->CI->assets_model);
$this->CI->unload_model('assets_model');
$this->CI->load->model('misc/Assets_model');
}

关于php - 如何在 CodeIgniter 中销毁和重新加载模型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21409966/

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