服务类
所有的业务逻辑都可以写在service中,继承服务类基类BaseService,以admin模块的userService为例
<?php
namespace app\admin\service;
use tmcore\base\BaseService;
class UserService extends BaseService
{
public function test {
}
}内置方法
self::方法(参数...)静态调用方法
/**
* 设置搜索条件
* 快速返回查询数组
*/
protected static function getSearchData(array $search, $extend = [], $data = [])search参数详解
@符号兼容前端字段与数据库不一致状况。@前表示前端参数字段,@后表示数据库字段。
| 搜索条件 | 搜索字段 | 支持@ | 说明 |
|---|---|---|---|
| = | 字段数组 | 是 | 等于 |
| <> | 字段数组 | 是 | 不等于 |
| > | 字段数组 | 是 | 大于 |
| >= | 字段数组 | 是 | 大于等于 |
| < | 字段数组 | 是 | 小于 |
| <= | 字段数组 | 是 | 小于等于 |
| in | 字段数组 | 是 | in查询 |
| %like% | 字段数组 | 是 | 模糊查询 |
| %like | 字段数组 | 是 | 左模糊查询 |
| like% | 字段数组 | 是 | 右模糊查询 |
| between | 字段数组 | 否 | 区间查询 |
| datetime | 字段数组 | 是 | 时间范围查询(兼容前端datetime组件) |
| find_in_set | 字段数组 | 是 | find_in_set查询 |
使用示例
//前端传参
status = 1
num = 18
nickname = '小明'
account = 'admin'
start_time = 1740189856
end_time = 1761098655
create_time = '2025-02-05 00:00:00 - 2025-03-22 00:00:00'
data_limit = '1,2,3'
// 使用示例
self::getSearchData([
'=' => ['status'],
'>' => ['num@age'],
'%like%' => ['nickname','account'],
'between' => [
'add_time' => 'start_time|end_time'
],
'datetime' => ['create_time'],
'find_in_set' => ['data_limit@data_list'],
]);
//返回查询数组
[
['status', '=', 1],
['age', '>', 18],
['nickname', '%like%', '小明'],
['account', '%like%', 'admin'],
['add_time', 'between', [1740189856,1761098655]],
['create_time', '>=', 1738684800],
['create_time', '<=', 1742572800],
['data_list', 'find_in_set', '1,2,3']
]/**
* 获取分页参数
*/
protected static function getPageData($params = [])
/**
* 开启事务
*/
public static function beginTrans()
/**
* 提交事务
*/
public static function commitTrans()
/**
* 关闭事务
*/
public static function rollbackTrans()
/**
* 设置错误信息
*/
public static function setError($errorMsg = '操作失败,请稍候再试!', $errorCode = 1000, $rollback = false)
/**
* 获取错误信息
*/
public static function getError($defaultMsg = '操作失败,请稍候再试!')
/**
* 获取错误码
*/
public static function getErrorCode($defaultCode = 1000)调用示例
服务类调用
namespace app\admin\service;
use tmcore\base\BaseService;
use app\common\model\user\User;
class UserService extends BaseService
{
public static function getList(): array
{
// 搜索条件
$searchParam = [
'=' => ['status'],
'%like%' => ['nickname','account'],
'datetime' => ['create_time'],
];
$where = self::getSearchData($searchParam);
// 返回分页数据
$list = User::page($where, self::getPageData(),'*', ['id' => 'desc'], ['status_desc']);
foreach ($list['list'] as &$item) {
$item['avatar'] = get_file_url($item['avatar']);
}
return $list;
}
public static function add(array $params)
{
self::beginTrans();
try{
// 执行程序
self::commitTrans();
return true;
} catch (\Exception $e) {
self::rollbackTrans();
return self::setError($e->getMessage());
}
}
}