php - 尝试通过制作可重用功能来减少代码点火器中的代码

标签 php mysql codeigniter

在我的主 Controller 中,我有一堆访问同一组代码的函数。我一直在尝试通过创建一个可重用函数来获取我需要的数据,然后将其传递给另一个函数调用的函数,从而减少 Controller 的大小。 _getSales() 函数将在同一 Controller 内的大约 30 个函数中使用。基本上不是将这些行添加到每个函数。完成后,我可能还会在该私有(private)函数中添加大约 5 个其他变量。现在 View 中的销售变量显示为空。

现有 Controller

function _getSales() {
    $sales = $this -> sale_model -> getSalesById();
    $data['sales'] = $sales;
}

function home() {
    $this -> _getSales();
    $data['pageName'] = 'home';
    $this -> load -> view($currentPage, $data);
}

最佳答案

_getSales() 函数中的 data['sales'] 变量无法在 home() 函数中访问。所以试试

function _getSales() {
    $sales = $this -> sale_model -> getSalesById();
    return $sales;
}

function home() {
    $data['sales'] = $this -> _getSales();
    $data['pageName'] = 'home';
    $this -> load -> view($currentPage, $data);
}

此外,模型函数看起来像是通过 id 获取销售额,而且您似乎没有向它传递任何参数

关于php - 尝试通过制作可重用功能来减少代码点火器中的代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21238818/

相关文章:

CodeIgniter:在同一 Controller 中加载多个模型

php - 如何使用按钮传递 php 变量(id)到其他表单

php - MySQLi 准备好的语句和事务

javascript - 如何使用 wp_localize_script 从另一个 php 文件传递​​参数

php - 来自 $_SERVER ['HTTP_REFERER' ] 的结果,当 referer header 未发送到服务器时

javascript - Json 编码 php mysql 查询

php - "cache" Eloquent 查询的最佳方式

javascript - 根据两个下拉菜单中的值填充并显示 html 表格

php - 如何检查codeigniter框架的版本?

php - 公共(public)函数与 CodeIgniter 中的函数