【问题标题】:What is the proper way to access a model function from another model in CI4?从 CI4 中的另一个模型访问模型函数的正确方法是什么?
【发布时间】:2021-10-31 22:26:43
【问题描述】:

我正在将现有的开源应用程序从 CodeIgniter 3.x 框架转换为 CodeIgniter 4.x 框架。

根据文档,我需要执行以下步骤:

这是我的一个模型的示例

<?php

namespace App\Models;

use CodeIgniter\Model;

/**
 * Sale class
 */
class Sale extends Model
{
    /**
     * Get sale info
     */
    public function get_info($sale_id)
    {
        $this->create_temp_table(array('sale_id' => $sale_id));

        $decimals = totals_decimals();
        $sales_tax = 'IFNULL(SUM(sales_items_taxes.sales_tax), 0)';
        $cash_adjustment = 'IFNULL(SUM(payments.sale_cash_adjustment), 0)';
        $sale_price = 'CASE WHEN sales_items.discount_type = ' . PERCENT
            . " THEN sales_items.quantity_purchased * sales_items.item_unit_price - ROUND(sales_items.quantity_purchased * sales_items.item_unit_price * sales_items.discount / 100, $decimals) "
            . 'ELSE sales_items.quantity_purchased * (sales_items.item_unit_price - sales_items.discount) END';

        if($this->config->item('tax_included'))

我面临的问题是,在这样做之后,PHPStorm 在if($this-&gt;config-&gt;item('tax_included')) 上给我一个警告,告诉我“通过魔术方法访问的属性”

根据 CI4 文档,我添加了 $this-&gt;config = new Config();,但 PHPStorm 然后抱怨 $this-&gt;config 告诉我“动态声明的属性”并建议我添加一个名为 $config 的私有变量......我不认为那是我想要的。它还抱怨 Config() 说“未定义的类配置”

我还尝试在类声明上方添加以下内容:

/**
 * Sale class
 * @property Config config
 */

但我同样抱怨 Config 不是一个有效的类。

Config 模型位于 app\Models\Config.php 下,与该模型所在的目录相同。

【问题讨论】:

  • 我会在你的控制器中声明$config = new Config('File'); 然后$config-&gt;property。这就是我会做的

标签: php model-view-controller namespaces codeigniter-4


【解决方案1】:
$mymodel = new MyModel();

我建议在您的 ctl 中使用服务层和实体调用服务。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-09-24
    • 1970-01-01
    • 2015-04-12
    • 2019-12-03
    相关资源
    最近更新 更多