Laravel: 为所有模型创建一个通用函数
Laravel: Creating a common function for all models
在我的 laravel(7.x) 应用程序中,我有一个通用功能来显示所有模块中所有活动和非活动记录的计数。因此,我有义务在每个模块上重复相同的功能。
例如:Device, DeviceType, DeviceCompany, etc
模型有一个名为 _getTotal
的相同方法,并且 _getTotal
方法在任何地方都在做同样的工作。
Device.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 全局范围:
https://laravel.com/docs/5.7/eloquent#global-scopes
另一个为什么在模型中使用 traits 和 use 并将方法设置为局部范围:
public function scopePopular($query) {
return $query->where('votes', '>', 100);
}
或者您可以创建一个 classe 扩展模型默认 class 并且您的模型从这个自定义 class 扩展(具有您的自定义函数)
在我的 laravel(7.x) 应用程序中,我有一个通用功能来显示所有模块中所有活动和非活动记录的计数。因此,我有义务在每个模块上重复相同的功能。
例如:Device, DeviceType, DeviceCompany, etc
模型有一个名为 _getTotal
的相同方法,并且 _getTotal
方法在任何地方都在做同样的工作。
Device.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 全局范围: https://laravel.com/docs/5.7/eloquent#global-scopes
另一个为什么在模型中使用 traits 和 use 并将方法设置为局部范围:
public function scopePopular($query) {
return $query->where('votes', '>', 100);
}
或者您可以创建一个 classe 扩展模型默认 class 并且您的模型从这个自定义 class 扩展(具有您的自定义函数)