关于service逻辑层的实现方法请教,大家是否有更好的方法?

之前都是逻辑写在控制器里边,最近看了一些教程,目前是这样子在项目里边实现,不知道有什么缺点吗?大家是否有更好的方法?谢谢大家!

service逻辑层:

<?php

namespace App\Services;

use Illuminate\Support\Facades\DB;

/**
 * 积分服务
 * Class PointsService
 * @package App\Services
 */
class PointsService //extends BaseService
{
    //用户的积分排名
    public static function getUserPointsRank($userId)
    {
        $sql = 'select c.rowno, c.user_id, c.sumPoint from (select @rowno:=@rowno+1 as rowno, a.user_id, a.sumPoint from (select (sum(point) + sum(extra_point)) as sumPoint , user_id from yt_points_record where type=1 GROUP BY user_id ORDER BY sumPoint desc) a, (select @rowno:=0) b) c WHERE c.user_id=?';
        $rankQuery = DB::connection('mysql_wx')
            ->select($sql, [$userId]);
        $result = [];
        if ($rankQuery) {
            foreach ($rankQuery as $key => $value) {
                $result = [
                    'rank' => $value->rowno,
                    'user_id' => $value->user_id,
                    'point' => $value->sumPoint
                ];
                break;
            }
        }
        return $result;
    }
}

控制器中使用

<?php

namespace App\Http\Controllers\YtUser;

use App\Http\Controllers\Controller;
use App\Models\Sign;
use Illuminate\Http\Request;
use App\Services\PointsService;
use Auth;

class SignController extends Controller
{
        public function index(Sign $sign)
    {
       $userId = Auth::guard('ytuser')->user()->id;
    //用户排行
       $ranking = PointsService::getUserPointsRank($userId);
     }
}
什么时候开始都不晚,学到老
《L01 基础入门》
我们将带你从零开发一个项目并部署到线上,本课程教授 Web 开发中专业、实用的技能,如 Git 工作流、Laravel Mix 前端工作流等。
《L02 从零构建论坛系统》
以构建论坛项目 LaraBBS 为线索,展开对 Laravel 框架的全面学习。应用程序架构思路贴近 Laravel 框架的设计哲学。
最佳答案

没啥问题,不过一般是在 construct 函数中实例化 service的,不写 service 静态方法

protected $serivce;

public function __construct()
{
    $this->service = new PointsService();
}

public function index(Sign $sign)
{
...
    $userId = Auth::guard('ytuser')->user()->id; 
    $ranking = $this->service->getUserPointsRank($userId);
...
} 

service 的抽离就是为了 解耦复用,从这个两个角度出发去设计 service 就没问题。

2年前 评论
七年 2年前
MArtian (作者) 2年前
芝麻开门 (楼主) 2年前
讨论数量: 1

没啥问题,不过一般是在 construct 函数中实例化 service的,不写 service 静态方法

protected $serivce;

public function __construct()
{
    $this->service = new PointsService();
}

public function index(Sign $sign)
{
...
    $userId = Auth::guard('ytuser')->user()->id; 
    $ranking = $this->service->getUserPointsRank($userId);
...
} 

service 的抽离就是为了 解耦复用,从这个两个角度出发去设计 service 就没问题。

2年前 评论
七年 2年前
MArtian (作者) 2年前
芝麻开门 (楼主) 2年前

讨论应以学习和精进为目的。请勿发布不友善或者负能量的内容,与人为善,比聪明更重要!