Laravel:为所有模型创建一个通用函数

标签 laravel methods module repeat

在我的 laravel(7.x) 应用程序中,我有一个通用功能来显示所有模块中所有事件和非事件记录的计数。因此,我有义务在每个模块上重复相同的功能。

例如:Device、DeviceType、DeviceCompany 等 模型有一个相同的方法称为 _getTotal 并且 _getTotal 方法在任何地方都做同样的事情工作。

设备.php

class Device extends Model
{
    protected $table = 'devices';

    ...

    public function _getTotal($status = \Common::STATUS_ACTIVE)
    {
        return self::where([
            'status' => $status
        ])->count() ?? 0;
    }
}

DeviceType.php

class DeviceType extends Model
{
    protected $table = 'device_types';

    ...

    public function _getTotal($status = \Common::STATUS_ACTIVE)
    {
        return self::where([
            'status' => $status
        ])->count() ?? 0;
    }
}

我试图将此方法放在 Base Model 中,但我认为这可能不是一个好的做法。我说得对吗?
有什么方法可以使此方法 _getTotal 成为所有模块的通用方法..?

最佳答案

您可以将此方法移至特征并将该特征包含在所有需要此方法的类中。

trait DeviceStatusTotal
{
    public function _getTotal($status = \Common::STATUS_ACTIVE)
    {
        return self::where([
            'status' => $status
        ])->count() ?? 0;
    }
}

DeviceType.php

class DeviceType extends Model
{
    use DeviceStatusTotal;

    protected $table = 'device_types';

    // ...
}

关于Laravel:为所有模型创建一个通用函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61018868/

相关文章:

laravel - 创建了 serviceprovider 然后手动删除了该文件并收到错误

reflection - 在 config/main.php 中找不到 Yii2 模块(不在/vendor 文件夹下)类

module - 如何从 Rust 模块中获取公共(public)元素?

c# - 将方法作为参数传递

从另一个方法调用时,Javascript 单例私有(private)函数不会访问对象属性

java - 如何在另一种方法中使用来自一种方法的用户输入字符串?

golang 模块和本地包

php - 在 Laravel 5 (Lumen) 中使用基本路径

laravel - Laravels 的 DD 辅助功能是否正常工作?

php - Laravel undefined variable 异常与 vue.js