gpt4 book ai didi

php - Codeigniter 3 创建动态方法

转载 作者:行者123 更新时间:2023-11-29 21:52:27 25 4
gpt4 key购买 nike

我正在一个应用程序中工作,我需要动态创建数据库表,我就是这样做的。但现在我需要一种优雅的方式来访问数据库表。这就是我的问题

在常规实践中,我们创建一个数据库表并创建一个类来映射表(ORM)。但在这种情况下我不能采取这种方法。这就是我到目前为止所做的..

我正在扩展 Crud 模型中的 MY_Model,我尝试在 set_table() 方法中设置数据库表名称。效果很好。

class Crud extends MY_Model
{

private $customer_id;

public function __construct()
{

parent::__construct();

$this->_database = $this->load->database('customer', TRUE);
}


public function set_table($customer_id, $table_name)
{
$this->customer_id = $customer_id;
$this->_table = 'tbl_' . $customer_id . '_' . $table_name;
}
}

Test.php 用于测试代码的 Controller 。

class Test extends CI_Controller
{

public function index(){

$this->load->model('editor/crud');

var_dump($this->crud->set_table(1, 'alpha'));
var_dump($this->crud->get_all());
}
}

但我需要一种优雅的方式来访问该表。例如。

$this->alpha->get_all()

或者

$this->crud->alpha->get_all()

很容易理解并且很有意义。 PHP 真的可以做到吗?任何帮助将非常感激。

最佳答案

我猜你可以这样做:

class Test extends CI_Controller
{

public function index(){

$this->load->model('editor/crud');
$this->crud->set_table(1, 'alpha');

$this->alpha = clone $this->crud; // in case you use set_table again

$info = this->alpha->get_all();

}
}

如果我没记错的话,你也应该能够在模型中做到这一点。

public function set_table($customer_id, $table_name)
{

$this->customer_id = $customer_id;
$this->_table = 'tbl_' . $customer_id . '_' . $table_name;
$this->{$table_name} = clone $this;
}

然后像这样访问它:$this->crud->alpha->get_all();

关于php - Codeigniter 3 创建动态方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33497711/

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