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

MrS*_*ngh 2 methods module repeat laravel

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

例如:Device, DeviceType, DeviceCompany, etc模型有一个相同的方法被调用,_getTotal并且到处都是_getTotal方法在都在做同样的工作。

设备.php

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

    ...

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

设备类型.php

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

    ...

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

我试图将这种方法放入,Base Model但我认为这可能不是一个好的做法。我对吗..?
有没有办法让这个方法_getTotal成为所有模块的通用方法..?

Dan*_*Dan 5

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

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

设备类型.php

class DeviceType extends Model
{
    use DeviceStatusTotal;

    protected $table = 'device_types';

    // ...
}
Run Code Online (Sandbox Code Playgroud)